abra/pkg/git/commit.go
decentral1se 4d7c812fe2
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
WIP: operator collaboration MVP
See toolshed/organising#467
2024-12-30 00:46:25 +01:00

84 lines
1.6 KiB
Go

package git
import (
"fmt"
"coopcloud.tech/abra/pkg/log"
"github.com/go-git/go-git/v5"
)
// Commit runs a git commit
func Commit(repoPath, commitMessage string, dryRun bool) error {
if commitMessage == "" {
return fmt.Errorf("no commit message specified?")
}
commitRepo, err := git.PlainOpen(repoPath)
if err != nil {
return err
}
commitWorktree, err := commitRepo.Worktree()
if err != nil {
return err
}
patterns, err := GetExcludesFiles()
if err != nil {
return err
}
if len(patterns) > 0 {
commitWorktree.Excludes = append(patterns, commitWorktree.Excludes...)
}
if !dryRun {
// NOTE(d1): `All: true` does not include untracked files
_, err = commitWorktree.Commit(commitMessage, &git.CommitOptions{All: true})
if err != nil {
return err
}
log.Debug("git changes commited")
} else {
log.Debug("dry run: no changes commited")
}
return nil
}
// CommitFile commits a specific file.
func CommitFile(repoPath, filePath, commitMessage string, dryRun bool) error {
if commitMessage == "" {
return fmt.Errorf("no commit message specified?")
}
commitRepo, err := git.PlainOpen(repoPath)
if err != nil {
return err
}
commitWorktree, err := commitRepo.Worktree()
if err != nil {
return err
}
if !dryRun {
if _, err := commitWorktree.Add(filePath); err != nil {
return fmt.Errorf("unable to add %s: %s", filePath, err)
}
}
opts := &git.CommitOptions{}
if !dryRun {
_, err = commitWorktree.Commit(commitMessage, opts)
if err != nil {
return err
}
log.Debug("git changes commited")
} else {
log.Debug("dry run: no changes commited")
}
return nil
}