~kornellapacz/gmnigit

ref: 9cdc82885cf4286f621f8cb7f26c45aa4e513ad6 gmnigit/commits.go -rw-r--r-- 1.7 KiB
9cdc8288Korneliusz Łapacz specify url by command line argument 6 months ago
                                                                                
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
package main

import (
	"os"
	"path/filepath"
	"text/template"

	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing/object"
)

var commitTemplate = template.Must(
	template.New("commit").Parse(`## {{.Hash}}
Author:  {{.Author.String}}
Date:    {{.Author.When.Format "Mon Jan 02 15:04:05 2006 -0700"}}
=> {{.Hash}}.patch Patch
Message: {{ .Message }}
`))

func iterateOverCommits(r *git.Repository, callback func(*object.Commit, *object.Patch) error) {
	ref, err := r.Head()
	check(err)

	cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
	check(err)

	err = cIter.ForEach(func(c *object.Commit) error {
		commitTree, err := c.Tree()
		check(err)

		// get direct parrent
		parent, err := c.Parent(0)

		if err == object.ErrParentNotFound {
			// probably first commit, generate patch for that
			emptyTree := r.EmptyTreeObject()

			patch, err := emptyTree.Patch(commitTree)
			check(err)

			return callback(c, patch)
		}

		check(err)

		parentTree, err := parent.Tree()
		check(err)

		patch, err := parentTree.Patch(commitTree)
		check(err)

		return callback(c, patch)
	})

	check(err)
}

func createCommitsFiles(repository *git.Repository) {
	commitsPath := filepath.Join(distPath, commitsSubPath)
	check(os.Mkdir(commitsPath, os.ModePerm))

	commitsIndex, err := os.Create(filepath.Join(commitsPath, "index.gmi"))
	check(err)
	commitsIndex.WriteString("# Commits \n\n")

	iterateOverCommits(repository, func(commit *object.Commit, patch *object.Patch) error {
		commitTemplate.Execute(commitsIndex, commit)

		patchFile, err := os.Create(filepath.Join(commitsPath, commit.Hash.String()+".patch"))
		check(err)

		patchFile.WriteString(patch.String())
		check(patchFile.Close())

		return nil
	})

	check(commitsIndex.Close())
	wg.Done()
}