| 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 existing |
| 16 |
// repository. |
| 17 |
func main() { |
| 18 |
CheckArgs("<directory>") |
| 19 |
directory := os.Args[1] |
| 20 |
|
| 21 |
// Opens an already existing 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 \"hello 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 area 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 |
Email: "[email protected]", |
| 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 |
} |