Skip to content

Commit

Permalink
Merge pull request #1 from dpanic/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
dpanic authored Aug 17, 2021
2 parents 7d41f9e + df32753 commit 0ae369f
Show file tree
Hide file tree
Showing 7 changed files with 193 additions and 51 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ bash <(curl -L -Ss https://github.com/dpanic/patchfiles/releases/latest/download
* ~~implement revert by category~~
* ~~implement patch by file name~~
* ~~implement revert by file name~~
* implement help page %
* ~~implement help page~~

* implement github ci/cd %
* docker %
Expand Down
94 changes: 94 additions & 0 deletions generator/footer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package generator

import (
"bytes"
"os"
"strings"
"text/template"

"go.uber.org/zap"
)

type Footer struct {
Names []string
Categories []string
ScriptFor string
PatchFilesControlFile string
}

const (
templateFooter = `
function help_me() {
echo -e "\n\n";
echo "******************";
echo "*** How to use ***";
echo "******************";
echo -e "\n";
echo "Available categories are:";
{{ range $category := .Categories }}
echo "* {{$category}}";
{{ end }}
echo -e "\n";
echo "Available patches are:";
{{ range $name := .Names }}
echo "* {{$name}}";
{{ end }}
echo "Examples:";
echo "./patch.sh all";
echo "./patch.sh security";
echo "./patch.sh sshd";
echo "./revert.sh sshd";
}
if [[ "$category" == "" ]]; then
echo "Choose what to patch. Consult help pages.";
help_me;
exit 1;
fi;
{{ if eq .ScriptFor "PATCHING" }}
echo 1 > {{.PatchFilesControlFile}};
{{ end }}
{{ if eq .ScriptFor "REVERTING" }}
rm -rf > {{.PatchFilesControlFile}};
{{ end }}
`
)

func (generator *Generator) writeFooter(fd *os.File, scriptFor string) (err error) {
logger := generator.Log.WithOptions(zap.Fields())
logger.Debug("attempt to write footer",
zap.String("scriptFor", scriptFor),
)

var (
buf = new(bytes.Buffer)
)

tpl, err := template.New("template").Parse(templateFooter)

obj := Footer{
ScriptFor: scriptFor,
Names: generator.names,
Categories: generator.categories,
PatchFilesControlFile: patchFilesControlFile,
}

t := template.Must(tpl, err)
err = t.Execute(buf, obj)
if err != nil {
return
}

res := buf.String()
res = strings.ReplaceAll(res, "\t", "")

fd.WriteString(res + "\n")
fd.Sync()

return
}
96 changes: 66 additions & 30 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,83 +9,119 @@ import (
"go.uber.org/zap"
)

var (
fdPatch *os.File
fdRevert *os.File
)
type Generator struct {
Log *zap.Logger
Environment string

n map[string]string
names []string
c map[string]string
categories []string
fdPatch *os.File
fdRevert *os.File
}

// Open opens both patch and revert file descriptors
func Open(log *zap.Logger, environment string) {
func (generator *Generator) Open() {
files := []string{
"patch",
"revert",
}

generator.n = make(map[string]string)
generator.c = make(map[string]string)

for _, name := range files {
fileLoc := fmt.Sprintf("%s.sh", name)
if environment == "dev" {
if generator.Environment == "dev" {
fileLoc = fmt.Sprintf("%s_dev.sh", name)
}
fd, err := os.Create(fileLoc)
os.Chmod(fileLoc, 0755)

if name == "patch" {
fdPatch = fd
generator.fdPatch = fd
} else {
fdRevert = fd
generator.fdRevert = fd
}

if err != nil {
log.Error("error in opening file",
generator.Log.Error("error in opening file",
zap.Error(err),
zap.String("fileLoc", fileLoc),
)
} else {
var head string

action := fmt.Sprintf("%sING", strings.ToUpper(name))
head, err = generateHeader(action, environment)
err = generator.writeHeader(fd, action)
if err != nil {
log.Error("error in generating header",
generator.Log.Error("error in writing header",
zap.String("fileLoc", fileLoc),
zap.Error(err),
)
}

fd.WriteString(head + "\n")
fd.Sync()
}
}

}

// Close closes opened file descriptors for
func Close() {
if fdPatch != nil {
fdPatch.WriteString(fmt.Sprintf("echo 1 > %s\n", patchFilesControlFile))
fdPatch.Sync()
fdPatch.Close()
func (generator *Generator) Close() {
for name := range generator.n {
generator.names = append(generator.names, name)
}
for category := range generator.c {
generator.categories = append(generator.categories, category)
}

if fdRevert != nil {
fdRevert.WriteString(fmt.Sprintf("rm -rf %s\n", patchFilesControlFile))
fdRevert.Sync()
fdRevert.Close()
files := []string{
"patch",
"revert",
}
for _, name := range files {
action := fmt.Sprintf("%sING", strings.ToUpper(name))
var err error
if name == "patch" {
err = generator.writeFooter(generator.fdPatch, action)

} else {
err = generator.writeFooter(generator.fdRevert, action)
}

if err != nil {
generator.Log.Error("error in writing footer",
zap.Error(err),
)
}
}

if generator.fdPatch != nil {
generator.fdPatch.Sync()
generator.fdPatch.Close()
}

if generator.fdRevert != nil {
generator.fdRevert.Sync()
generator.fdRevert.Close()
}
}

// Save generates output for a patch and revert
func Write(p *parser.Result, environment string, log *zap.Logger) {
err := writePatch(p, environment, log)
func (generator *Generator) Write(p *parser.Result) {
generator.n[p.Name] = ""
for _, category := range p.Patch.Categories {
generator.c[category] = ""
}

err := generator.writePatch(p)
if err != nil {
log.Error("error in writing patch file",
generator.Log.Error("error in writing patch file",
zap.Error(err),
)
}

err = writeRevert(p, environment, log)
err = generator.writeRevert(p)
if err != nil {
log.Error("error in writing revert file",
generator.Log.Error("error in writing revert file",
zap.Error(err),
)
}
Expand Down
24 changes: 15 additions & 9 deletions generator/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import (
"strings"
"text/template"
"time"

"go.uber.org/zap"
)

const (
templateHeader = `
#!/usr/bin/env bash
templateHeader = `#!/usr/bin/env bash
#
# PATCHFILES SCRIPT FOR {{.ScriptFor}}
#
Expand All @@ -23,10 +24,6 @@ const (
args=("$@")
category="${args[0]}"
if [[ "$category" == "" ]]; then
echo "Choose what to patch. Consult help pages.";
exit 1;
fi;
{{ if eq .ScriptFor "PATCHING" }}
if test -f "{{.PatchFilesControlFile}}"; then
Expand Down Expand Up @@ -55,7 +52,12 @@ type Header struct {
}

// generateHeader generates header based on input parameters
func generateHeader(scriptFor, environment string) (res string, err error) {
func (generator *Generator) writeHeader(fd *os.File, scriptFor string) (err error) {
logger := generator.Log.WithOptions(zap.Fields())
logger.Debug("attempt to write footer",
zap.String("scriptFor", scriptFor),
)

built := time.Now().UTC().Format("2006-01-02 15:04:05 -07:00")

author := os.Getenv("AUTHOR")
Expand All @@ -71,7 +73,7 @@ func generateHeader(scriptFor, environment string) (res string, err error) {
Version: version,
Built: built,
ScriptFor: scriptFor,
Environment: environment,
Environment: generator.Environment,
PatchFilesControlFile: patchFilesControlFile,
}

Expand All @@ -87,7 +89,11 @@ func generateHeader(scriptFor, environment string) (res string, err error) {
return
}

res = buf.String()
res := buf.String()
res = strings.ReplaceAll(res, "\t", "")

fd.WriteString(res)
fd.Sync()

return
}
8 changes: 4 additions & 4 deletions generator/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ const (
`
)

func writePatch(p *parser.Result, environment string, log *zap.Logger) (err error) {
logger := log.WithOptions(zap.Fields(
func (generator *Generator) writePatch(p *parser.Result) (err error) {
logger := generator.Log.WithOptions(zap.Fields(
zap.String("fileLoc", *p.FileLoc),
zap.String("name", p.Name),
))
Expand Down Expand Up @@ -125,7 +125,7 @@ func writePatch(p *parser.Result, environment string, log *zap.Logger) (err erro

body := buf.String()
body = strings.ReplaceAll(body, "\t", "")
fdPatch.WriteString(body + "\n")
fdPatch.Sync()
generator.fdPatch.WriteString(body + "\n")
generator.fdPatch.Sync()
return
}
8 changes: 4 additions & 4 deletions generator/revert.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ const (
`
)

func writeRevert(p *parser.Result, environment string, log *zap.Logger) (err error) {
logger := log.WithOptions(zap.Fields(
func (generator *Generator) writeRevert(p *parser.Result) (err error) {
logger := generator.Log.WithOptions(zap.Fields(
zap.String("fileLoc", *p.FileLoc),
zap.String("name", p.Name),
))
Expand Down Expand Up @@ -107,8 +107,8 @@ func writeRevert(p *parser.Result, environment string, log *zap.Logger) (err err

body := buf.String()
body = strings.ReplaceAll(body, "\t", "")
fdRevert.WriteString(body + "\n")
fdRevert.Sync()
generator.fdRevert.WriteString(body + "\n")
generator.fdRevert.Sync()

return
}
12 changes: 9 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@ func main() {
if environment == "" {
environment = "dev"
}
generator.Open(log, environment)

gen := generator.Generator{
Log: log,
Environment: environment,
}
gen.Open()

// setup context timeout
ctx := context.Background()
Expand Down Expand Up @@ -91,20 +96,21 @@ func main() {
))
logger.Info("received result")

generator.Write(r, environment, log)
gen.Write(r)
stats["good"] += 1
stats["total"] += 1

case <-ctx.Done():
log.Info("context is done")

gen.Close()

log.Debug("processing is done. stats",
zap.Int("total", stats["total"]),
zap.Int("good", stats["good"]),
zap.Int("errors", stats["errors"]),
)

generator.Close()
os.Exit(0)
}
}
Expand Down

0 comments on commit 0ae369f

Please sign in to comment.