aboutsummaryrefslogtreecommitdiffstats
path: root/_examples
diff options
context:
space:
mode:
authorfatelei <fatelei@gmail.com>2020-08-02 12:21:36 +0800
committerfatelei <fatelei@gmail.com>2020-08-22 17:11:16 +0800
commit0518e8de71e33311f8dc8da7b7e684ec786eb27b (patch)
treed1301a11411008dca8803a21e09e047d24e363ea /_examples
parentcded5b685b8a8032605c5704c567c6340dc3953a (diff)
downloadgo-git-0518e8de71e33311f8dc8da7b7e684ec786eb27b.tar.gz
chore: add an exmaple: clone with ssh
Diffstat (limited to '_examples')
-rw-r--r--_examples/README.md1
-rw-r--r--_examples/clone/auth/ssh/main.go52
2 files changed, 53 insertions, 0 deletions
diff --git a/_examples/README.md b/_examples/README.md
index 80d4dd5..92b9d4d 100644
--- a/_examples/README.md
+++ b/_examples/README.md
@@ -10,6 +10,7 @@ Here you can find a list of annotated _go-git_ examples:
using a username and password.
- [personal access token](clone/auth/basic/access_token/main.go) - Cloning
a repository using a GitHub personal access token.
+ - [ssh private key](clone/auth/ssh/main.go) - Cloning a repository using a ssh private key.
- [commit](commit/main.go) - Commit changes to the current branch to an existent repository.
- [push](push/main.go) - Push repository to default remote (origin).
- [pull](pull/main.go) - Pull changes from a remote repository.
diff --git a/_examples/clone/auth/ssh/main.go b/_examples/clone/auth/ssh/main.go
new file mode 100644
index 0000000..1e06e44
--- /dev/null
+++ b/_examples/clone/auth/ssh/main.go
@@ -0,0 +1,52 @@
+package main
+
+import (
+ "fmt"
+ "os"
+
+ git "github.com/go-git/go-git/v5"
+ . "github.com/go-git/go-git/v5/_examples"
+ "github.com/go-git/go-git/v5/plumbing/transport/ssh"
+)
+
+func main() {
+ CheckArgs("<url>", "<directory>", "<private_key_file>")
+ url, directory, privateKeyFile := os.Args[1], os.Args[2], os.Args[3]
+ var password string
+ if len(os.Args) == 5 {
+ password = os.Args[4]
+ }
+
+ _, err := os.Stat(privateKeyFile)
+ if err != nil {
+ Warning("read file %s failed %s\n", privateKeyFile, err.Error())
+ return
+ }
+
+ // Clone the given repository to the given directory
+ Info("git clone %s ", url)
+ publicKeys, err := ssh.NewPublicKeysFromFile("git", privateKeyFile, password)
+ if err != nil {
+ Warning("generate publickeys failed: %s\n", err.Error())
+ return
+ }
+
+ r, err := git.PlainClone(directory, false, &git.CloneOptions{
+ // The intended use of a GitHub personal access token is in replace of your password
+ // because access tokens can easily be revoked.
+ // https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/
+ Auth: publicKeys,
+ URL: url,
+ Progress: os.Stdout,
+ })
+ CheckIfError(err)
+
+ // ... retrieving the branch being pointed by HEAD
+ ref, err := r.Head()
+ CheckIfError(err)
+ // ... retrieving the commit object
+ commit, err := r.CommitObject(ref.Hash())
+ CheckIfError(err)
+
+ fmt.Println(commit)
+}