github.com/jaypipes/ghw@v0.21.1/cmd/ghw-snapshot/command/create.go (about) 1 // 2 // Use and distribution licensed under the Apache license version 2. 3 // 4 // See the COPYING file in the root project directory for full text. 5 // 6 7 package command 8 9 import ( 10 "crypto/md5" 11 "fmt" 12 "io" 13 "os" 14 "runtime" 15 16 "github.com/spf13/cobra" 17 18 "github.com/jaypipes/ghw/pkg/snapshot" 19 ) 20 21 var ( 22 // output filepath to save snapshot to 23 outPath string 24 ) 25 26 var createCmd = &cobra.Command{ 27 Use: "create", 28 Short: "Creates a new ghw snapshot", 29 RunE: doCreate, 30 } 31 32 // doCreate creates a ghw snapshot 33 func doCreate(cmd *cobra.Command, args []string) error { 34 scratchDir, err := os.MkdirTemp("", "ghw-snapshot") 35 if err != nil { 36 return err 37 } 38 defer os.RemoveAll(scratchDir) 39 40 snapshot.SetTraceFunction(trace) 41 if err = snapshot.CloneTreeInto(scratchDir); err != nil { 42 return err 43 } 44 45 if outPath == "" { 46 outPath, err = defaultOutPath() 47 if err != nil { 48 return err 49 } 50 trace("using default output filepath %s\n", outPath) 51 } 52 53 return snapshot.PackFrom(outPath, scratchDir) 54 } 55 56 func systemFingerprint() (string, error) { 57 hn, err := os.Hostname() 58 if err != nil { 59 return "unknown", err 60 } 61 m := md5.New() 62 _, err = io.WriteString(m, hn) 63 if err != nil { 64 return "unknown", err 65 } 66 return fmt.Sprintf("%x", m.Sum(nil)), nil 67 } 68 69 func defaultOutPath() (string, error) { 70 fp, err := systemFingerprint() 71 if err != nil { 72 return "unknown", err 73 } 74 return fmt.Sprintf("%s-%s-%s.tar.gz", runtime.GOOS, runtime.GOARCH, fp), nil 75 } 76 77 func init() { 78 createCmd.PersistentFlags().StringVarP( 79 &outPath, 80 "out", "o", 81 outPath, 82 "Path to place snapshot. Defaults to file in current directory with name $OS-$ARCH-$HASHSYSTEMNAME.tar.gz", 83 ) 84 rootCmd.AddCommand(createCmd) 85 }