How do you say "Git add myfile in directory mydir" in OCamlese?

For some of my OCaml-made scripts, I would like to be able to express the following instruction :

Go to directory mydir, and inside it do git add myfile.

I tried the following in the toplevel :

Sys.chdir "mydir" ;; 
Sys.command "git add myfile" ;;

It doesn’t work (it’s a 128 Unix error code and says fatal: pathspec myfile' did not match any files) even though the .git does exist, the path is correct and if I do cd mydir;git add myfile in the shell it works just fine.

Any ideas ?

If it matters, I’m using OCaml 4.11.0 on my 10.14.6 Mac

You might want to look into how to use “truss” (on Linux I’d use “strace”).

It works fine on Ubuntu Linux:

        OCaml version 4.12.0

# Sys.chdir "test";;
- : unit = ()
# Sys.command "ls";;
- : int = 0
# Sys.command "ls -la";;
total 8
drwxrwxr-x  2 chet chet 4096 Sep  6 11:46 .
drwxrwxr-x 26 chet chet 4096 Sep  6 11:46 ..
- : int = 0
# Sys.command "git init";;
Initialized empty Git repository in /home/chet/Hack/Camlp5/tmp/test/.git/
- : int = 0
# Sys.command "touch argle";;
- : int = 0
# Sys.command "git add argle";;
- : int = 0
# Sys.command "git status";;
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
	new file:   argle

- : int = 0
# 
$ ls -la test
total 12
drwxrwxr-x  3 chet chet 4096 Sep  6 11:46 .
drwxrwxr-x 26 chet chet 4096 Sep  6 11:46 ..
-rw-rw-r--  1 chet chet    0 Sep  6 11:46 argle
drwxrwxr-x  7 chet chet 4096 Sep  6 11:46 .git
$ (cd test && git status)
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
	new file:   argle

Unrelated to OCaml and your toplevel issue, but I do all my git-scripting with the -C option:

   -C <path>
       Run as if git was started in <path> instead of the current working directory. When multiple -C options are given, each
       subsequent non-absolute -C <path> is interpreted relative to the preceding -C <path>. If <path> is present but empty,
       e.g.  -C "", then the current working directory is left unchanged.

       This option affects options that expect path name like --git-dir and --work-tree in that their interpretations of the
       path names would be made relative to the working directory caused by the -C option. For example the following
       invocations are equivalent:

           git --git-dir=a.git --work-tree=b -C c status
           git --git-dir=c/a.git --work-tree=c/b status
2 Likes