//go:build !gitgo // +build !gitgo package sync import ( "bytes" "fmt" "os/exec" "strings" ) // GitImporter implements an Importer, where files to imports are located // inside a local directory from your filesystem, backed by git (binary). type GitImporter struct { li LocalImporter Remote string } func NewGitImporter(li LocalImporter, remote string) GitImporter { return GitImporter{ li: li, Remote: remote, } } func (i GitImporter) Kind() string { cmdshow := exec.Command("git", "-C", i.li.Base, "show") var outshow bytes.Buffer cmdshow.Stdout = &outshow err := cmdshow.Run() var commit string if err != nil { commit = fmt.Sprintf("error (%s)", err.Error()) } else { commit, err = outshow.ReadString('\n') if err == nil { commit = strings.TrimPrefix(commit, "commit ") } else { commit = fmt.Sprintf("error (%s)", err.Error()) } } return "git originated from " + i.Remote + " on " + i.li.Kind() + ", currently on commit " + commit } func (i GitImporter) Init() error { // Check if the directory exists, create it if needed if err := i.li.Init(); err != nil { return err } // If the directory is empty, clone it if n, err := countFileInDir(i.li.Base); err != nil { return err } else if n == 0 { cmdclone := exec.Command("git", "-C", i.li.Base, "clone", "--recursive", i.Remote) stdout, err := cmdclone.CombinedOutput() if err != nil { return fmt.Errorf("%w:\n%s", err, stdout) } } // Check if the .git directory exists, change the origin remote to our cmdremote := exec.Command("git", "-C", i.li.Base, "remote", "set-url", "origin", i.Remote) stdout, err := cmdremote.CombinedOutput() if err != nil { return fmt.Errorf("%w:\n%s", err, stdout) } return nil } func (i GitImporter) Sync() error { cmdremote := exec.Command("git", "-C", i.li.Base, "pull", "--rebase", "--force", "--recurse-submodules=yes", "origin") stdout, err := cmdremote.CombinedOutput() if err != nil { return fmt.Errorf("%w:\n%s", err, stdout) } return nil }