pigfox
pigfox

Reputation: 1401

Get Git status from Go from a different directory

I need to get a list of modified files from a different directory.

func main() {
    log.Println("Starting Site map")
    dir := "/media/my_path/ubuntu/"

    git0 := "git --git-dir=" + dir + ".git --work-tree=" + dir + " status"
    log.Println(git0) //<-- works when pasted in console
    cmd0 := exec.Command("git", git0)
    status0, err := cmd0.Output()
    if err != nil {
        log.Println(whereami.WhereAmI(), err)
    }
    log.Println(status0)

    git := "git --git-dir=" + dir + ".git --work-tree=" + dir
    log.Println(git)
    cmd := exec.Command("git", "status", git)
    status, err := cmd.Output()
    if err != nil {
        log.Println(whereami.WhereAmI(), err)
    }
    log.Println(status)
    log.Println("End Site map")
}

The I have the following output:

2021/05/24 11:38:07 Starting Site map
2021/05/24 11:38:07 git --git-dir=/media/my_path/ubuntu/.git --work-tree=/media/my_path/ubuntu/ status
2021/05/24 11:38:07 File: main.go  Function: main.main Line: 19 exit status 1
2021/05/24 11:38:07 []
2021/05/24 11:38:07 git --git-dir=/media/my_path/ubuntu/.git --work-tree=/media/my_path/ubuntu/
2021/05/24 11:38:07 File: main.go  Function: main.main Line: 28 exit status 128
2021/05/24 11:38:07 []
2021/05/24 11:38:07 End Site map

This command: git --git-dir=/media/my_path/ubuntu/.git --work-tree=/media/my_path/ubuntu/ status It works fine when pasted into the console.

The expected result would be array containing modified files.

Upvotes: 0

Views: 97

Answers (2)

Zombo
Zombo

Reputation: 1

This works for me:

package main

import (
   "os"
   "os/exec"
)

func main() {
   c := exec.Command("git", "status")
   c.Dir = "/media/my_path/ubuntu"
   c.Stdout = os.Stdout
   c.Run()
}

https://golang.org/pkg/os/exec#Cmd.Dir

Upvotes: 1

grg
grg

Reputation: 5884

exec.Command takes a command and some arguments.

You’re calling it with ‘git’, then ‘git …’ as an argument, which is executed like

git "git --git-dir …"

which isn’t going to work.


  • Don’t repeat the command in the argument.
  • Use individual arguments.
  • Provide the path to the git command.

Each argument should be a separate string comma separated.

exec.Command("/path/to/git", "--git-dir=" + dir + ".git", "--work-tree=" + dir, "status")

Upvotes: 1

Related Questions