I want to clone a specific repository, fetch all tags and iterate through them. For each tag I want to checkout a specific file ( package.json ) in the root directory. If no file is present, it should continue, otherwise it should pass it over so I can inspect it.
I started with the following code ( my first Go application ... )
package main
import (
"fmt"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory"
"os"
)
func main() {
authentication := &http.BasicAuth{
Username: "me",
Password: "my-key",
}
repositoryUrl := "my-repo-url"
inMemoryStorage := memory.NewStorage()
inMemoryFilesystem := memfs.New()
repository, err := cloneRepository(repositoryUrl, authentication, inMemoryStorage, inMemoryFilesystem)
if err != nil {
handleError(err)
}
tagsIterator, err := repository.Tags()
if err != nil {
handleError(err)
}
err = tagsIterator.ForEach(func(tag *plumbing.Reference) error {
fmt.Println(tag.Name().Short()) // for debugging purposes
// checkout package.json file ( at root ) via tag
return nil
})
if err != nil {
handleError(err)
}
}
func cloneRepository(repositoryUrl string, authentication *http.BasicAuth, inMemoryStorage *memory.Storage, inMemoryFilesystem billy.Filesystem) (*git.Repository, error) {
return git.Clone(inMemoryStorage, inMemoryFilesystem, &git.CloneOptions{
URL: repositoryUrl,
Auth: authentication,
})
}
func handleError(err error) {
fmt.Println(err)
os.Exit(1)
}
Does someone know how to try checking out the file inside the loop by a given tag?
You don't need to "check out" anything if all you want is the file content; you can extract that directly from the repository. But first, caveats: I am neither an experienced Go programmer, nor have I ever worked with
go-gitbefore, so there may be a more optimal way of doing this.Starting with a tag, you can:
package.jsonThe above steps might look something like this:
The above function will, given a commit reference, look for
filenamein the top level of the repository (as written it does not traverse subdirectories). You would need to modify thetagsIterator.ForEachloop in yourmainfunction to do something like this:I don't know if this is what you were looking for, but it was interesting learning about the
go-gitpackage.