@@ -20,16 +20,48 @@ package source
2020
2121import (
2222 "fmt"
23+ "path/filepath"
2324
2425 git2go "github.com/libgit2/git2go/v34"
2526)
2627
28+ const (
29+ // The error returned by libgit2 when the user is not the owner of the git repository.
30+ safeDirectoryNotFoundErrorMsg = "config value 'safe.directory' was not found"
31+ )
32+
33+ // isSafeDirectoryNotFoundError checks if the error is a safe.directory not found error.
34+ func isSafeDirectoryNotFoundError (err error ) bool {
35+ return err .Error () == safeDirectoryNotFoundErrorMsg
36+ }
37+
2738type git struct {}
2839
2940func (g * git ) Parse (workspace string ) (* Info , error ) {
41+ absWorkspace , err := filepath .Abs (workspace )
42+ if err != nil {
43+ return nil , fmt .Errorf ("failed to get absolute path of workspace: %w" , err )
44+ }
45+
3046 repo , err := git2go .OpenRepository (workspace )
3147 if err != nil {
32- return nil , fmt .Errorf ("failed to open repository at %s: %w" , workspace , err )
48+ // Try to set safe.directory manually if it is not found, and try to open repository again.
49+ if isSafeDirectoryNotFoundError (err ) {
50+ config , err := git2go .OpenDefault ()
51+ if err != nil {
52+ return nil , fmt .Errorf ("failed to open config: %w" , err )
53+ }
54+ defer config .Free ()
55+
56+ if err := config .SetString ("safe.directory" , absWorkspace ); err != nil {
57+ return nil , fmt .Errorf ("failed to set safe.directory: %w" , err )
58+ }
59+ }
60+
61+ repo , err = git2go .OpenRepository (workspace )
62+ if err != nil {
63+ return nil , fmt .Errorf ("failed to open repository at %s: %w" , workspace , err )
64+ }
3365 }
3466 defer repo .Free ()
3567
0 commit comments