Get Git status from Go from a different directory

Asked By: Anonymous

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.


Solution

Answered By: Anonymous

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")
techinplanet staff

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno