|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/vdjagilev/nmap-formatter/formatter" |
| 8 | +) |
| 9 | + |
| 10 | +// validate is checking input from the command line |
| 11 | +func validate(config formatter.Config) error { |
| 12 | + if !config.OutputFormat.IsValid() { |
| 13 | + return fmt.Errorf("not valid format: %s, please choose html/json/md/csv", config.OutputFormat) |
| 14 | + } |
| 15 | + |
| 16 | + err := validateIOFiles(config) |
| 17 | + if err != nil { |
| 18 | + return err |
| 19 | + } |
| 20 | + |
| 21 | + return validateTemplateConfig(config) |
| 22 | +} |
| 23 | + |
| 24 | +// validateIOFiles validates whether Input files and output files exists/have permissions to be created |
| 25 | +func validateIOFiles(config formatter.Config) error { |
| 26 | + // Checking if xml file is readable |
| 27 | + if !config.InputFileConfig.IsStdin { |
| 28 | + err := config.InputFileConfig.ExistsOpen() |
| 29 | + if err != nil { |
| 30 | + return fmt.Errorf("could not open XML file: %v", err) |
| 31 | + } |
| 32 | + } |
| 33 | + // Checking if output file can be created and does not exist already |
| 34 | + // If OutputFile == "", it means that all output goes to stdout, no check needed |
| 35 | + if config.OutputFile != "" { |
| 36 | + outputFile, err := os.OpenFile(string(config.OutputFile), os.O_EXCL|os.O_WRONLY|os.O_CREATE, os.ModePerm) |
| 37 | + if err != nil { |
| 38 | + return fmt.Errorf("unable to create output file: %s", err) |
| 39 | + } |
| 40 | + outputFile.Close() |
| 41 | + os.Remove(string(config.OutputFile)) |
| 42 | + } |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +// validateTemplateConfig validates template config, if it has adequate output format configs and is readable |
| 47 | +func validateTemplateConfig(config formatter.Config) error { |
| 48 | + // Checking if custom template is existing and readable and |
| 49 | + if config.TemplatePath != "" { |
| 50 | + switch config.OutputFormat { |
| 51 | + case formatter.CSVOutput: |
| 52 | + case formatter.JSONOutput: |
| 53 | + return fmt.Errorf("cannot set templates for the formats other than HTML or Markdown") |
| 54 | + } |
| 55 | + file, err := os.Open(config.TemplatePath) |
| 56 | + if err != nil { |
| 57 | + return fmt.Errorf("could not read template file: %v", err) |
| 58 | + } |
| 59 | + defer file.Close() |
| 60 | + } |
| 61 | + return nil |
| 62 | +} |
0 commit comments