"fmt"
"io/ioutil"
"log"
+ "mime"
"net/mail"
"os"
"os/exec"
+ "regexp"
"strconv"
"strings"
"syscall"
"time"
- "go.cypherpunks.ru/netstring/v2"
+ "go.cypherpunks.ru/recfile"
"go.stargrave.org/sgblog"
)
+var hashFinder = regexp.MustCompile("([0-9a-f]{40})")
+
+// Remove various whitespaces and excess lines, because git-notes-add
+// will remove and we have to know exact bytes count
+func cleanupBody(body string) []string {
+ lines := strings.Split(string(body), "\n")
+ for i, line := range lines {
+ line = strings.ReplaceAll(line, " ", " ")
+ line = strings.TrimRight(line, " \r")
+ lines[i] = line
+ }
+ for lines[0] == "" {
+ lines = lines[1:]
+ }
+ for lines[len(lines)-1] == "" {
+ lines = lines[:len(lines)-1]
+ }
+ withoutDups := make([]string, 0, len(lines))
+ emptyMet := false
+ for _, line := range lines {
+ if line == "" {
+ if emptyMet {
+ continue
+ }
+ emptyMet = true
+ } else {
+ emptyMet = false
+ }
+ withoutDups = append(withoutDups, line)
+ }
+ return withoutDups
+}
+
func main() {
gitCmd := flag.String("git-cmd", "/usr/local/bin/git", "Path to git executable")
gitDir := flag.String("git-dir", "", "Path to .git repository")
if len(body) == 0 {
log.Fatal("no body")
}
+ from, err = new(mime.WordDecoder).DecodeHeader(from)
+ if err != nil {
+ log.Fatal(err)
+ }
- subj = strings.TrimPrefix(subj, "Re: ")
+ subj = hashFinder.FindString(subj)
+ if subj == "" {
+ log.Fatal("no commit hash found in subject")
+ }
if h, err := hex.DecodeString(subj); err != nil || len(h) != sha1.Size {
os.Exit(0)
}
note, _ := cmd.Output()
note = bytes.TrimRight(note, "\r\n")
- // Remove trailing whitespaces, because git-notes-add will remove
- // them anyway, and we have to know exact bytes count
- lines := strings.Split(string(body), "\n")
- for i, line := range lines {
- lines[i] = strings.TrimRight(line, " \r")
+ buf := bytes.NewBuffer(note)
+ recfileW := recfile.NewWriter(buf)
+ if _, err = recfileW.RecordStart(); err != nil {
+ log.Fatal(err)
}
- for lines[len(lines)-1] == "" {
- lines = lines[:len(lines)-1]
+ // We trimmed newline, so have to start record twice
+ if _, err = recfileW.RecordStart(); err != nil {
+ log.Fatal(err)
+ }
+ if _, err = recfileW.WriteFields(
+ recfile.Field{"From", from},
+ recfile.Field{"Date", time.Now().UTC().Format(sgblog.WhenFmt)},
+ ); err != nil {
+ log.Fatal(err)
+ }
+ if _, err = recfileW.WriteFieldMultiline(
+ "Body", append([]string{""}, cleanupBody(string(body))...),
+ ); err != nil {
+ log.Fatal(err)
}
-
- buf := bytes.NewBuffer(note)
- w := netstring.NewWriter(buf)
- w.WriteChunk([]byte(fmt.Sprintf(
- "From: %s\nDate: %s\n\n%s",
- from,
- time.Now().UTC().Format(sgblog.WhenFmt),
- strings.Join(lines, "\n"),
- )))
if *dryRun {
fmt.Print(buf.String())