From e05c869dbd4ce1a35b90fc85176a2264d65aa062 Mon Sep 17 00:00:00 2001 From: Alper Rifat Ulucinar Date: Wed, 6 Mar 2024 13:00:43 +0300 Subject: [PATCH] Refactor main.updateFileWithBuildTag to decrease its cyclomatic complexity Signed-off-by: Alper Rifat Ulucinar --- cmd/buildtagger/main.go | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/cmd/buildtagger/main.go b/cmd/buildtagger/main.go index 88c6cb6..8515917 100644 --- a/cmd/buildtagger/main.go +++ b/cmd/buildtagger/main.go @@ -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} @@ -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...")