EnsureRepository prepares the local git working tree by cloning or opening the repository.
()
| 98 | |
| 99 | // EnsureRepository prepares the local git working tree by cloning or opening the repository. |
| 100 | func (s *GitTokenStore) EnsureRepository() error { |
| 101 | s.dirLock.Lock() |
| 102 | if s.remote == "" { |
| 103 | s.dirLock.Unlock() |
| 104 | return fmt.Errorf("git token store: remote not configured") |
| 105 | } |
| 106 | if s.baseDir == "" { |
| 107 | s.dirLock.Unlock() |
| 108 | return fmt.Errorf("git token store: base directory not configured") |
| 109 | } |
| 110 | repoDir := s.repoDir |
| 111 | if repoDir == "" { |
| 112 | repoDir = filepath.Dir(s.baseDir) |
| 113 | if repoDir == "" || repoDir == "." { |
| 114 | repoDir = s.baseDir |
| 115 | } |
| 116 | s.repoDir = repoDir |
| 117 | } |
| 118 | if s.configDir == "" { |
| 119 | s.configDir = filepath.Join(repoDir, "config") |
| 120 | } |
| 121 | authDir := filepath.Join(repoDir, "auths") |
| 122 | configDir := filepath.Join(repoDir, "config") |
| 123 | gitDir := filepath.Join(repoDir, ".git") |
| 124 | authMethod := s.gitAuth() |
| 125 | var initPaths []string |
| 126 | if _, err := os.Stat(gitDir); errors.Is(err, fs.ErrNotExist) { |
| 127 | if errMk := os.MkdirAll(repoDir, 0o700); errMk != nil { |
| 128 | s.dirLock.Unlock() |
| 129 | return fmt.Errorf("git token store: create repo dir: %w", errMk) |
| 130 | } |
| 131 | cloneOpts := &git.CloneOptions{Auth: authMethod, URL: s.remote} |
| 132 | if s.branch != "" { |
| 133 | cloneOpts.ReferenceName = plumbing.NewBranchReferenceName(s.branch) |
| 134 | } |
| 135 | if _, errClone := git.PlainClone(repoDir, cloneOpts); errClone != nil { |
| 136 | if errors.Is(errClone, transport.ErrEmptyRemoteRepository) { |
| 137 | _ = os.RemoveAll(gitDir) |
| 138 | repo, errInit := git.PlainInit(repoDir, false) |
| 139 | if errInit != nil { |
| 140 | s.dirLock.Unlock() |
| 141 | return fmt.Errorf("git token store: init empty repo: %w", errInit) |
| 142 | } |
| 143 | if s.branch != "" { |
| 144 | headRef := plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName(s.branch)) |
| 145 | if errHead := repo.Storer.SetReference(headRef); errHead != nil { |
| 146 | s.dirLock.Unlock() |
| 147 | return fmt.Errorf("git token store: set head to branch %s: %w", s.branch, errHead) |
| 148 | } |
| 149 | } |
| 150 | if _, errRemote := repo.Remote("origin"); errRemote != nil { |
| 151 | if _, errCreate := repo.CreateRemote(&config.RemoteConfig{ |
| 152 | Name: "origin", |
| 153 | URLs: []string{s.remote}, |
| 154 | }); errCreate != nil && !errors.Is(errCreate, git.ErrRemoteExists) { |
| 155 | s.dirLock.Unlock() |
| 156 | return fmt.Errorf("git token store: configure remote: %w", errCreate) |
| 157 | } |