Skip to content

Commit 0518e8d

Browse files
committed
chore: add an exmaple: clone with ssh
1 parent cded5b6 commit 0518e8d

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

_examples/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Here you can find a list of annotated _go-git_ examples:
1010
using a username and password.
1111
- [personal access token](clone/auth/basic/access_token/main.go) - Cloning
1212
a repository using a GitHub personal access token.
13+
- [ssh private key](clone/auth/ssh/main.go) - Cloning a repository using a ssh private key.
1314
- [commit](commit/main.go) - Commit changes to the current branch to an existent repository.
1415
- [push](push/main.go) - Push repository to default remote (origin).
1516
- [pull](pull/main.go) - Pull changes from a remote repository.

_examples/clone/auth/ssh/main.go

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"os"
6+
7+
git "github.com/go-git/go-git/v5"
8+
. "github.com/go-git/go-git/v5/_examples"
9+
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
10+
)
11+
12+
func main() {
13+
CheckArgs("<url>", "<directory>", "<private_key_file>")
14+
url, directory, privateKeyFile := os.Args[1], os.Args[2], os.Args[3]
15+
var password string
16+
if len(os.Args) == 5 {
17+
password = os.Args[4]
18+
}
19+
20+
_, err := os.Stat(privateKeyFile)
21+
if err != nil {
22+
Warning("read file %s failed %s\n", privateKeyFile, err.Error())
23+
return
24+
}
25+
26+
// Clone the given repository to the given directory
27+
Info("git clone %s ", url)
28+
publicKeys, err := ssh.NewPublicKeysFromFile("git", privateKeyFile, password)
29+
if err != nil {
30+
Warning("generate publickeys failed: %s\n", err.Error())
31+
return
32+
}
33+
34+
r, err := git.PlainClone(directory, false, &git.CloneOptions{
35+
// The intended use of a GitHub personal access token is in replace of your password
36+
// because access tokens can easily be revoked.
37+
// https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/
38+
Auth: publicKeys,
39+
URL: url,
40+
Progress: os.Stdout,
41+
})
42+
CheckIfError(err)
43+
44+
// ... retrieving the branch being pointed by HEAD
45+
ref, err := r.Head()
46+
CheckIfError(err)
47+
// ... retrieving the commit object
48+
commit, err := r.CommitObject(ref.Hash())
49+
CheckIfError(err)
50+
51+
fmt.Println(commit)
52+
}

0 commit comments

Comments
 (0)