commit 1
This commit is contained in:
72
git/squash.go
Normal file
72
git/squash.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SquashInput contains the input for Squash
|
||||
type SquashInput struct {
|
||||
Message *string
|
||||
}
|
||||
|
||||
// Squash squashes everything every commit ahead of main into one commit
|
||||
func (g *Git) Squash(input SquashInput) error {
|
||||
|
||||
// Get the current commit hash
|
||||
hash, err := g.GetHash()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Get the commit hash on the remote
|
||||
remote, err := g.GetCommitRemote()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// If the hashes are the same, there's nothing to squash
|
||||
if hash == remote {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get the number of commits ahead of main
|
||||
commits, err := g.GetCommitsAhead()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
message := ""
|
||||
|
||||
if input.Message != nil {
|
||||
message = *input.Message
|
||||
} else {
|
||||
|
||||
// Get array of commit messages
|
||||
out, err := g.Execute("log", "--pretty=format:%s", "-n", strconv.Itoa(commits))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messages := strings.Split(out, "\n")
|
||||
|
||||
// Add `-` to each message
|
||||
for i, m := range messages {
|
||||
messages[i] = "- " + m
|
||||
}
|
||||
|
||||
// Join the messages
|
||||
message = strings.Join(messages, "\n")
|
||||
|
||||
// Add header comment
|
||||
message = "# Squashed " + strconv.Itoa(commits) + " commits\n\n" + message
|
||||
|
||||
}
|
||||
|
||||
// Squash the current commit into the previous commits
|
||||
_, err = g.Execute("rebase", "-i", hash+"~"+strconv.Itoa(commits), "-x", "git commit --amend -m \""+message+"\" ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user