Skip to content

Instantly share code, notes, and snippets.

@rogerwelin
Last active January 20, 2021 21:52
Show Gist options
  • Save rogerwelin/7b1d2718bfbd94ecdfef0b9854fff99d to your computer and use it in GitHub Desktop.
Save rogerwelin/7b1d2718bfbd94ecdfef0b9854fff99d to your computer and use it in GitHub Desktop.
use go-git & memfs to push files to remote
package main
import (
"fmt"
billy "github.com/go-git/go-billy/v5"
memfs "github.com/go-git/go-billy/v5/memfs"
git "github.com/go-git/go-git/v5"
config "github.com/go-git/go-git/v5/config"
http "github.com/go-git/go-git/v5/plumbing/transport/http"
memory "github.com/go-git/go-git/v5/storage/memory"
)
var storer *memory.Storage
var fs billy.Filesystem
func main() {
storer = memory.NewStorage()
fs = memfs.New()
// Authentication
auth := &http.BasicAuth{
Username: "abc123",
Password: "abc123",
}
r, err := git.Init(storer, fs)
if err != nil {
fmt.Printf("error: %v", err)
return
}
_, err = r.CreateRemote(&config.RemoteConfig{
Name: "origin",
URLs: []string{"https://gitlab.com/rogerwelin/go-git-example.git"},
})
w, err := r.Worktree()
if err != nil {
fmt.Printf("%v", err)
return
}
// Create new file
filePath := "roger.txt"
newFile, err := fs.Create(filePath)
if err != nil {
return
}
newFile.Write([]byte("My new file"))
newFile.Close()
// Run git status before adding the file to the worktree
fmt.Println(w.Status())
// git add $filePath
w.Add(filePath)
// Run git status after the file has been added adding to the worktree
fmt.Println(w.Status())
// git commit -m $message
w.Commit("Added my new file", &git.CommitOptions{})
//Push the code to the remote
err = r.Push(&git.PushOptions{
RemoteName: "origin",
Auth: auth,
})
if err != nil {
return
}
fmt.Println("Remote updated.", filePath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment