Last active
July 9, 2021 06:58
-
-
Save agnivade/fba2151ebda76b9a07d60d0f561b2e3e to your computer and use it in GitHub Desktop.
Add release notes to commit message
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"regexp" | |
) | |
func hookCommitMsg(args []string) { | |
if len(args) != 1 { | |
fmt.Println("usage: commit-msg message.txt\n") | |
return | |
} | |
file := args[0] | |
oldData, err := ioutil.ReadFile(file) | |
if err != nil { | |
fmt.Println("%v", err) | |
return | |
} | |
data := append([]byte{}, oldData...) | |
data = stripComments(data) | |
// Empty message not allowed. | |
if len(bytes.TrimSpace(data)) == 0 { | |
return | |
} | |
// Insert a blank line between first line and subsequent lines if not present. | |
eol := bytes.IndexByte(data, '\n') | |
if eol != -1 && len(data) > eol+1 && data[eol+1] != '\n' { | |
data = append(data, 0) | |
copy(data[eol+1:], data[eol:]) | |
data[eol+1] = '\n' | |
} | |
// Complain if two release notes are present. | |
// This can happen during an interactive rebase; | |
// it is easy to forget to remove one of them. | |
numRelNotes := bytes.Count(data, []byte("\n```release-note")) | |
if numRelNotes > 1 { | |
fmt.Println("multiple release-note lines") | |
return | |
} | |
// Add release-note to commit message if not present. | |
if numRelNotes == 0 { | |
data = append(data, []byte("```release-note\nNONE\n```")...) | |
} | |
if !bytes.Equal(data, oldData) { | |
if err := ioutil.WriteFile(file, data, 0666); err != nil { | |
fmt.Println("%v", err) | |
return | |
} | |
} | |
} | |
func stripComments(in []byte) []byte { | |
return regexp.MustCompile(`(?m)^#.*\n`).ReplaceAll(in, nil) | |
} | |
func main() { | |
hookCommitMsg(os.Args[1:]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment