add(repository): discover repository informations

This implemtation determines the git remote origin url and extracts the
information for the owner and repo names for the api url's. WIP for #2.
This commit is contained in:
2023-10-19 22:29:29 +02:00
parent 0e6efacd13
commit 3a04085d3a
3 changed files with 76 additions and 2 deletions

37
internal/gitw/discover.go Normal file
View File

@@ -0,0 +1,37 @@
package gitw
import (
"errors"
"fmt"
"os/exec"
"regexp"
"strings"
"gitea.yves-biener.de/yves-biener/gitwarrior/internal/gitea"
)
func Discover() (gitea.Repository, error) {
var repository gitea.Repository
cmd := exec.Command("git", "remote", "get-url", "origin")
out, err := cmd.Output()
if err != nil {
return repository, err
}
re := regexp.MustCompile("^git@.*:(.*).git")
matches := re.FindAllStringSubmatch(string(out), -1)
var match string
if len(matches) > 0 && len(matches[0]) == 2 {
match = matches[0][1] // get the first match which is the Full_name of the repository
if len(match) <= 0 {
return repository, errors.New("No matching group found. Are you in a git repository?")
}
} else {
return repository, errors.New("No matching group found. Are you in a git repository?")
}
repo := strings.Split(match, "/")
if len(repo) != 2 {
msg := fmt.Sprintf("Expected remote url to contain {owner}/{repo}, but found: %#v", repo)
return repository, errors.New(msg)
}
return gitea.NewRepository(repo[1], repo[0]), nil
}