github.com/purpleclay/gitz@v0.8.2-0.20240515052600-43f80eea2fe1/stage.go (about) 1 package git 2 3 import "strings" 4 5 // StageOption provides a way for setting specific options during a stage 6 // operation. Each supported option can customize the way files are staged 7 // within the current repository (working directory) 8 type StageOption func(*stageOptions) 9 10 type stageOptions struct { 11 PathSpecs []string 12 } 13 14 // WithPathSpecs permits a series of [PathSpecs] (or globs) to be defined 15 // that will stage any matching files within the current repository 16 // (working directory). Paths to files and folders are relative to the 17 // root of the repository. All leading and trailing whitespace will be 18 // trimmed from the file paths, allowing empty paths to be ignored 19 // 20 // [PathSpecs]: https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec 21 func WithPathSpecs(specs ...string) StageOption { 22 return func(opts *stageOptions) { 23 opts.PathSpecs = trim(specs...) 24 } 25 } 26 27 // Stage changes to any file or folder within the current repository 28 // (working directory) ready for inclusion in the next commit. Options 29 // can be provided to further configure stage semantics. By default, 30 // all changes will be staged ready for the next commit. 31 func (c *Client) Stage(opts ...StageOption) (string, error) { 32 options := &stageOptions{} 33 for _, opt := range opts { 34 opt(options) 35 } 36 37 // Build command based on the provided options 38 var stageCmd strings.Builder 39 stageCmd.WriteString("git add ") 40 41 if len(options.PathSpecs) > 0 { 42 stageCmd.WriteString("--") 43 for _, spec := range options.PathSpecs { 44 stageCmd.WriteString(" ") 45 stageCmd.WriteString(spec) 46 } 47 } else { 48 stageCmd.WriteString("--all") 49 } 50 51 return c.exec(stageCmd.String()) 52 } 53 54 // Staged retrieves a list of all currently staged file changes within the 55 // current repository 56 func (c *Client) Staged() ([]string, error) { 57 diff, err := c.exec("git diff --staged --name-only") 58 if err != nil { 59 return nil, err 60 } 61 62 if diff == "" { 63 return nil, nil 64 } 65 66 return strings.Split(diff, "\n"), nil 67 }