/
stack_branchcommit.go
232 lines (205 loc) · 7.02 KB
/
stack_branchcommit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package main
import (
"fmt"
"os"
"regexp"
"strings"
"emperror.dev/errors"
"github.com/aviator-co/av/internal/actions"
"github.com/aviator-co/av/internal/config"
"github.com/aviator-co/av/internal/git"
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/utils/cleanup"
"github.com/aviator-co/av/internal/utils/colors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const (
// This is an arbitrary limit on the branch name length.
branchNameLength = 200
)
var (
// See man 1 git-check-ref-format for the refname spec. This pattern is more restrictive
// than the spec.
//
// * Do not allow slashes because creating a branch directory from a commit message is
// unlikely.
// * Do not allow dots because dots cannot be placed on a certain location and it's unlikely
// the user wants to have a dot in the branch name.
branchNameReplacedPattern = regexp.MustCompile("[^-_a-zA-Z0-9]")
multipleSpacePattern = regexp.MustCompile(" +")
)
var stackBranchCommitFlags struct {
// The commit message.
Message string
// Name of the new branch.
BranchName string
// Same as `git add --all`.
// Stages all changes, including untracked files.
All bool
// Same as `git commit --all`.
// Stage all files that have been modified and deleted, but ignore untracked files.
AllModified bool
}
var stackBranchCommitCmd = &cobra.Command{
Use: "branch-commit [flags]",
Aliases: []string{"branchcommit", "bc"},
Short: "create a new stacked branch and commit staged changes to it",
Long: "Create a new branch that is stacked on the current branch and commit all staged changes with the specified arguments.",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) (reterr error) {
branchName := stackBranchCommitFlags.BranchName
if branchName == "" {
if stackBranchCommitFlags.Message == "" {
_ = cmd.Usage()
return errors.New("Need a branch name or a commit message")
}
branchName = branchNameFromMessage(stackBranchCommitFlags.Message)
if branchName == "" {
return errors.New("Cannot create a valid branch name from the message")
}
}
repo, err := getRepo()
if err != nil {
return err
}
db, err := getDB(repo)
if err != nil {
return err
}
tx := db.WriteTx()
var cu cleanup.Cleanup
defer cu.Cleanup()
cu.Add(func() {
logrus.WithError(reterr).Debug("aborting db transaction")
tx.Abort()
})
// Determine important contextual information from Git
defaultBranch, err := repo.DefaultBranch()
if err != nil {
return errors.WrapIf(err, "failed to determine repository default branch")
}
parentBranchName, err := repo.CurrentBranchName()
if err != nil {
return errors.WrapIff(err, "failed to get current branch name")
}
// Currently, we only allow the repo default branch to be a trunk.
// We might want to allow other branches to be trunks in the future, but
// that does run the risk of allowing the user to get into a weird state
// (where some stacks assume a branch is a trunk and others don't).
isBranchFromTrunk := parentBranchName == defaultBranch
var parentHead string
if !isBranchFromTrunk {
parentHead, err = repo.RevParse(&git.RevParse{Rev: parentBranchName})
if err != nil {
return errors.WrapIf(err, "failed to get parent branch head commit")
}
}
if err != nil {
return errors.WrapIf(err, "failed to read parent branch state")
}
// Create a new branch off of the parent
logrus.WithFields(logrus.Fields{
"parent": parentBranchName,
"new_branch": branchName,
}).Debug("creating new branch from parent")
if _, err := repo.CheckoutBranch(&git.CheckoutBranch{
Name: branchName,
NewBranch: true,
}); err != nil {
return errors.WrapIff(err, "checkout error")
}
// On failure, we want to delete the branch we created so that the user
// can try again (e.g., to fix issues surfaced by a pre-commit hook).
cu.Add(func() {
_, _ = fmt.Fprint(os.Stderr,
colors.Faint(" - Cleaning up branch "),
colors.UserInput(branchName),
colors.Faint(" because commit was not successful."),
"\n",
)
if _, err := repo.CheckoutBranch(&git.CheckoutBranch{
Name: parentBranchName,
}); err != nil {
logrus.WithError(err).Error("failed to return to original branch during cleanup")
}
if err := repo.BranchDelete(branchName); err != nil {
logrus.WithError(err).Error("failed to delete branch during cleanup")
}
})
tx.SetBranch(meta.Branch{
Name: branchName,
Parent: meta.BranchState{
Name: parentBranchName,
Trunk: isBranchFromTrunk,
Head: parentHead,
},
})
// For "--all" and "--all-modified",
var addArgs []string
if stackBranchCommitFlags.All {
addArgs = append(addArgs, "--all")
} else if stackBranchCommitFlags.AllModified {
// This is meant to mirror `git commit --all` which does not add
// unstaged files to the index (which is different from `git add --all`).
addArgs = append(addArgs, "--update")
}
if len(addArgs) > 0 {
_, err := repo.Run(&git.RunOpts{
Args: append([]string{"add"}, addArgs...),
ExitError: true,
})
if err != nil {
_, _ = fmt.Fprint(os.Stderr,
"\n", colors.Failure("Failed to stage files: ", err.Error()), "\n",
)
return actions.ErrExitSilently{ExitCode: 1}
}
}
commitArgs := []string{"commit"}
if stackBranchCommitFlags.Message != "" {
commitArgs = append(commitArgs, "--message", stackBranchCommitFlags.Message)
}
if _, err := repo.Run(&git.RunOpts{
Args: commitArgs,
ExitError: true,
Interactive: true,
}); err != nil {
_, _ = fmt.Fprint(os.Stderr,
"\n", colors.Failure("Failed to create commit."), "\n",
)
return actions.ErrExitSilently{ExitCode: 1}
}
// Cancel the cleanup **after** the commit is successful (so that we
// delete the created branch).
cu.Cancel()
if err := tx.Commit(); err != nil {
return err
}
return nil
},
}
func init() {
stackBranchCommitCmd.Flags().
StringVarP(&stackBranchCommitFlags.Message, "message", "m", "", "the commit message")
stackBranchCommitCmd.Flags().
StringVarP(&stackBranchCommitFlags.BranchName, "branch-name", "b", "", "the branch name to create (if empty, automatically generated from the message)")
stackBranchCommitCmd.Flags().
BoolVarP(&stackBranchCommitFlags.All, "all", "A", false, "automatically stage all files")
stackBranchCommitCmd.Flags().
BoolVarP(&stackBranchCommitFlags.AllModified, "all-modified", "a", false, "automatically stage modified and deleted files (ignore untracked files)")
stackBranchCommitCmd.MarkFlagsMutuallyExclusive("all", "all-modified")
}
func branchNameFromMessage(message string) string {
name := branchNameReplacedPattern.ReplaceAllLiteralString(message, " ")
name = strings.TrimSpace(name)
name = multipleSpacePattern.ReplaceAllLiteralString(name, "-")
if len(name) > branchNameLength {
name = name[:branchNameLength]
}
name = strings.ToLower(name)
if config.Av.PullRequest.BranchNamePrefix != "" {
name = fmt.Sprintf("%s%s", config.Av.PullRequest.BranchNamePrefix, name)
}
return name
}