github.com/erikjuhani/git-gong@v0.0.0-20220213141213-6b9fa82d4e7c/cmd/commit.go (about) 1 package cmd 2 3 import ( 4 "github.com/erikjuhani/git-gong/gong" 5 "github.com/spf13/cobra" 6 ) 7 8 func init() { 9 rootCmd.AddCommand(commitCmd) 10 commitFlags() 11 } 12 13 var ( 14 stageOnly bool 15 commitMsg string 16 ) 17 18 var commitCmd = &cobra.Command{ 19 Use: "commit [pathspec]", 20 Short: "Record changes to index and repository", 21 Long: `Create a new commit containing the contents of the index. 22 23 To only stage file changes apply a flag --stage. The files won't be recorded 24 until the next call for commit. 25 `, 26 Run: func(cmd *cobra.Command, args []string) { 27 err := commit(args) 28 if err != nil { 29 cmd.PrintErr(err) 30 return 31 } 32 }, 33 } 34 35 func commitFlags() { 36 commitCmd.Flags().BoolVarP( 37 &stageOnly, "stage", "s", false, 38 "Use to stage file changes instead of a commit", 39 ) 40 commitCmd.Flags().StringVarP( 41 &commitMsg, "message", "m", "", 42 "Set commit message", 43 ) 44 } 45 46 func commit(paths []string) error { 47 repo, err := gong.Open() 48 if err != nil { 49 return err 50 } 51 defer gong.Free(repo) 52 53 tree, err := repo.AddToIndex(paths) 54 if err != nil || stageOnly { 55 return err 56 } 57 defer gong.Free(tree) 58 59 commit, err := repo.CreateCommit(tree, commitMsg) 60 if err != nil { 61 return err 62 } 63 defer gong.Free(commit) 64 65 return nil 66 }