package git import ( "errors" "farga/lib" "fmt" "io" "os" "path/filepath" "strings" git "github.com/go-git/go-git/v6" "github.com/go-git/go-git/v6/plumbing" "github.com/go-git/go-git/v6/plumbing/object" "github.com/google/uuid" ) var ErrEmptyRepo = errors.New("git: repository has no branches. (blank repo)") var ErrRepoDoesNotExist = errors.New("git: no such repository exists.") var ErrRepoHasNoBranches = errors.New("git: repository has no branches.") var ErrRepoHasNoHead = errors.New("git: repository has no HEAD.") var ErrInvalidBranch = errors.New("git: no such branch exists.") func RepoPath(user uuid.UUID, repo uuid.UUID) string { base, err := filepath.Abs(lib.GitReposDir) if err != nil { return "" } return strings.TrimSuffix(filepath.Join( base, user.String(), repo.String(), )+"/", ".git") } // branch new repos start on, and the first choice when HEAD needs repointing. const DefaultBranch = "main" // creates a git repo func InitRepo(userID uuid.UUID, repoID uuid.UUID) (*git.Repository, error) { repoPath := RepoPath(userID, repoID) // bare repo with HEAD -> main. if the first push uses a different branch, FixHead repoints it. return git.PlainInit(repoPath, true, git.WithDefaultBranch(plumbing.NewBranchReferenceName(DefaultBranch))) } type GitRepo struct { Git *git.Repository Head *plumbing.Reference ShortHash string LatestCommit *object.Commit Readme ReadmeType Files []File } // opens a git repo by the defined branch (if empty, HEAD will be used) func Repo(userID uuid.UUID, repoID uuid.UUID, branch string) (*GitRepo, error) { path := RepoPath(userID, repoID) repo, err := git.PlainOpen(path) if err != nil { switch err { case git.ErrRepositoryNotExists: return nil, ErrRepoDoesNotExist default: return nil, err } } return loadRepo(repo, branch) } // opens a git repo from the part of a URL that follows /tree/, /blob/, etc. // branch names might contain slashes ("feature/login"), so the branch can't be // told apart from the file path by looking at the URL alone. Returns the repo // opened at that branch, plus whatever was left over as the file path. func RepoAtRefPath(userID uuid.UUID, repoID uuid.UUID, refPath string) (*GitRepo, string, error) { repo, err := git.PlainOpen(RepoPath(userID, repoID)) if err != nil { if err == git.ErrRepositoryNotExists { return nil, "", ErrRepoDoesNotExist } return nil, "", err } branch, filePath, err := SplitRefPath(repo, refPath) if err != nil { repo.Close() return nil, "", err } gitRepo, err := loadRepo(repo, branch) if err != nil { repo.Close() return nil, "", err } return gitRepo, filePath, nil } // splits "feature/login/src/main.go" into ("feature/login", "src/main.go") by // checking which leading segments name an existing branch. Git never lets // "a" and "a/b" both exist as branches, so at most one prefix can match. func SplitRefPath(repo *git.Repository, refPath string) (branch string, filePath string, err error) { segments := strings.Split(strings.Trim(refPath, "/"), "/") for i := 1; i <= len(segments); i++ { candidate := strings.Join(segments[:i], "/") if len(candidate) > lib.GitBranchMaxLen { break } if !lib.GitBranchRegex.MatchString(candidate) { continue } _, refErr := repo.Reference(plumbing.NewBranchReferenceName(candidate), false) if refErr == nil { return candidate, strings.Join(segments[i:], "/"), nil } if !errors.Is(refErr, plumbing.ErrReferenceNotFound) { return "", "", refErr } } return "", "", ErrInvalidBranch } func loadRepo(repo *git.Repository, branch string) (*GitRepo, error) { head, err := ResolveHead(repo, branch) // potentially nil. if err != nil && err != ErrRepoHasNoHead { return nil, err } var latestCommit *object.Commit var shortHash string // extra info if head != nil { latestCommit, err = object.GetCommit(repo.Storer, head.Hash()) if err != nil { fmt.Println(err) } else { shortHash, err = ShortenHash(head.Hash().String()) } } return &GitRepo{ Git: repo, ShortHash: shortHash, Head: head, LatestCommit: latestCommit, }, nil } // resolves the head of a git repo func ResolveHead(repo *git.Repository, branchName string) (*plumbing.Reference, error) { // if a branch was provided if branchName != "" { ref, err := repo.Reference(plumbing.NewBranchReferenceName(branchName), false) if errors.Is(err, plumbing.ErrReferenceNotFound) { return nil, ErrInvalidBranch // doesn't exist. } if err != nil { return nil, err } return ref, nil } ref, err := repo.Head() // get HEAD as default if err == nil { return ref, nil } if !errors.Is(err, plumbing.ErrReferenceNotFound) { return nil, err } // HEAD points at a missing branch (or there are no branches yet) ref, err = fallbackBranch(repo) if err != nil { return nil, err } if ref == nil { return nil, ErrRepoHasNoHead } return ref, nil } // picks the branch HEAD should point to: main and if not, master, then the first branch. // returns nil if the repo has no branches. func fallbackBranch(repo *git.Repository) (*plumbing.Reference, error) { for _, name := range []string{DefaultBranch, "master"} { ref, err := repo.Reference(plumbing.NewBranchReferenceName(name), false) if err == nil { return ref, nil } if !errors.Is(err, plumbing.ErrReferenceNotFound) { return nil, err } } branches, err := repo.Branches() if err != nil { return nil, err } defer branches.Close() first, err := branches.Next() if errors.Is(err, io.EOF) { return nil, nil // no branches } return first, err } // gets the tree from a commit. func BaseTree(repo *git.Repository, head *plumbing.Reference) (*object.Tree, error) { commit, err := object.GetCommit(repo.Storer, head.Hash()) if err != nil { return nil, err } return commit.Tree() } // deletes a repo on-disk. func DeleteRepo(userID uuid.UUID, repoID uuid.UUID) { os.RemoveAll(RepoPath(userID, repoID)) } // points HEAD at an existing branch if it currently refers to a missing one // (e.g. HEAD -> main, but only master was pushed). run after pushes. func FixHead(path string) error { repo, err := git.PlainOpen(path) if err != nil { return err } head, err := repo.Reference(plumbing.HEAD, false) if err != nil { return err } if head.Type() != plumbing.SymbolicReference { return nil // detached HEAD, leave it alone } if _, err := repo.Reference(head.Target(), false); err == nil { return nil // HEAD target exists, nothing to fix } else if !errors.Is(err, plumbing.ErrReferenceNotFound) { return err } target, err := fallbackBranch(repo) if err != nil || target == nil { return err // nil target: no branches yet (empty repo) } return repo.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, target.Name())) }