Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.

Commit 15a23a7

Browse files
authored
Merge pull request #381 from mcuadros/example-commit
examples: commit example
2 parents 7cd0215 + 86abaa0 commit 15a23a7

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

_examples/commit/main.go

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"io/ioutil"
6+
"os"
7+
"path/filepath"
8+
"time"
9+
10+
"gopkg.in/src-d/go-git.v4"
11+
. "gopkg.in/src-d/go-git.v4/_examples"
12+
"gopkg.in/src-d/go-git.v4/plumbing/object"
13+
)
14+
15+
// Basic example of how to commit changes to the current branch to an existant
16+
// repository.
17+
func main() {
18+
CheckArgs("<directory>")
19+
directory := os.Args[1]
20+
21+
// Opens an already existant repository.
22+
r, err := git.PlainOpen(directory)
23+
CheckIfError(err)
24+
25+
w, err := r.Worktree()
26+
CheckIfError(err)
27+
28+
// ... we need a file to commit so let's create a new file inside of the
29+
// worktree of the project using the go standard library.
30+
Info("echo \"hellow world!\" > example-git-file")
31+
filename := filepath.Join(directory, "example-git-file")
32+
err = ioutil.WriteFile(filename, []byte("hello world!"), 0644)
33+
CheckIfError(err)
34+
35+
// Adds the new file to the staging area.
36+
Info("git add example-git-file")
37+
_, err = w.Add("example-git-file")
38+
CheckIfError(err)
39+
40+
// We can verify the current status of the worktree using the method Status.
41+
Info("git status --porcelain")
42+
status, err := w.Status()
43+
CheckIfError(err)
44+
45+
fmt.Println(status)
46+
47+
// Commits the current staging are to the repository, with the new file
48+
// just created. We should provide the object.Signature of Author of the
49+
// commit.
50+
Info("git commit -m \"example go-git commit\"")
51+
commit, err := w.Commit("example go-git commit", &git.CommitOptions{
52+
Author: &object.Signature{
53+
Name: "John Doe",
54+
55+
When: time.Now(),
56+
},
57+
})
58+
59+
CheckIfError(err)
60+
61+
// Prints the current HEAD to verify that all worked well.
62+
Info("git show -s")
63+
obj, err := r.CommitObject(commit)
64+
CheckIfError(err)
65+
66+
fmt.Println(obj)
67+
}

_examples/common_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ var defaultURL = "https://github.com/git-fixtures/basic.git"
1717
var args = map[string][]string{
1818
"checkout": []string{defaultURL, tempFolder(), "35e85108805c84807bc66a02d91535e1e24b38b9"},
1919
"clone": []string{defaultURL, tempFolder()},
20+
"commit": []string{cloneRepository(defaultURL, tempFolder())},
2021
"custom_http": []string{defaultURL},
2122
"open": []string{cloneRepository(defaultURL, tempFolder())},
2223
"progress": []string{defaultURL, tempFolder()},

0 commit comments

Comments
 (0)