From c18aaf0b0bf5c22d33c3348376236fc56bc663a4 Mon Sep 17 00:00:00 2001 From: CHIKAMATSU Naohiro Date: Fri, 23 Sep 2022 22:42:49 +0900 Subject: [PATCH] Added output option to Export subcommand --- cmd/export.go | 42 +++++++++++++++++++++++++++++++++------ internal/config/config.go | 10 ++-------- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/cmd/export.go b/cmd/export.go index 595adcf..92e5fba 100644 --- a/cmd/export.go +++ b/cmd/export.go @@ -27,6 +27,7 @@ according to the contents of gup.conf.`, } func init() { + exportCmd.Flags().BoolP("output", "o", false, "print command path information at STDOUT") rootCmd.AddCommand(exportCmd) } @@ -36,8 +37,9 @@ func export(cmd *cobra.Command, args []string) int { return 1 } - if err := os.MkdirAll(config.DirPath(), 0775); err != nil { - print.Err(fmt.Errorf("%s: %w", "can not make config directory", err)) + output, err := cmd.Flags().GetBool("output") + if err != nil { + print.Err(fmt.Errorf("%s: %w", "can not parse command line argument", err)) return 1 } @@ -53,14 +55,42 @@ func export(cmd *cobra.Command, args []string) int { return 1 } - if err := config.WriteConfFile(pkgs); err != nil { - print.Err(err) - return 1 + if output { + if err := outputConfig(pkgs); err != nil { + print.Err(err) + return 1 + } + } else { + if err := writeConfigFile(pkgs); err != nil { + print.Err(err) + return 1 + } } - print.Info("Export " + config.FilePath()) return 0 } +func writeConfigFile(pkgs []goutil.Package) error { + if err := os.MkdirAll(config.DirPath(), 0775); err != nil { + return fmt.Errorf("%s: %w", "can not make config directory", err) + } + + file, err := os.Create(config.FilePath()) + if err != nil { + return fmt.Errorf("%s %s: %w", "can't update", config.FilePath(), err) + } + defer file.Close() + + if err := config.WriteConfFile(file, pkgs); err != nil { + return err + } + print.Info("Export " + config.FilePath()) + return nil +} + +func outputConfig(pkgs []goutil.Package) error { + return config.WriteConfFile(os.Stdout, pkgs) +} + func validPkgInfo(pkgs []goutil.Package) []goutil.Package { result := []goutil.Package{} for _, v := range pkgs { diff --git a/internal/config/config.go b/internal/config/config.go index 3a27d97..7bdbac3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -58,20 +58,14 @@ func ReadConfFile() ([]goutil.Package, error) { } // WriteConfFile write package information at configuration-file. -func WriteConfFile(pkgs []goutil.Package) error { - file, err := os.Create(FilePath()) - if err != nil { - return fmt.Errorf("%s %s: %w", "can't update", FilePath(), err) - } - defer file.Close() - +func WriteConfFile(file *os.File, pkgs []goutil.Package) error { text := "" for _, v := range pkgs { // lost version information text = text + fmt.Sprintf("%s = %s\n", v.Name, v.ImportPath) } - _, err = file.Write(([]byte)(text)) + _, err := file.Write(([]byte)(text)) if err != nil { return fmt.Errorf("%s %s: %w", "can't update", FilePath(), err) }