Skip to content

Commit

Permalink
Refactor main.updateFileWithBuildTag to decrease its cyclomatic compl…
Browse files Browse the repository at this point in the history
…exity

Signed-off-by: Alper Rifat Ulucinar <ulucinar@users.noreply.github.com>
  • Loading branch information
ulucinar committed Mar 6, 2024
1 parent 84acbb1 commit a619f47
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions cmd/buildtagger/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,7 @@ func updateFileWithBuildTag(filePath, buildTag string, deleteTag bool) error {
return nil
}
var updatedLines []string
index := -1
tagExists := false
if strings.HasPrefix(lines[0], "//go:build") {
tagExists = true
index++
}
emptyLineFollows := len(lines) > 1 && strings.TrimSpace(lines[1]) == ""
if deleteTag && emptyLineFollows && tagExists {
index++
}
index, tagExists, emptyLineFollows := getLineStartIndex(lines, deleteTag)
updatedLines = lines[index+1:]
if !deleteTag {
addedLines := [2]string{buildTag}
Expand All @@ -134,6 +125,20 @@ func updateFileWithBuildTag(filePath, buildTag string, deleteTag bool) error {
return errors.Wrapf(os.WriteFile(filePath, []byte(strings.Join(updatedLines, "\n")), 0600), "failed to write the source file at path %s", filePath)
}

func getLineStartIndex(lines []string, deleteTag bool) (int, bool, bool) {
index := -1
tagExists := false
if strings.HasPrefix(lines[0], "//go:build") {
tagExists = true
index++
}
emptyLineFollows := len(lines) > 1 && strings.TrimSpace(lines[1]) == ""
if deleteTag && emptyLineFollows && tagExists {
index++
}
return index, tagExists, emptyLineFollows
}

func main() {
kingpin.MustParse(app.Parse(os.Args[1:]))
kingpin.FatalIfError(addOrUpdateBuildTag(*parentDir, *regex, *tagFormat, *mode, *deleteTags), "Failed to run the buildtagger...")
Expand Down

0 comments on commit a619f47

Please sign in to comment.