Skip to content

Commit

Permalink
Fix issues reported by golangci-lint
Browse files Browse the repository at this point in the history
Signed-off-by: Khosrow Moossavi <khos2ow@gmail.com>
  • Loading branch information
khos2ow committed Mar 16, 2021
1 parent 0c25f7b commit 3cc4f44
Show file tree
Hide file tree
Showing 15 changed files with 105 additions and 68 deletions.
12 changes: 10 additions & 2 deletions internal/cli/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@ func defaultSections() sections {
}
}

func (s *sections) validate() error {
func (s *sections) validate() error { //nolint:gocyclo
// NOTE(khos2ow): this function is over our cyclomatic complexity goal.
// Be wary when adding branches, and look for functionality that could
// be reasonably moved into an injected dependency.

for _, item := range s.Show {
switch item {
case allSections[0], allSections[1], allSections[2], allSections[3], allSections[4], allSections[5], allSections[6], allSections[7]:
Expand Down Expand Up @@ -326,7 +330,11 @@ func (c *Config) process() {
}

// validate config and check for any misuse or misconfiguration
func (c *Config) validate() error {
func (c *Config) validate() error { //nolint:gocyclo
// NOTE(khos2ow): this function is over our cyclomatic complexity goal.
// Be wary when adding branches, and look for functionality that could
// be reasonably moved into an injected dependency.

// formatter
if c.Formatter == "" {
return fmt.Errorf("value of 'formatter' can't be empty")
Expand Down
6 changes: 5 additions & 1 deletion internal/cli/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ func (c *cfgreader) exist() (bool, error) {
return true, nil
}

func (c *cfgreader) parse() error {
func (c *cfgreader) parse() error { //nolint:gocyclo
// NOTE(khos2ow): this function is over our cyclomatic complexity goal.
// Be wary when adding branches, and look for functionality that could
// be reasonably moved into an injected dependency.

if ok, err := c.exist(); !ok {
return err
}
Expand Down
10 changes: 4 additions & 6 deletions internal/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func PreRunEFunc(config *Config) func(*cobra.Command, []string) error {

// root command must have an argument, otherwise we're going to show help
if formatter == "root" && len(args) == 0 {
cmd.Help() //nolint:errcheck
cmd.Help() //nolint:errcheck,gosec
os.Exit(0)
}

Expand All @@ -63,14 +63,12 @@ func PreRunEFunc(config *Config) func(*cobra.Command, []string) error {
}
// config is not provided and file not found, only show an error for the root command
if formatter == "root" {
cmd.Help() //nolint:errcheck
cmd.Help() //nolint:errcheck,gosec
os.Exit(0)
}
} else {
} else if err := cfgreader.parse(); err != nil {
// config file is found, we're now going to parse it
if err := cfgreader.parse(); err != nil {
return err
}
return err
}

// explicitly setting formatter to Config for non-root commands this
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func (fw *fileWriter) Write(p []byte) (int, error) {
if after < before {
return 0, errors.New(errEndCommentBeforeBegin)
}
content = content + fc[after+len(fw.end):]
content += fc[after+len(fw.end):]
}

n := len(content)
Expand Down
6 changes: 2 additions & 4 deletions internal/format/tfvars_hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,8 @@ func alignments(inputs []*terraform.Input) {
padding[i] = l
maxlen = 0
index = i + 1
} else {
if l > maxlen {
maxlen = l
}
} else if l > maxlen {
maxlen = l
}
}
for i := index; i < len(inputs); i++ {
Expand Down
6 changes: 5 additions & 1 deletion internal/plugin/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,16 @@ func findPlugins(dir string) (*List, error) {
}

for _, f := range files {
name := strings.Replace(f.Name(), namePrefix, "", -1)
name := strings.ReplaceAll(f.Name(), namePrefix, "")
path, err := getPluginPath(dir, name)
if err != nil {
return nil, err
}

// Accepting variables here is intentional; we need to determine the
// path on the fly per directory.
//
// nolint:gosec
cmd := exec.Command(path)

client := pluginsdk.NewClient(&pluginsdk.ClientOpts{
Expand Down
2 changes: 1 addition & 1 deletion internal/plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type List struct {

// All returns all registered plugins.
func (l *List) All() []*pluginsdk.Client {
all := make([]*pluginsdk.Client, len(l.formatters)-1)
all := make([]*pluginsdk.Client, 0)
for _, f := range l.formatters {
all = append(all, f)
}
Expand Down
10 changes: 8 additions & 2 deletions internal/reader/lines.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,19 @@ func (l *Lines) Extract() ([]string, error) {
return l.extract(f)
}

func (l *Lines) extract(r io.Reader) ([]string, error) {
func (l *Lines) extract(r io.Reader) ([]string, error) { //nolint:gocyclo
// NOTE(khos2ow): this function is over our cyclomatic complexity goal.
// Be wary when adding branches, and look for functionality that could
// be reasonably moved into an injected dependency.

bf := bufio.NewReader(r)
var lines = make([]string, 0)
for lnum := 0; ; lnum++ {
if l.LineNum != -1 && lnum >= l.LineNum-1 {
break
}
line, err := bf.ReadString('\n')
if err == io.EOF && line == "" {
if errors.Is(err, io.EOF) && line == "" {
switch lnum {
case 0:
return nil, errors.New("no lines in file")
Expand All @@ -62,6 +66,8 @@ func (l *Lines) extract(r io.Reader) ([]string, error) {
return nil, fmt.Errorf("only %d lines", lnum)
}
}

//nolint:gocritic
if l.Condition(line) {
if extracted, capture := l.Parser(line); capture {
lines = append(lines, extracted)
Expand Down
35 changes: 18 additions & 17 deletions internal/template/sanitizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
func sanitizeName(name string, settings *print.Settings) string {
if settings.EscapeCharacters {
// Escape underscore
name = strings.Replace(name, "_", "\\_", -1)
name = strings.ReplaceAll(name, "_", "\\_")
}
return name
}
Expand Down Expand Up @@ -106,8 +106,8 @@ func sanitizeMarkdownTable(s string, settings *print.Settings) string {
},
func(segment string) string {
segment = strings.TrimSpace(segment)
segment = strings.Replace(segment, "\n", "<br>", -1)
segment = strings.Replace(segment, "\r", "", -1)
segment = strings.ReplaceAll(segment, "\n", "<br>")
segment = strings.ReplaceAll(segment, "\r", "")
segment = fmt.Sprintf("<pre>%s</pre>", segment)
return segment
},
Expand Down Expand Up @@ -145,7 +145,7 @@ func convertMultiLineText(s string, isTable bool, isHeader bool) string {
}

// Convert double newlines to <br><br>.
s = strings.Replace(s, "\n\n", "<br><br>", -1)
s = strings.ReplaceAll(s, "\n\n", "<br><br>")

// Convert line-break on a non-empty line followed by another line
// starting with "alphanumeric" word into space-space-newline
Expand All @@ -154,18 +154,18 @@ func convertMultiLineText(s string, isTable bool, isHeader bool) string {
// consecutive lines start with hyphen which is a special character.
if !isHeader {
s = regexp.MustCompile(`(\S*)(\r?\n)(\s*)(\w+)`).ReplaceAllString(s, "$1 $2$3$4")
s = strings.Replace(s, " \n", " \n", -1)
s = strings.Replace(s, "<br> \n", "\n\n", -1)
s = strings.ReplaceAll(s, " \n", " \n")
s = strings.ReplaceAll(s, "<br> \n", "\n\n")
}

if isTable {
// Convert space-space-newline to <br>
s = strings.Replace(s, " \n", "<br>", -1)
s = strings.ReplaceAll(s, " \n", "<br>")

// Convert single newline to <br>.
s = strings.Replace(s, "\n", "<br>", -1)
s = strings.ReplaceAll(s, "\n", "<br>")
} else {
s = strings.Replace(s, "<br>", "\n", -1)
s = strings.ReplaceAll(s, "<br>", "\n")
}

return s
Expand All @@ -179,7 +179,7 @@ func escapeIllegalCharacters(s string, settings *print.Settings, escapePipe bool
s,
"`",
func(segment string) string {
return strings.Replace(segment, "|", "\\|", -1)
return strings.ReplaceAll(segment, "|", "\\|")
},
func(segment string) string {
return fmt.Sprintf("`%s`", segment)
Expand All @@ -194,7 +194,7 @@ func escapeIllegalCharacters(s string, settings *print.Settings, escapePipe bool
func(segment string) string {
return executePerLine(segment, func(line string) string {
escape := func(char string) {
c := strings.Replace(char, "*", "\\*", -1)
c := strings.ReplaceAll(char, "*", "\\*")
cases := []struct {
pattern string
index []int
Expand All @@ -208,18 +208,19 @@ func escapeIllegalCharacters(s string, settings *print.Settings, escapePipe bool
index: []int{6, 2},
},
}
for _, c := range cases {
for i := range cases {
c := cases[i]
r := regexp.MustCompile(c.pattern)
m := r.FindAllStringSubmatch(line, -1)
i := r.FindAllStringSubmatchIndex(line, -1)
for j := range m {
for _, k := range c.index {
line = line[:i[j][k*2]] + strings.Replace(m[j][k], char, "‡‡‡DONTESCAPE‡‡‡", -1) + line[i[j][(k*2)+1]:]
line = line[:i[j][k*2]] + strings.ReplaceAll(m[j][k], char, "‡‡‡DONTESCAPE‡‡‡") + line[i[j][(k*2)+1]:]
}
}
}
line = strings.Replace(line, char, "\\"+char, -1)
line = strings.Replace(line, "‡‡‡DONTESCAPE‡‡‡", char, -1)
line = strings.ReplaceAll(line, char, "\\"+char)
line = strings.ReplaceAll(line, "‡‡‡DONTESCAPE‡‡‡", char)
}
escape("_") // Escape underscore
return line
Expand All @@ -242,8 +243,8 @@ func normalizeURLs(s string, settings *print.Settings) string {
if settings.EscapeCharacters {
if urls := xurls.Strict().FindAllString(s, -1); len(urls) > 0 {
for _, url := range urls {
normalized := strings.Replace(url, "\\", "", -1)
s = strings.Replace(s, url, normalized, -1)
normalized := strings.ReplaceAll(url, "\\", "")
s = strings.ReplaceAll(s, url, normalized)
}
}
}
Expand Down
40 changes: 24 additions & 16 deletions internal/terraform/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,11 @@ func loadFooter(options *Options) (string, error) {
return loadSection(options, options.FooterFromFile, "footer")
}

func loadSection(options *Options, file string, section string) (string, error) {
func loadSection(options *Options, file string, section string) (string, error) { //nolint:gocyclo
// NOTE(khos2ow): this function is over our cyclomatic complexity goal.
// Be wary when adding branches, and look for functionality that could
// be reasonably moved into an injected dependency.

if section == "" {
return "", errors.New("section is missing")
}
Expand All @@ -225,7 +229,7 @@ func loadSection(options *Options, file string, section string) (string, error)
return "", err // user explicitly asked for a file which doesn't exist
}
if getFileFormat(file) != ".tf" {
content, err := ioutil.ReadFile(filename)
content, err := ioutil.ReadFile(filepath.Clean(filename))
if err != nil {
return "", err
}
Expand Down Expand Up @@ -266,7 +270,7 @@ func loadInputs(tfmodule *tfconfig.Module) ([]*Input, []*Input, []*Input) {

for _, input := range tfmodule.Variables {
// convert CRLF to LF early on (https://github.com/terraform-docs/terraform-docs/issues/305)
inputDescription := strings.Replace(input.Description, "\r\n", "\n", -1)
inputDescription := strings.ReplaceAll(input.Description, "\r\n", "\n")
if inputDescription == "" {
inputDescription = loadComments(input.Pos.Filename, input.Pos.Line)
}
Expand Down Expand Up @@ -355,12 +359,10 @@ func loadOutputValues(options *Options) (map[string]*output, error) {
cmd := exec.Command("terraform", "output", "-json")
cmd.Dir = options.Path
if out, err = cmd.Output(); err != nil {
return nil, fmt.Errorf("caught error while reading the terraform outputs: %v", err)
}
} else {
if out, err = ioutil.ReadFile(options.OutputValuesPath); err != nil {
return nil, fmt.Errorf("caught error while reading the terraform outputs file at %s: %v", options.OutputValuesPath, err)
return nil, fmt.Errorf("caught error while reading the terraform outputs: %w", err)
}
} else if out, err = ioutil.ReadFile(options.OutputValuesPath); err != nil {
return nil, fmt.Errorf("caught error while reading the terraform outputs file at %s: %w", options.OutputValuesPath, err)
}
var terraformOutputs map[string]*output
err = json.Unmarshal(out, &terraformOutputs)
Expand Down Expand Up @@ -514,21 +516,26 @@ func loadComments(filename string, lineNum int) string {
return strings.Join(comment, " ")
}

func sortItems(tfmodule *Module, sortby *SortBy) {
func sortItems(tfmodule *Module, sortby *SortBy) { //nolint:gocyclo
// NOTE(khos2ow): this function is over our cyclomatic complexity goal.
// Be wary when adding branches, and look for functionality that could
// be reasonably moved into an injected dependency.

// inputs
if sortby.Type {
switch {
case sortby.Type:
sort.Sort(inputsSortedByType(tfmodule.Inputs))
sort.Sort(inputsSortedByType(tfmodule.RequiredInputs))
sort.Sort(inputsSortedByType(tfmodule.OptionalInputs))
} else if sortby.Required {
case sortby.Required:
sort.Sort(inputsSortedByRequired(tfmodule.Inputs))
sort.Sort(inputsSortedByRequired(tfmodule.RequiredInputs))
sort.Sort(inputsSortedByRequired(tfmodule.OptionalInputs))
} else if sortby.Name {
case sortby.Name:
sort.Sort(inputsSortedByName(tfmodule.Inputs))
sort.Sort(inputsSortedByName(tfmodule.RequiredInputs))
sort.Sort(inputsSortedByName(tfmodule.OptionalInputs))
} else {
default:
sort.Sort(inputsSortedByPosition(tfmodule.Inputs))
sort.Sort(inputsSortedByPosition(tfmodule.RequiredInputs))
sort.Sort(inputsSortedByPosition(tfmodule.OptionalInputs))
Expand All @@ -552,11 +559,12 @@ func sortItems(tfmodule *Module, sortby *SortBy) {
sort.Sort(resourcesSortedByType(tfmodule.Resources))

// modules
if sortby.Name || sortby.Required {
switch {
case sortby.Name || sortby.Required:
sort.Sort(modulecallsSortedByName(tfmodule.ModuleCalls))
} else if sortby.Type {
case sortby.Type:
sort.Sort(modulecallsSortedBySource(tfmodule.ModuleCalls))
} else {
default:
sort.Sort(modulecallsSortedByPosition(tfmodule.ModuleCalls))
}
}
8 changes: 4 additions & 4 deletions internal/terraform/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,11 @@ func (o *Output) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if err != nil {
return err
}
fn(o.Name, "name") //nolint: errcheck
fn(o.Description, "description") //nolint: errcheck
fn(o.Name, "name") //nolint:errcheck,gosec
fn(o.Description, "description") //nolint:errcheck,gosec
if o.ShowValue {
fn(o.Value, "value") //nolint: errcheck
fn(o.Sensitive, "sensitive") //nolint: errcheck
fn(o.Value, "value") //nolint:errcheck,gosec
fn(o.Sensitive, "sensitive") //nolint:errcheck,gosec
}
return e.EncodeToken(start.End())
}
Expand Down
2 changes: 1 addition & 1 deletion internal/testutil/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func GetModule(options *terraform.Options) (*terraform.Module, error) {
// GetExpected returns 'example' Module and expected Golden file content
func GetExpected(format, name string) (string, error) {
path := filepath.Join(testDataPath(), format, name+".golden")
bytes, err := ioutil.ReadFile(path)
bytes, err := ioutil.ReadFile(filepath.Clean(path))
if err != nil {
return "", err
}
Expand Down

0 comments on commit 3cc4f44

Please sign in to comment.