guard: add create PR message on git push #611

Respond to a successful push with a URL to create a PR pointing to the default branch. This behavior is made to mimic other Git forges.

Signed-off-by: Samuel Shuert me@thecoded.prof

Changed files
+24
hook
+24
hook/hook.go
···
"strings"
"github.com/urfave/cli/v3"
+
"tangled.org/core/idresolver"
+
"tangled.org/core/knotserver/git"
)
type HookResponse struct {
···
client := &http.Client{}
+
gr, err := git.PlainOpen(gitDir)
+
defaultBranch, err := gr.FindMainBranch()
+
if err != nil {
+
fmt.Fprintln(os.Stderr, "failed to retrieve default branch")
+
return nil
+
}
+
gitPath := strings.Split(gitDir, "/")
+
repoName := gitPath[len(gitPath)-1]
+
userIdent, err := idresolver.DefaultResolver().ResolveIdent(ctx, userDid)
+
lines, err := git.ParsePostReceive(strings.NewReader(payload))
+
if err != nil {
+
return fmt.Errorf("failed to parse post-receive payload: %w", err)
+
}
+
for _, line := range lines {
+
if line.OldSha.IsZero() && line.OldSha != line.NewSha {
+
fmt.Fprintln(os.Stderr, "​")
+
fmt.Fprintf(os.Stderr, "Create a PR pointing to %s\n", defaultBranch)
+
fmt.Fprintf(os.Stderr, "\thttps://tangled.org/@%s/%s/compare/%s...%s\n", userIdent.Handle.String(), repoName, defaultBranch, strings.TrimPrefix(line.Ref, "refs/heads/"))
+
fmt.Fprintln(os.Stderr, "​")
+
}
+
}
+
req, err := http.NewRequest("POST", "http://"+endpoint+"/hooks/post-receive", strings.NewReader(payload))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)