From 6279fd65e8ca0aafcc1ef3e7599d21c6fead76b9 Mon Sep 17 00:00:00 2001 From: Fredrik Blomqvist Date: Tue, 20 Oct 2020 21:29:31 -0400 Subject: [PATCH] Add option for output --- README.md | 2 ++ doc.go | 2 +- main.go | 28 +++++++++++++++++++++------- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 2220b8c..6e820c4 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,8 @@ Usage of goimports-reviser: Your project name(ex.: github.com/incu6us/goimports-reviser). Optional parameter. -local string Local package prefixes which will be placed after 3rd-party group(if defined). Values should be comma-separated. Optional parameters. + -output string + Can be "file" or "stdout". Whether to write the formatted content back to the file or to stdout. Optional parameter. (default "file") -rm-unused Remove unused imports. Optional parameter. -set-alias diff --git a/doc.go b/doc.go index ba6c4b0..581b008 100644 --- a/doc.go +++ b/doc.go @@ -1,4 +1,4 @@ -// Tool for Golang to sort goimports by 3 groups: std, general and project dependencies. +// Tool for Golang to sort goimports by 3-4 groups: std, general, local(which is optional) and project dependencies. // It will help you to keep your code cleaner. // // Example: diff --git a/main.go b/main.go index 9e5dffe..d037453 100644 --- a/main.go +++ b/main.go @@ -21,6 +21,7 @@ const ( removeUnusedImportsArg = "rm-unused" setAliasArg = "set-alias" localPkgPrefixesArg = "local" + outputArg = "output" ) // Project build specific vars @@ -35,7 +36,7 @@ var ( shouldSetAlias *bool ) -var projectName, filePath, localPkgPrefixes string +var projectName, filePath, localPkgPrefixes, output string func init() { flag.StringVar( @@ -56,7 +57,14 @@ func init() { &localPkgPrefixes, localPkgPrefixesArg, "", - `Local package prefixes which will be placed after 3rd-party group(if defined). Values should be comma-separated. Optional parameters.`, + "Local package prefixes which will be placed after 3rd-party group(if defined). Values should be comma-separated. Optional parameters.", + ) + + flag.StringVar( + &output, + outputArg, + "file", + `Can be "file" or "stdout". Whether to write the formatted content back to the file or to stdout. Optional parameter.`, ) shouldRemoveUnusedImports = flag.Bool( @@ -135,12 +143,18 @@ func main() { log.Fatalf("%+v", errors.WithStack(err)) } - if !hasChange { - return - } + if output == "stdout" { + fmt.Print(string(formattedOutput)) + } else if output == "file" { + if !hasChange { + return + } - if err := ioutil.WriteFile(filePath, formattedOutput, 0644); err != nil { - log.Fatalf("failed to write fixed result to file(%s): %+v", filePath, errors.WithStack(err)) + if err := ioutil.WriteFile(filePath, formattedOutput, 0644); err != nil { + log.Fatalf("failed to write fixed result to file(%s): %+v", filePath, errors.WithStack(err)) + } + } else { + log.Fatalf(`invalid output "%s" specified`, output) } }