aboutsummaryrefslogtreecommitdiffstats
path: root/_examples/blame/main.go
blob: 3ffae17b5e18127f78ef4dff78445a4bd5bd1c2b (plain) (blame)
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
package main

import (
	"fmt"
	"os"

	"github.com/go-git/go-git/v5"
	. "github.com/go-git/go-git/v5/_examples"
)

// Basic example of how to blame a repository.
func main() {
	CheckArgs("<url>", "<file_to_blame>")
	url := os.Args[1]
	path := os.Args[2]

	tmp, err := os.MkdirTemp("", "go-git-blame-*")
	CheckIfError(err)

	defer os.RemoveAll(tmp)

	// Clone the given repository.
	Info("git clone %s %s", url, tmp)
	r, err := git.PlainClone(
		tmp,
		false,
		&git.CloneOptions{
			URL:  url,
			Tags: git.NoTags,
		},
	)
	CheckIfError(err)

	// Retrieve the branch's HEAD, to then get the HEAD commit.
	ref, err := r.Head()
	CheckIfError(err)

	c, err := r.CommitObject(ref.Hash())
	CheckIfError(err)

	Info("git blame %s", path)

	// Blame the given file/path.
	br, err := git.Blame(c, path)
	CheckIfError(err)

	fmt.Printf("%s", br.String())
}