-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#12: Move workflow interface/struct to separate file
- Loading branch information
Showing
2 changed files
with
74 additions
and
73 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
package formatter | ||
|
||
import ( | ||
"encoding/xml" | ||
"fmt" | ||
"os" | ||
) | ||
|
||
type Workflow interface { | ||
Execute() (err error) | ||
SetConfig(c *Config) | ||
} | ||
|
||
type MainWorkflow struct { | ||
Config *Config | ||
} | ||
|
||
func (w *MainWorkflow) SetConfig(c *Config) { | ||
w.Config = c | ||
} | ||
|
||
// Execute is the core of the application which executes required steps | ||
// one-by-one to achieve formatting from input -> output. | ||
func (w *MainWorkflow) Execute() (err error) { | ||
// If no output file has been provided all content | ||
// goes to the STDOUT | ||
if w.Config.OutputFile == "" { | ||
w.Config.Writer = os.Stdout | ||
} else { | ||
// Open output file for writing, produces an error if file already exists | ||
// This won't work if user redirects output to some file using ">" or ">>" | ||
f, err := os.OpenFile(string(w.Config.OutputFile), os.O_CREATE|os.O_EXCL|os.O_WRONLY, os.ModePerm) | ||
if err != nil { | ||
return err | ||
} | ||
defer f.Close() | ||
w.Config.Writer = f | ||
} | ||
|
||
// Reading & parsing the input file | ||
NMAPRun, err := w.parse() | ||
if err != nil { | ||
return | ||
} | ||
|
||
// Build template data with NMAPRun entry & various output options | ||
templateData := TemplateData{ | ||
NMAPRun: NMAPRun, | ||
OutputOptions: w.Config.OutputOptions, | ||
} | ||
|
||
// Getting new instance of formatter based on provided config | ||
formatter := New(w.Config) | ||
|
||
// This part usually should not happen | ||
if formatter == nil { | ||
return fmt.Errorf("no formatter is defined") | ||
} | ||
|
||
err = formatter.Format(&templateData) | ||
return | ||
} | ||
|
||
// parse reads & unmarshalles the input file into NMAPRun struct | ||
func (w *MainWorkflow) parse() (NMAPRun NMAPRun, err error) { | ||
input, err := os.ReadFile(string(w.Config.InputFile)) | ||
if err != nil { | ||
return | ||
} | ||
if err = xml.Unmarshal(input, &NMAPRun); err != nil { | ||
return | ||
} | ||
return NMAPRun, nil | ||
} |