Debian Codegraph @

_examples/showcase/main.go

raw
1 package main
2
3 import (
4 "fmt"
5 "os"
6 "strings"
7
8 "gopkg.in/src-d/go-git.v4"
9 "gopkg.in/src-d/go-git.v4/plumbing/object"
10
11 . "gopkg.in/src-d/go-git.v4/_examples"
12 )
13
14 // Example of an specific use case:
15 // - Clone a repository in a specific path
16 // - Get the HEAD reference
17 // - Using the HEAD reference, obtain the commit this reference is pointing to
18 // - Print the commit content
19 // - Using the commit, iterate over all its files and print them
20 // - Print all the commit history with commit messages, short hash and the
21 // first line of the commit message
22 func main() {
23 CheckArgs("<url> <path>")
24 url := os.Args[1]
25 path := os.Args[2]
26
27 // Clone the given repository, creating the remote, the local branches
28 // and fetching the objects, exactly as:
29 Info("git clone %s %s", url, path)
30
31 r, err := git.PlainClone(path, false, &git.CloneOptions{URL: url})
32 CheckIfError(err)
33
34 // Getting the latest commit on the current branch
35 Info("git log -1")
36
37 // ... retrieving the branch being pointed by HEAD
38 ref, err := r.Head()
39 CheckIfError(err)
40
41 // ... retrieving the commit object
42 commit, err := r.CommitObject(ref.Hash())
43 CheckIfError(err)
44 fmt.Println(commit)
45
46 // List the tree from HEAD
47 Info("git ls-tree -r HEAD")
48
49 // ... retrieve the tree from the commit
50 tree, err := commit.Tree()
51 CheckIfError(err)
52
53 // ... get the files iterator and print the file
54 tree.Files().ForEach(func(f *object.File) error {
55 fmt.Printf("100644 blob %s %s\n", f.Hash, f.Name)
56 return nil
57 })
58
59 // List the history of the repository
60 Info("git log --oneline")
61
62 commitIter, err := r.Log(&git.LogOptions{From: commit.Hash})
63 CheckIfError(err)
64
65 err = commitIter.ForEach(func(c *object.Commit) error {
66 hash := c.Hash.String()
67 line := strings.Split(c.Message, "\n")
68 fmt.Println(hash[:7], line[0])
69
70 return nil
71 })
72 CheckIfError(err)
73 }