Read a file after cloning a repository with go-git

Issue

I want to be able to do run-time git manipulations with go.

I recently discovered the go-git package which comes in very handy to this end.

I was also able to perform pull operations, more or less as follows:

import {
  git "gopkg.in/src-d/go-git.v4"
}

repo, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
    URL: "https://github.com/pkaramol/myrepo",
})

err := repo.Pull(&git.PullOptions{
    RemoteName: "origin"
})

My question is, assuming I am using in-memory checkout of the repo as above), how will I be able to read in (my go program) a file from the repository? i.e. assuming the file

https://github.com/pkaramol/myrepo/someConfig.yaml

Would it be preferable (in case I need just this particular file) to perform a git clone (still in mem) of only the particular file?

Solution

From the docs:

Clone a repository into the given Storer and worktree Filesystem with the given options, if worktree is nil a bare repository is created.

Don’t pass a nil filesystem if you want access to the worktree. Use something like gopkg.in/src-d/go-billy.v4/memfs.Memory:

package main

import (
    "gopkg.in/src-d/go-git.v4"
    "gopkg.in/src-d/go-git.v4/storage/memory"
    "gopkg.in/src-d/go-billy.v4/memfs"
)

func main() {
    fs := memfs.New()

    repo, err := git.Clone(memory.NewStorage(), fs, &git.CloneOptions{
        URL: "https://github.com/pkaramol/myrepo",
    })

    file, err := fs.Open("someConfig.yaml")
}

You cannot clone a single file (that’s not how git works), but you can limit the number of commits that are downloaded using CloneOptions.Depth.

Answered By – Peter

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published