udondan
udondan

Reputation: 59989

How to pass arguments correctly to syscall (git)?

I am trying to clone a git repository by calling git via syscall. (I know there is git2go but that's not what I want. I definitely want to do a syscall)

git, lookErr := exec.LookPath("git")

if lookErr != nil {
    fmt.Fprintf(os.Stderr, "%s\n", lookErr)
    os.Exit(126)
}

args := []string{"clone", "http://github.com/some/repo.git"}

var env = os.Environ()

execErr := syscall.Exec(git, args, env)

if execErr != nil {
  panic(execErr)
}

So what I want to execute is git clone http://github.com/some/repo.git and executing this manually works just fine. But when I run it in go like in the code snippet above, git fails with this:

git: 'http://github.com/some/repo.git' is not a git command. See 'git --help'.

Why would git interpret the 2nd argument as another command? It is supposed to be the remote <repo> URL, git clone [options] [--] <repo> [<dir>].

How do I pass the arguments correctly so git has the expected behavior?

Upvotes: 2

Views: 143

Answers (1)

Ainar-G
Ainar-G

Reputation: 36199

The first argument of argv is usually a program's name, so just add it there:

args := []string{git, "clone", "http://github.com/some/repo.git"}
var env = os.Environ()
if err := syscall.Exec(git, args, env); err != nil {
    panic(err)
}

See also: os.Args variable.

Upvotes: 2

Related Questions