| 166 | } |
| 167 | |
| 168 | func CommitAndPush(ctx context.Context, projectPath string, config *Config, commitMsg string, author *object.Signature) error { |
| 169 | // init git repo |
| 170 | repo, err := git.PlainInitWithOptions(projectPath, &git.PlainInitOptions{ |
| 171 | InitOptions: git.InitOptions{ |
| 172 | DefaultBranch: plumbing.NewBranchReferenceName(config.DefaultBranch), |
| 173 | }, |
| 174 | Bare: false, |
| 175 | }) |
| 176 | if err != nil { |
| 177 | if !errors.Is(err, git.ErrRepositoryAlreadyExists) { |
| 178 | return fmt.Errorf("failed to init git repo: %w", err) |
| 179 | } |
| 180 | repo, err = git.PlainOpen(projectPath) |
| 181 | if err != nil { |
| 182 | return fmt.Errorf("failed to open git repo: %w", err) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // check current branch matches deployed branch |
| 187 | headRef, err := repo.Head() |
| 188 | if err == nil { |
| 189 | if !headRef.Name().IsBranch() { |
| 190 | return fmt.Errorf("detached HEAD state detected. Checkout a branch") |
| 191 | } |
| 192 | branch := headRef.Name().Short() |
| 193 | if headRef.Name().Short() != config.DefaultBranch { |
| 194 | return fmt.Errorf("current branch %q does not match deployed branch %q", branch, config.DefaultBranch) |
| 195 | } |
| 196 | } else if !errors.Is(err, plumbing.ErrReferenceNotFound) { |
| 197 | // ErrReferenceNotFound happens when looking for HEAD on a fresh repo |
| 198 | return err |
| 199 | } |
| 200 | |
| 201 | wt, err := repo.Worktree() |
| 202 | if err != nil { |
| 203 | return fmt.Errorf("failed to get worktree: %w", err) |
| 204 | } |
| 205 | |
| 206 | // git add subpath/** |
| 207 | var stagingPath string |
| 208 | if config.Subpath != "" { |
| 209 | stagingPath = filepath.Join(config.Subpath, "**") |
| 210 | } else { |
| 211 | stagingPath = "." |
| 212 | } |
| 213 | if err := wt.AddWithOptions(&git.AddOptions{Glob: stagingPath}); err != nil { |
| 214 | return fmt.Errorf("failed to add files to git: %w", err) |
| 215 | } |
| 216 | |
| 217 | // git commit -m |
| 218 | if commitMsg == "" { |
| 219 | commitMsg = "Auto committed by Rill" |
| 220 | } |
| 221 | _, err = wt.Commit(commitMsg, &git.CommitOptions{Author: author, AllowEmptyCommits: false}) |
| 222 | if err != nil { |
| 223 | if !errors.Is(err, git.ErrEmptyCommit) { |
| 224 | return fmt.Errorf("failed to commit files to git: %w", err) |
| 225 | } |