Remove underscores from Go code, pt 3
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "bufio" "context" "errors" "io" "net/http" "net/url" "strings" "github.com/jackc/pgx/v5" )
func fedauth(ctx context.Context, user_id int, service, remote_username, pubkey string) (bool, error) {
func fedauth(ctx context.Context, userID int, service, remote_username, pubkey string) (bool, error) {
var err error var resp *http.Response matched := false username_escaped := url.PathEscape(remote_username) switch service { case "sr.ht": resp, err = http.Get("https://meta.sr.ht/~" + username_escaped + ".keys") case "github": resp, err = http.Get("https://github.com/" + username_escaped + ".keys") case "codeberg": resp, err = http.Get("https://codeberg.org/" + username_escaped + ".keys") case "tangled": resp, err = http.Get("https://tangled.sh/keys/" + username_escaped) // TODO: Don't rely on one webview default: return false, errors.New("unknown federated service") } if err != nil { return false, err } defer func() { _ = resp.Body.Close() }() buf := bufio.NewReader(resp.Body) for { line, err := buf.ReadString('\n') if errors.Is(err, io.EOF) { break } else if err != nil { return false, err } lineSplit := strings.Split(line, " ") if len(lineSplit) < 2 { continue } line = strings.Join(lineSplit[:2], " ") if line == pubkey { matched = true break } } if !matched { return false, nil } var tx pgx.Tx if tx, err = database.Begin(ctx); err != nil { return false, err } defer func() { _ = tx.Rollback(ctx) }()
if _, err = tx.Exec(ctx, `UPDATE users SET type = 'federated' WHERE id = $1 AND type = 'pubkey_only'`, user_id); err != nil {
if _, err = tx.Exec(ctx, `UPDATE users SET type = 'federated' WHERE id = $1 AND type = 'pubkey_only'`, userID); err != nil {
return false, err }
if _, err = tx.Exec(ctx, `INSERT INTO federated_identities (user_id, service, remote_username) VALUES ($1, $2, $3)`, user_id, service, remote_username); err != nil {
if _, err = tx.Exec(ctx, `INSERT INTO federated_identities (user_id, service, remote_username) VALUES ($1, $2, $3)`, userID, service, remote_username); err != nil {
return false, err } if err = tx.Commit(ctx); err != nil { return false, err } return true, nil }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "bytes" "fmt" "strings" "time" "github.com/go-git/go-git/v5/plumbing/object" ) // get_patch_from_commit formats a commit object as if it was returned by // git-format-patch. func fmtCommitPatch(commit *object.Commit) (final string, err error) { var patch *object.Patch var buf bytes.Buffer var author object.Signature var date string var commitTitle, commitDetails string
if _, patch, err = get_patch_from_commit(commit); err != nil {
if _, patch, err = fmtCommitAsPatch(commit); err != nil {
return "", err } author = commit.Author date = author.When.Format(time.RFC1123Z) commitTitle, commitDetails, _ = strings.Cut(commit.Message, "\n") // This date is hardcoded in Git. fmt.Fprintf(&buf, "From %s Mon Sep 17 00:00:00 2001\n", commit.Hash) fmt.Fprintf(&buf, "From: %s <%s>\n", author.Name, author.Email) fmt.Fprintf(&buf, "Date: %s\n", date) fmt.Fprintf(&buf, "Subject: [PATCH] %s\n\n", commitTitle) if commitDetails != "" { commitDetails1, commitDetails2, _ := strings.Cut(commitDetails, "\n") if strings.TrimSpace(commitDetails1) == "" { commitDetails = commitDetails2 } buf.WriteString(commitDetails) buf.WriteString("\n") } buf.WriteString("---\n") fmt.Fprint(&buf, patch.Stats().String()) fmt.Fprintln(&buf) buf.WriteString(patch.String()) fmt.Fprintf(&buf, "\n-- \n2.48.1\n") return buf.String(), nil }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "bytes" "context" "encoding/binary" "errors" "fmt" "io" "net" "os" "path/filepath" "strconv" "strings" "syscall" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/jackc/pgx/v5" "go.lindenii.runxiyu.org/lindenii-common/ansiec" ) var ( errGetFD = errors.New("unable to get file descriptor") errGetUcred = errors.New("failed getsockopt") ) // hooksHandler handles a connection from hookc via the // unix socket. func hooksHandler(conn net.Conn) { var ctx context.Context var cancel context.CancelFunc var ucred *syscall.Ucred var err error var cookie []byte
var pack_to_hook pack_to_hook_t var ssh_stderr io.Writer
var packPass packPass var sshStderr io.Writer
var ok bool
var hook_return_value byte
var hookRet byte
defer conn.Close() ctx, cancel = context.WithCancel(context.Background()) defer cancel() // There aren't reasonable cases where someone would run this as // another user. if ucred, err = getUcred(conn); err != nil { if _, err = conn.Write([]byte{1}); err != nil { return }
wf_error(conn, "\nUnable to get peer credentials: %v", err)
writeRedError(conn, "\nUnable to get peer credentials: %v", err)
return } if ucred.Uid != uint32(os.Getuid()) { if _, err = conn.Write([]byte{1}); err != nil { return }
wf_error(conn, "\nUID mismatch")
writeRedError(conn, "\nUID mismatch")
return } cookie = make([]byte, 64) if _, err = conn.Read(cookie); err != nil { if _, err = conn.Write([]byte{1}); err != nil { return }
wf_error(conn, "\nFailed to read cookie: %v", err)
writeRedError(conn, "\nFailed to read cookie: %v", err)
return }
pack_to_hook, ok = pack_to_hook_by_cookie.Load(string(cookie))
packPass, ok = packPasses.Load(string(cookie))
if !ok { if _, err = conn.Write([]byte{1}); err != nil { return }
wf_error(conn, "\nInvalid handler cookie")
writeRedError(conn, "\nInvalid handler cookie")
return }
ssh_stderr = pack_to_hook.session.Stderr()
sshStderr = packPass.session.Stderr()
_, _ = ssh_stderr.Write([]byte{'\n'})
_, _ = sshStderr.Write([]byte{'\n'})
hook_return_value = func() byte {
hookRet = func() byte {
var argc64 uint64 if err = binary.Read(conn, binary.NativeEndian, &argc64); err != nil {
wf_error(ssh_stderr, "Failed to read argc: %v", err)
writeRedError(sshStderr, "Failed to read argc: %v", err)
return 1 } var args []string for i := uint64(0); i < argc64; i++ { var arg bytes.Buffer for { b := make([]byte, 1) n, err := conn.Read(b) if err != nil || n != 1 {
wf_error(ssh_stderr, "Failed to read arg: %v", err)
writeRedError(sshStderr, "Failed to read arg: %v", err)
return 1 } if b[0] == 0 { break } arg.WriteByte(b[0]) } args = append(args, arg.String()) }
git_env := make(map[string]string)
gitEnv := make(map[string]string)
for {
var env_line bytes.Buffer
var envLine bytes.Buffer
for { b := make([]byte, 1) n, err := conn.Read(b) if err != nil || n != 1 {
wf_error(ssh_stderr, "Failed to read environment variable: %v", err)
writeRedError(sshStderr, "Failed to read environment variable: %v", err)
return 1 } if b[0] == 0 { break }
env_line.WriteByte(b[0])
envLine.WriteByte(b[0])
}
if env_line.Len() == 0 {
if envLine.Len() == 0 {
break }
kv := env_line.String()
kv := envLine.String()
parts := strings.SplitN(kv, "=", 2) if len(parts) < 2 {
wf_error(ssh_stderr, "Invalid environment variable line: %v", kv)
writeRedError(sshStderr, "Invalid environment variable line: %v", kv)
return 1 }
git_env[parts[0]] = parts[1]
gitEnv[parts[0]] = parts[1]
} var stdin bytes.Buffer if _, err = io.Copy(&stdin, conn); err != nil {
wf_error(conn, "Failed to read to the stdin buffer: %v", err)
writeRedError(conn, "Failed to read to the stdin buffer: %v", err)
} switch filepath.Base(args[0]) { case "pre-receive":
if pack_to_hook.direct_access {
if packPass.directAccess {
return 0 } else {
all_ok := true
allOK := true
for {
var line, old_oid, rest, new_oid, ref_name string
var line, oldOID, rest, newIOID, refName string
var found bool
var old_hash, new_hash plumbing.Hash var old_commit, new_commit *object.Commit var git_push_option_count int
var oldHash, newHash plumbing.Hash var oldCommit, newCommit *object.Commit var pushOptCount int
git_push_option_count, err = strconv.Atoi(git_env["GIT_PUSH_OPTION_COUNT"])
pushOptCount, err = strconv.Atoi(gitEnv["GIT_PUSH_OPTION_COUNT"])
if err != nil {
wf_error(ssh_stderr, "Failed to parse GIT_PUSH_OPTION_COUNT: %v", err)
writeRedError(sshStderr, "Failed to parse GIT_PUSH_OPTION_COUNT: %v", err)
return 1 } // TODO: Allow existing users (even if they are already federated or registered) to add a federated user ID... though perhaps this should be in the normal SSH interface instead of the git push interface? // Also it'd be nice to be able to combine users or whatever
if pack_to_hook.contrib_requirements == "federated" && pack_to_hook.user_type != "federated" && pack_to_hook.user_type != "registered" { if git_push_option_count == 0 { wf_error(ssh_stderr, "This repo requires contributors to be either federated or registered users. You must supply your federated user ID as a push option. For example, git push -o fedid=sr.ht:runxiyu")
if packPass.contribReq == "federated" && packPass.userType != "federated" && packPass.userType != "registered" { if pushOptCount == 0 { writeRedError(sshStderr, "This repo requires contributors to be either federated or registered users. You must supply your federated user ID as a push option. For example, git push -o fedid=sr.ht:runxiyu")
return 1 }
for i := 0; i < git_push_option_count; i++ { push_option, ok := git_env[fmt.Sprintf("GIT_PUSH_OPTION_%d", i)]
for i := 0; i < pushOptCount; i++ { pushOpt, ok := gitEnv[fmt.Sprintf("GIT_PUSH_OPTION_%d", i)]
if !ok {
wf_error(ssh_stderr, "Failed to get push option %d", i)
writeRedError(sshStderr, "Failed to get push option %d", i)
return 1 }
if strings.HasPrefix(push_option, "fedid=") { federated_user_identifier := strings.TrimPrefix(push_option, "fedid=") service, username, found := strings.Cut(federated_user_identifier, ":")
if strings.HasPrefix(pushOpt, "fedid=") { fedUserID := strings.TrimPrefix(pushOpt, "fedid=") service, username, found := strings.Cut(fedUserID, ":")
if !found {
wf_error(ssh_stderr, "Invalid federated user identifier %#v does not contain a colon", federated_user_identifier)
writeRedError(sshStderr, "Invalid federated user identifier %#v does not contain a colon", fedUserID)
return 1 }
ok, err := fedauth(ctx, pack_to_hook.user_id, service, username, pack_to_hook.pubkey)
ok, err := fedauth(ctx, packPass.userID, service, username, packPass.pubkey)
if err != nil {
wf_error(ssh_stderr, "Failed to verify federated user identifier %#v: %v", federated_user_identifier, err)
writeRedError(sshStderr, "Failed to verify federated user identifier %#v: %v", fedUserID, err)
return 1 } if !ok {
wf_error(ssh_stderr, "Failed to verify federated user identifier %#v: you don't seem to be on the list", federated_user_identifier)
writeRedError(sshStderr, "Failed to verify federated user identifier %#v: you don't seem to be on the list", fedUserID)
return 1 } break }
if i == git_push_option_count-1 { wf_error(ssh_stderr, "This repo requires contributors to be either federated or registered users. You must supply your federated user ID as a push option. For example, git push -o fedid=sr.ht:runxiyu")
if i == pushOptCount-1 { writeRedError(sshStderr, "This repo requires contributors to be either federated or registered users. You must supply your federated user ID as a push option. For example, git push -o fedid=sr.ht:runxiyu")
return 1 } } } line, err = stdin.ReadString('\n') if errors.Is(err, io.EOF) { break } else if err != nil {
wf_error(ssh_stderr, "Failed to read pre-receive line: %v", err)
writeRedError(sshStderr, "Failed to read pre-receive line: %v", err)
return 1 } line = line[:len(line)-1]
old_oid, rest, found = strings.Cut(line, " ")
oldOID, rest, found = strings.Cut(line, " ")
if !found {
wf_error(ssh_stderr, "Invalid pre-receive line: %v", line)
writeRedError(sshStderr, "Invalid pre-receive line: %v", line)
return 1 }
new_oid, ref_name, found = strings.Cut(rest, " ")
newIOID, refName, found = strings.Cut(rest, " ")
if !found {
wf_error(ssh_stderr, "Invalid pre-receive line: %v", line)
writeRedError(sshStderr, "Invalid pre-receive line: %v", line)
return 1 }
if strings.HasPrefix(ref_name, "refs/heads/contrib/") { if all_zero_num_string(old_oid) { // New branch fmt.Fprintln(ssh_stderr, ansiec.Blue+"POK"+ansiec.Reset, ref_name) var new_mr_id int
if strings.HasPrefix(refName, "refs/heads/contrib/") { if allZero(oldOID) { // New branch fmt.Fprintln(sshStderr, ansiec.Blue+"POK"+ansiec.Reset, refName) var newMRID int
err = database.QueryRow(ctx, "INSERT INTO merge_requests (repo_id, creator, source_ref, status) VALUES ($1, $2, $3, 'open') RETURNING id",
pack_to_hook.repo_id, pack_to_hook.user_id, strings.TrimPrefix(ref_name, "refs/heads/"), ).Scan(&new_mr_id)
packPass.repoID, packPass.userID, strings.TrimPrefix(refName, "refs/heads/"), ).Scan(&newMRID)
if err != nil {
wf_error(ssh_stderr, "Error creating merge request: %v", err)
writeRedError(sshStderr, "Error creating merge request: %v", err)
return 1 }
fmt.Fprintln(ssh_stderr, ansiec.Blue+"Created merge request at", generate_http_remote_url(pack_to_hook.group_path, pack_to_hook.repo_name)+"/contrib/"+strconv.FormatUint(uint64(new_mr_id), 10)+"/"+ansiec.Reset)
fmt.Fprintln(sshStderr, ansiec.Blue+"Created merge request at", generate_http_remote_url(packPass.group_path, packPass.repo_name)+"/contrib/"+strconv.FormatUint(uint64(newMRID), 10)+"/"+ansiec.Reset)
} else { // Existing contrib branch
var existing_merge_request_user_id int var is_ancestor bool
var existingMRUser int var isAncestor bool
err = database.QueryRow(ctx, "SELECT COALESCE(creator, 0) FROM merge_requests WHERE source_ref = $1 AND repo_id = $2",
strings.TrimPrefix(ref_name, "refs/heads/"), pack_to_hook.repo_id, ).Scan(&existing_merge_request_user_id)
strings.TrimPrefix(refName, "refs/heads/"), packPass.repoID, ).Scan(&existingMRUser)
if err != nil { if errors.Is(err, pgx.ErrNoRows) {
wf_error(ssh_stderr, "No existing merge request for existing contrib branch: %v", err)
writeRedError(sshStderr, "No existing merge request for existing contrib branch: %v", err)
} else {
wf_error(ssh_stderr, "Error querying for existing merge request: %v", err)
writeRedError(sshStderr, "Error querying for existing merge request: %v", err)
} return 1 }
if existing_merge_request_user_id == 0 { all_ok = false fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(branch belongs to unowned MR)")
if existingMRUser == 0 { allOK = false fmt.Fprintln(sshStderr, ansiec.Red+"NAK"+ansiec.Reset, refName, "(branch belongs to unowned MR)")
continue }
if existing_merge_request_user_id != pack_to_hook.user_id { all_ok = false fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(branch belongs another user's MR)")
if existingMRUser != packPass.userID { allOK = false fmt.Fprintln(sshStderr, ansiec.Red+"NAK"+ansiec.Reset, refName, "(branch belongs another user's MR)")
continue }
old_hash = plumbing.NewHash(old_oid)
oldHash = plumbing.NewHash(oldOID)
if old_commit, err = pack_to_hook.repo.CommitObject(old_hash); err != nil { wf_error(ssh_stderr, "Daemon failed to get old commit: %v", err)
if oldCommit, err = packPass.repo.CommitObject(oldHash); err != nil { writeRedError(sshStderr, "Daemon failed to get old commit: %v", err)
return 1 } // Potential BUG: I'm not sure if new_commit is guaranteed to be // detectable as they haven't been merged into the main repo's // objects yet. But it seems to work, and I don't think there's // any reason for this to only work intermitently.
new_hash = plumbing.NewHash(new_oid) if new_commit, err = pack_to_hook.repo.CommitObject(new_hash); err != nil { wf_error(ssh_stderr, "Daemon failed to get new commit: %v", err)
newHash = plumbing.NewHash(newIOID) if newCommit, err = packPass.repo.CommitObject(newHash); err != nil { writeRedError(sshStderr, "Daemon failed to get new commit: %v", err)
return 1 }
if is_ancestor, err = old_commit.IsAncestor(new_commit); err != nil { wf_error(ssh_stderr, "Daemon failed to check if old commit is ancestor: %v", err)
if isAncestor, err = oldCommit.IsAncestor(newCommit); err != nil { writeRedError(sshStderr, "Daemon failed to check if old commit is ancestor: %v", err)
return 1 }
if !is_ancestor {
if !isAncestor {
// TODO: Create MR snapshot ref instead
all_ok = false fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(force pushes are not supported yet)")
allOK = false fmt.Fprintln(sshStderr, ansiec.Red+"NAK"+ansiec.Reset, refName, "(force pushes are not supported yet)")
continue }
fmt.Fprintln(ssh_stderr, ansiec.Blue+"POK"+ansiec.Reset, ref_name)
fmt.Fprintln(sshStderr, ansiec.Blue+"POK"+ansiec.Reset, refName)
} } else { // Non-contrib branch
all_ok = false fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(you cannot push to branches outside of contrib/*)")
allOK = false fmt.Fprintln(sshStderr, ansiec.Red+"NAK"+ansiec.Reset, refName, "(you cannot push to branches outside of contrib/*)")
} }
fmt.Fprintln(ssh_stderr) if all_ok { fmt.Fprintln(ssh_stderr, "Overall "+ansiec.Green+"ACK"+ansiec.Reset+" (all checks passed)")
fmt.Fprintln(sshStderr) if allOK { fmt.Fprintln(sshStderr, "Overall "+ansiec.Green+"ACK"+ansiec.Reset+" (all checks passed)")
return 0 } else {
fmt.Fprintln(ssh_stderr, "Overall "+ansiec.Red+"NAK"+ansiec.Reset+" (one or more branches failed checks)")
fmt.Fprintln(sshStderr, "Overall "+ansiec.Red+"NAK"+ansiec.Reset+" (one or more branches failed checks)")
return 1 } } default:
fmt.Fprintln(ssh_stderr, ansiec.Red+"Invalid hook:", args[0]+ansiec.Reset)
fmt.Fprintln(sshStderr, ansiec.Red+"Invalid hook:", args[0]+ansiec.Reset)
return 1 } }()
fmt.Fprintln(ssh_stderr)
fmt.Fprintln(sshStderr)
_, _ = conn.Write([]byte{hook_return_value})
_, _ = conn.Write([]byte{hookRet})
} func serveGitHooks(listener net.Listener) error { for { conn, err := listener.Accept() if err != nil { return err } go hooksHandler(conn) } } func getUcred(conn net.Conn) (ucred *syscall.Ucred, err error) {
var unix_conn *net.UnixConn = conn.(*net.UnixConn)
var unixConn *net.UnixConn = conn.(*net.UnixConn)
var fd *os.File
if fd, err = unix_conn.File(); err != nil {
if fd, err = unixConn.File(); err != nil {
return nil, errGetFD } defer fd.Close() if ucred, err = syscall.GetsockoptUcred(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED); err != nil { return nil, errGetUcred } return ucred, nil }
func all_zero_num_string(s string) bool {
func allZero(s string) bool {
for _, r := range s { if r != '0' { return false } } return true }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "github.com/go-git/go-git/v5"
git_config "github.com/go-git/go-git/v5/config" git_format_config "github.com/go-git/go-git/v5/plumbing/format/config"
gitConfig "github.com/go-git/go-git/v5/config" gitFmtConfig "github.com/go-git/go-git/v5/plumbing/format/config"
)
// git_bare_init_with_default_hooks initializes a bare git repository with the
// gitInit initializes a bare git repository with the
// forge-deployed hooks directory as the hooksPath.
func git_bare_init_with_default_hooks(repo_path string) (err error) {
func gitInit(repoPath string) (err error) {
var repo *git.Repository
var git_config *git_config.Config
var gitConf *gitConfig.Config
if repo, err = git.PlainInit(repo_path, true); err != nil {
if repo, err = git.PlainInit(repoPath, true); err != nil {
return err }
if git_config, err = repo.Config(); err != nil {
if gitConf, err = repo.Config(); err != nil {
return err }
git_config.Raw.SetOption("core", git_format_config.NoSubsection, "hooksPath", config.Hooks.Execs) git_config.Raw.SetOption("receive", git_format_config.NoSubsection, "advertisePushOptions", "true")
gitConf.Raw.SetOption("core", gitFmtConfig.NoSubsection, "hooksPath", config.Hooks.Execs) gitConf.Raw.SetOption("receive", gitFmtConfig.NoSubsection, "advertisePushOptions", "true")
if err = repo.SetConfig(git_config); err != nil {
if err = repo.SetConfig(gitConf); err != nil {
return err } return nil }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "context" "errors" "io" "os" "strings" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/jackc/pgx/v5/pgtype" )
// open_git_repo opens a git repository by group and repo name. func open_git_repo(ctx context.Context, group_path []string, repo_name string) (repo *git.Repository, description string, repo_id int, err error) { var fs_path string
// openRepo opens a git repository by group and repo name. func openRepo(ctx context.Context, groupPath []string, repoName string) (repo *git.Repository, description string, repoID int, err error) { var fsPath string
err = database.QueryRow(ctx, ` WITH RECURSIVE group_path_cte AS ( -- Start: match the first name in the path where parent_group IS NULL SELECT id, parent_group, name, 1 AS depth FROM groups WHERE name = ($1::text[])[1] AND parent_group IS NULL UNION ALL -- Recurse: join next segment of the path SELECT g.id, g.parent_group, g.name, group_path_cte.depth + 1 FROM groups g JOIN group_path_cte ON g.parent_group = group_path_cte.id WHERE g.name = ($1::text[])[group_path_cte.depth + 1] AND group_path_cte.depth + 1 <= cardinality($1::text[]) ) SELECT r.filesystem_path, COALESCE(r.description, ''), r.id FROM group_path_cte g JOIN repos r ON r.group_id = g.id WHERE g.depth = cardinality($1::text[]) AND r.name = $2
`, pgtype.FlatArray[string](group_path), repo_name).Scan(&fs_path, &description, &repo_id)
`, pgtype.FlatArray[string](groupPath), repoName).Scan(&fsPath, &description, &repoID)
if err != nil { return }
repo, err = git.PlainOpen(fs_path)
repo, err = git.PlainOpen(fsPath)
return } // go-git's tree entries are not friendly for use in HTML templates.
type display_git_tree_entry_t struct {
type displayTreeEntry struct {
Name string Mode string Size int64
Is_file bool Is_subtree bool
IsFile bool IsSubtree bool
}
func build_display_git_tree(tree *object.Tree) (display_git_tree []display_git_tree_entry_t) {
func makeDisplayTree(tree *object.Tree) (displayTree []displayTreeEntry) {
for _, entry := range tree.Entries {
display_git_tree_entry := display_git_tree_entry_t{}
displayEntry := displayTreeEntry{}
var err error
var os_mode os.FileMode
var osMode os.FileMode
if os_mode, err = entry.Mode.ToOSFileMode(); err != nil { display_git_tree_entry.Mode = "x---------"
if osMode, err = entry.Mode.ToOSFileMode(); err != nil { displayEntry.Mode = "x---------"
} else {
display_git_tree_entry.Mode = os_mode.String()
displayEntry.Mode = osMode.String()
}
display_git_tree_entry.Is_file = entry.Mode.IsFile()
displayEntry.IsFile = entry.Mode.IsFile()
if display_git_tree_entry.Size, err = tree.Size(entry.Name); err != nil { display_git_tree_entry.Size = 0
if displayEntry.Size, err = tree.Size(entry.Name); err != nil { displayEntry.Size = 0
}
display_git_tree_entry.Name = strings.TrimPrefix(entry.Name, "/")
displayEntry.Name = strings.TrimPrefix(entry.Name, "/")
display_git_tree = append(display_git_tree, display_git_tree_entry)
displayTree = append(displayTree, displayEntry)
}
return display_git_tree
return displayTree
}
func get_recent_commits(repo *git.Repository, head_hash plumbing.Hash, number_of_commits int) (recent_commits []*object.Commit, err error) { var commit_iter object.CommitIter var this_recent_commit *object.Commit
func getRecentCommits(repo *git.Repository, headHash plumbing.Hash, numCommits int) (recentCommits []*object.Commit, err error) { var commitIter object.CommitIter var thisCommit *object.Commit
commit_iter, err = repo.Log(&git.LogOptions{From: head_hash})
commitIter, err = repo.Log(&git.LogOptions{From: headHash})
if err != nil { return nil, err }
recent_commits = make([]*object.Commit, 0) defer commit_iter.Close() if number_of_commits < 0 {
recentCommits = make([]*object.Commit, 0) defer commitIter.Close() if numCommits < 0 {
for {
this_recent_commit, err = commit_iter.Next()
thisCommit, err = commitIter.Next()
if errors.Is(err, io.EOF) {
return recent_commits, nil
return recentCommits, nil
} else if err != nil { return nil, err }
recent_commits = append(recent_commits, this_recent_commit)
recentCommits = append(recentCommits, thisCommit)
} } else {
for range number_of_commits { this_recent_commit, err = commit_iter.Next()
for range numCommits { thisCommit, err = commitIter.Next()
if errors.Is(err, io.EOF) {
return recent_commits, nil
return recentCommits, nil
} else if err != nil { return nil, err }
recent_commits = append(recent_commits, this_recent_commit)
recentCommits = append(recentCommits, thisCommit)
} }
return recent_commits, err
return recentCommits, err
}
func get_patch_from_commit(commit_object *object.Commit) (parent_commit_hash plumbing.Hash, patch *object.Patch, err error) { var parent_commit_object *object.Commit var commit_tree *object.Tree
func fmtCommitAsPatch(commit *object.Commit) (parentCommitHash plumbing.Hash, patch *object.Patch, err error) { var parentCommit *object.Commit var commitTree *object.Tree
parent_commit_object, err = commit_object.Parent(0)
parentCommit, err = commit.Parent(0)
if errors.Is(err, object.ErrParentNotFound) {
if commit_tree, err = commit_object.Tree(); err != nil {
if commitTree, err = commit.Tree(); err != nil {
return }
if patch, err = (&object.Tree{}).Patch(commit_tree); err != nil {
if patch, err = (&object.Tree{}).Patch(commitTree); err != nil {
return } } else if err != nil { return } else {
parent_commit_hash = parent_commit_object.Hash if patch, err = parent_commit_object.Patch(commit_object); err != nil {
parentCommitHash = parentCommit.Hash if patch, err = parentCommit.Patch(commit); err != nil {
return } } return }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" )
// get_ref_hash_from_type_and_name returns the hash of a reference given its
// getRefHash returns the hash of a reference given its
// type and name as supplied in URL queries.
func get_ref_hash_from_type_and_name(repo *git.Repository, ref_type, ref_name string) (ref_hash plumbing.Hash, err error) {
func getRefHash(repo *git.Repository, ref_type, ref_name string) (ref_hash plumbing.Hash, err error) {
var ref *plumbing.Reference switch ref_type { case "": if ref, err = repo.Head(); err != nil { return } ref_hash = ref.Hash() case "commit": ref_hash = plumbing.NewHash(ref_name) case "branch": if ref, err = repo.Reference(plumbing.NewBranchReferenceName(ref_name), true); err != nil { return } ref_hash = ref.Hash() case "tag": if ref, err = repo.Reference(plumbing.NewTagReferenceName(ref_name), true); err != nil { return } ref_hash = ref.Hash() default: panic("Invalid ref type " + ref_type) } return }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "net/http" "path/filepath" "strconv" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" ) func handle_group_index(w http.ResponseWriter, r *http.Request, params map[string]any) { var group_path []string var repos []nameDesc var subgroups []nameDesc var err error var group_id int var group_description string group_path = params["group_path"].([]string) // The group itself err = database.QueryRow(r.Context(), ` WITH RECURSIVE group_path_cte AS ( SELECT id, parent_group, name, 1 AS depth FROM groups WHERE name = ($1::text[])[1] AND parent_group IS NULL UNION ALL SELECT g.id, g.parent_group, g.name, group_path_cte.depth + 1 FROM groups g JOIN group_path_cte ON g.parent_group = group_path_cte.id WHERE g.name = ($1::text[])[group_path_cte.depth + 1] AND group_path_cte.depth + 1 <= cardinality($1::text[]) ) SELECT c.id, COALESCE(g.description, '') FROM group_path_cte c JOIN groups g ON g.id = c.id WHERE c.depth = cardinality($1::text[]) `, pgtype.FlatArray[string](group_path), ).Scan(&group_id, &group_description) if err == pgx.ErrNoRows { http.Error(w, "Group not found", http.StatusNotFound) return } else if err != nil { http.Error(w, "Error getting group: "+err.Error(), http.StatusInternalServerError) return } // ACL var count int err = database.QueryRow(r.Context(), ` SELECT COUNT(*) FROM user_group_roles WHERE user_id = $1 AND group_id = $2 `, params["user_id"].(int), group_id).Scan(&count) if err != nil { http.Error(w, "Error checking access: "+err.Error(), http.StatusInternalServerError) return } direct_access := (count > 0) if r.Method == "POST" { if !direct_access { http.Error(w, "You do not have direct access to this group", http.StatusForbidden) return } repo_name := r.FormValue("repo_name") repo_description := r.FormValue("repo_desc") contrib_requirements := r.FormValue("repo_contrib") if repo_name == "" { http.Error(w, "Repo name is required", http.StatusBadRequest) return } var new_repo_id int err := database.QueryRow( r.Context(), `INSERT INTO repos (name, description, group_id, contrib_requirements) VALUES ($1, $2, $3, $4) RETURNING id`, repo_name, repo_description, group_id, contrib_requirements, ).Scan(&new_repo_id) if err != nil { http.Error(w, "Error creating repo: "+err.Error(), http.StatusInternalServerError) return } file_path := filepath.Join(config.Git.RepoDir, strconv.Itoa(new_repo_id)+".git") _, err = database.Exec( r.Context(), `UPDATE repos SET filesystem_path = $1 WHERE id = $2`, file_path, new_repo_id, ) if err != nil { http.Error(w, "Error updating repo path: "+err.Error(), http.StatusInternalServerError) return }
if err = git_bare_init_with_default_hooks(file_path); err != nil {
if err = gitInit(file_path); err != nil {
http.Error(w, "Error initializing repo: "+err.Error(), http.StatusInternalServerError) return } redirect_unconditionally(w, r) return } // Repos var rows pgx.Rows rows, err = database.Query(r.Context(), ` SELECT name, COALESCE(description, '') FROM repos WHERE group_id = $1 `, group_id) if err != nil { http.Error(w, "Error getting repos: "+err.Error(), http.StatusInternalServerError) return } defer rows.Close() for rows.Next() { var name, description string if err = rows.Scan(&name, &description); err != nil { http.Error(w, "Error getting repos: "+err.Error(), http.StatusInternalServerError) return } repos = append(repos, nameDesc{name, description}) } if err = rows.Err(); err != nil { http.Error(w, "Error getting repos: "+err.Error(), http.StatusInternalServerError) return } // Subgroups rows, err = database.Query(r.Context(), ` SELECT name, COALESCE(description, '') FROM groups WHERE parent_group = $1 `, group_id) if err != nil { http.Error(w, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) return } defer rows.Close() for rows.Next() { var name, description string if err = rows.Scan(&name, &description); err != nil { http.Error(w, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) return } subgroups = append(subgroups, nameDesc{name, description}) } if err = rows.Err(); err != nil { http.Error(w, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) return } params["repos"] = repos params["subgroups"] = subgroups params["description"] = group_description params["direct_access"] = direct_access render_template(w, "group", params) }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "fmt" "net/http" "strings" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/format/diff" "github.com/go-git/go-git/v5/plumbing/object" "go.lindenii.runxiyu.org/lindenii-common/misc" ) // The file patch type from go-git isn't really usable in HTML templates // either. type usable_file_patch_t struct { From diff.File To diff.File Chunks []usable_chunk } type usable_chunk struct { Operation diff.Operation Content string } func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]any) { var repo *git.Repository var commit_id_specified_string, commit_id_specified_string_without_suffix string var commit_id plumbing.Hash var parent_commit_hash plumbing.Hash var commit_object *object.Commit var commit_id_string string var err error var patch *object.Patch repo, commit_id_specified_string = params["repo"].(*git.Repository), params["commit_id"].(string) commit_id_specified_string_without_suffix = strings.TrimSuffix(commit_id_specified_string, ".patch") commit_id = plumbing.NewHash(commit_id_specified_string_without_suffix) if commit_object, err = repo.CommitObject(commit_id); err != nil { http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) return } if commit_id_specified_string_without_suffix != commit_id_specified_string { var formatted_patch string if formatted_patch, err = fmtCommitPatch(commit_object); err != nil { http.Error(w, "Error formatting patch: "+err.Error(), http.StatusInternalServerError) return } fmt.Fprintln(w, formatted_patch) return } commit_id_string = commit_object.Hash.String() if commit_id_string != commit_id_specified_string { http.Redirect(w, r, commit_id_string, http.StatusSeeOther) return } params["commit_object"] = commit_object params["commit_id"] = commit_id_string
parent_commit_hash, patch, err = get_patch_from_commit(commit_object)
parent_commit_hash, patch, err = fmtCommitAsPatch(commit_object)
if err != nil { http.Error(w, "Error getting patch from commit: "+err.Error(), http.StatusInternalServerError) return } params["parent_commit_hash"] = parent_commit_hash.String() params["patch"] = patch params["file_patches"] = make_usable_file_patches(patch) render_template(w, "repo_commit", params) } type fake_diff_file struct { hash plumbing.Hash mode filemode.FileMode path string } func (f fake_diff_file) Hash() plumbing.Hash { return f.hash } func (f fake_diff_file) Mode() filemode.FileMode { return f.mode } func (f fake_diff_file) Path() string { return f.path } var fake_diff_file_null = fake_diff_file{ hash: plumbing.NewHash("0000000000000000000000000000000000000000"), mode: misc.First_or_panic(filemode.New("100644")), path: "", } func make_usable_file_patches(patch diff.Patch) (usable_file_patches []usable_file_patch_t) { // TODO: Remove unnecessary context // TODO: Prepend "+"/"-"/" " instead of solely distinguishing based on color for _, file_patch := range patch.FilePatches() { var from, to diff.File var usable_file_patch usable_file_patch_t chunks := []usable_chunk{} from, to = file_patch.Files() if from == nil { from = fake_diff_file_null } if to == nil { to = fake_diff_file_null } for _, chunk := range file_patch.Chunks() { var content string content = chunk.Content() if len(content) > 0 && content[0] == '\n' { content = "\n" + content } // Horrible hack to fix how browsers newlines that immediately proceed <pre> chunks = append(chunks, usable_chunk{ Operation: chunk.Type(), Content: content, }) } usable_file_patch = usable_file_patch_t{ Chunks: chunks, From: from, To: to, } usable_file_patches = append(usable_file_patches, usable_file_patch) } return }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "net/http" "strconv" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" ) func handle_repo_contrib_one(w http.ResponseWriter, r *http.Request, params map[string]any) { var mr_id_string string var mr_id int var err error var title, status, source_ref, destination_branch string var repo *git.Repository var source_ref_hash plumbing.Hash var source_commit, destination_commit, merge_base *object.Commit var merge_bases []*object.Commit mr_id_string = params["mr_id"].(string) mr_id_int64, err := strconv.ParseInt(mr_id_string, 10, strconv.IntSize) if err != nil { http.Error(w, "Merge request ID not an integer: "+err.Error(), http.StatusBadRequest) return } mr_id = int(mr_id_int64) if err = database.QueryRow(r.Context(), "SELECT COALESCE(title, ''), status, source_ref, COALESCE(destination_branch, '') FROM merge_requests WHERE id = $1", mr_id, ).Scan(&title, &status, &source_ref, &destination_branch); err != nil { http.Error(w, "Error querying merge request: "+err.Error(), http.StatusInternalServerError) return } repo = params["repo"].(*git.Repository)
if source_ref_hash, err = get_ref_hash_from_type_and_name(repo, "branch", source_ref); err != nil {
if source_ref_hash, err = getRefHash(repo, "branch", source_ref); err != nil {
http.Error(w, "Error getting source ref hash: "+err.Error(), http.StatusInternalServerError) return } if source_commit, err = repo.CommitObject(source_ref_hash); err != nil { http.Error(w, "Error getting source commit: "+err.Error(), http.StatusInternalServerError) return } params["source_commit"] = source_commit var destination_branch_hash plumbing.Hash if destination_branch == "" { destination_branch = "HEAD"
destination_branch_hash, err = get_ref_hash_from_type_and_name(repo, "", "")
destination_branch_hash, err = getRefHash(repo, "", "")
} else {
destination_branch_hash, err = get_ref_hash_from_type_and_name(repo, "branch", destination_branch)
destination_branch_hash, err = getRefHash(repo, "branch", destination_branch)
} if err != nil { http.Error(w, "Error getting destination branch hash: "+err.Error(), http.StatusInternalServerError) return } if destination_commit, err = repo.CommitObject(destination_branch_hash); err != nil { http.Error(w, "Error getting destination commit: "+err.Error(), http.StatusInternalServerError) return } params["destination_commit"] = destination_commit if merge_bases, err = source_commit.MergeBase(destination_commit); err != nil { http.Error(w, "Error getting merge base: "+err.Error(), http.StatusInternalServerError) return } merge_base = merge_bases[0] params["merge_base"] = merge_base patch, err := merge_base.Patch(source_commit) if err != nil { http.Error(w, "Error getting patch: "+err.Error(), http.StatusInternalServerError) return } params["file_patches"] = make_usable_file_patches(patch) params["mr_title"], params["mr_status"], params["mr_source_ref"], params["mr_destination_branch"] = title, status, source_ref, destination_branch render_template(w, "repo_contrib_one", params) }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "net/http" "strings" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/storer" ) func handle_repo_index(w http.ResponseWriter, r *http.Request, params map[string]any) { var repo *git.Repository var repo_name string var group_path []string var ref_hash plumbing.Hash var err error var recent_commits []*object.Commit var commit_object *object.Commit var tree *object.Tree var notes []string var branches []string var branches_ storer.ReferenceIter repo, repo_name, group_path = params["repo"].(*git.Repository), params["repo_name"].(string), params["group_path"].([]string) if strings.Contains(repo_name, "\n") || slice_contains_newline(group_path) { notes = append(notes, "Path contains newlines; HTTP Git access impossible") }
ref_hash, err = get_ref_hash_from_type_and_name(repo, params["ref_type"].(string), params["ref_name"].(string))
ref_hash, err = getRefHash(repo, params["ref_type"].(string), params["ref_name"].(string))
if err != nil { goto no_ref } branches_, err = repo.Branches() if err != nil { } err = branches_.ForEach(func(branch *plumbing.Reference) error { branches = append(branches, branch.Name().Short()) return nil }) if err != nil { } params["branches"] = branches
if recent_commits, err = get_recent_commits(repo, ref_hash, 3); err != nil {
if recent_commits, err = getRecentCommits(repo, ref_hash, 3); err != nil {
goto no_ref } params["commits"] = recent_commits if commit_object, err = repo.CommitObject(ref_hash); err != nil { goto no_ref } if tree, err = commit_object.Tree(); err != nil { goto no_ref }
params["files"] = build_display_git_tree(tree)
params["files"] = makeDisplayTree(tree)
params["readme_filename"], params["readme"] = render_readme_at_tree(tree) no_ref: params["http_clone_url"] = generate_http_remote_url(group_path, repo_name) params["ssh_clone_url"] = generate_ssh_remote_url(group_path, repo_name) params["notes"] = notes render_template(w, "repo_index", params) }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "net/http" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" ) // TODO: I probably shouldn't include *all* commits here... func handle_repo_log(w http.ResponseWriter, r *http.Request, params map[string]any) { var repo *git.Repository var ref_hash plumbing.Hash var err error var commits []*object.Commit repo = params["repo"].(*git.Repository)
if ref_hash, err = get_ref_hash_from_type_and_name(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil {
if ref_hash, err = getRefHash(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil {
http.Error(w, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) return }
if commits, err = get_recent_commits(repo, ref_hash, -1); err != nil {
if commits, err = getRecentCommits(repo, ref_hash, -1); err != nil {
http.Error(w, "Error getting recent commits: "+err.Error(), http.StatusInternalServerError) return } params["commits"] = commits render_template(w, "repo_log", params) }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "fmt" "net/http" "path" "strings" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" ) func handle_repo_raw(w http.ResponseWriter, r *http.Request, params map[string]any) { var raw_path_spec, path_spec string var repo *git.Repository var ref_hash plumbing.Hash var commit_object *object.Commit var tree *object.Tree var err error raw_path_spec = params["rest"].(string) repo, path_spec = params["repo"].(*git.Repository), strings.TrimSuffix(raw_path_spec, "/") params["path_spec"] = path_spec
if ref_hash, err = get_ref_hash_from_type_and_name(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil {
if ref_hash, err = getRefHash(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil {
http.Error(w, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) return } if commit_object, err = repo.CommitObject(ref_hash); err != nil { http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) return } if tree, err = commit_object.Tree(); err != nil { http.Error(w, "Error getting file tree: "+err.Error(), http.StatusInternalServerError) return } var target *object.Tree if path_spec == "" { target = tree } else { if target, err = tree.Tree(path_spec); err != nil { var file *object.File var file_contents string if file, err = tree.File(path_spec); err != nil { http.Error(w, "Error retrieving path: "+err.Error(), http.StatusInternalServerError) return } if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' { http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther) return } if file_contents, err = file.Contents(); err != nil { http.Error(w, "Error reading file: "+err.Error(), http.StatusInternalServerError) return } fmt.Fprint(w, file_contents) return } } if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] != '/' { http.Redirect(w, r, path.Base(path_spec)+"/", http.StatusSeeOther) return }
params["files"] = build_display_git_tree(target)
params["files"] = makeDisplayTree(target)
render_template(w, "repo_raw_dir", params) }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "bytes" "html/template" "net/http" "path" "strings" "github.com/alecthomas/chroma/v2" chroma_formatters_html "github.com/alecthomas/chroma/v2/formatters/html" chroma_lexers "github.com/alecthomas/chroma/v2/lexers" chroma_styles "github.com/alecthomas/chroma/v2/styles" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" ) func handle_repo_tree(w http.ResponseWriter, r *http.Request, params map[string]any) { var raw_path_spec, path_spec string var repo *git.Repository var ref_hash plumbing.Hash var commit_object *object.Commit var tree *object.Tree var err error raw_path_spec = params["rest"].(string) repo, path_spec = params["repo"].(*git.Repository), strings.TrimSuffix(raw_path_spec, "/") params["path_spec"] = path_spec
if ref_hash, err = get_ref_hash_from_type_and_name(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil {
if ref_hash, err = getRefHash(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil {
http.Error(w, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) return } if commit_object, err = repo.CommitObject(ref_hash); err != nil { http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) return } if tree, err = commit_object.Tree(); err != nil { http.Error(w, "Error getting file tree: "+err.Error(), http.StatusInternalServerError) return } var target *object.Tree if path_spec == "" { target = tree } else { if target, err = tree.Tree(path_spec); err != nil { var file *object.File var file_contents string var lexer chroma.Lexer var iterator chroma.Iterator var style *chroma.Style var formatter *chroma_formatters_html.Formatter var formatted_encapsulated template.HTML if file, err = tree.File(path_spec); err != nil { http.Error(w, "Error retrieving path: "+err.Error(), http.StatusInternalServerError) return } if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' { http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther) return } if file_contents, err = file.Contents(); err != nil { http.Error(w, "Error reading file: "+err.Error(), http.StatusInternalServerError) return } lexer = chroma_lexers.Match(path_spec) if lexer == nil { lexer = chroma_lexers.Fallback } if iterator, err = lexer.Tokenise(nil, file_contents); err != nil { http.Error(w, "Error tokenizing code: "+err.Error(), http.StatusInternalServerError) return } var formatted_unencapsulated bytes.Buffer style = chroma_styles.Get("autumn") formatter = chroma_formatters_html.New(chroma_formatters_html.WithClasses(true), chroma_formatters_html.TabWidth(8)) if err = formatter.Format(&formatted_unencapsulated, style, iterator); err != nil { http.Error(w, "Error formatting code: "+err.Error(), http.StatusInternalServerError) return } formatted_encapsulated = template.HTML(formatted_unencapsulated.Bytes()) //#nosec G203 params["file_contents"] = formatted_encapsulated render_template(w, "repo_tree_file", params) return } } if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] != '/' { http.Redirect(w, r, path.Base(path_spec)+"/", http.StatusSeeOther) return } params["readme_filename"], params["readme"] = render_readme_at_tree(target)
params["files"] = build_display_git_tree(target)
params["files"] = makeDisplayTree(target)
render_template(w, "repo_tree_dir", params) }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "errors" "fmt" "net/http" "strconv" "strings" "github.com/jackc/pgx/v5" "go.lindenii.runxiyu.org/lindenii-common/clog" ) type httpRouter struct{} func (router *httpRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { clog.Info("Incoming HTTP: " + r.RemoteAddr + " " + r.Method + " " + r.RequestURI) var segments []string var err error var non_empty_last_segments_len int var separator_index int params := make(map[string]any) if segments, _, err = parse_request_uri(r.RequestURI); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } non_empty_last_segments_len = len(segments) if segments[len(segments)-1] == "" { non_empty_last_segments_len-- } if segments[0] == ":" { if len(segments) < 2 { http.Error(w, "Blank system endpoint", http.StatusNotFound) return } else if len(segments) == 2 && redirect_with_slash(w, r) { return } switch segments[1] { case "static": static_handler.ServeHTTP(w, r) return case "source": source_handler.ServeHTTP(w, r) return } } params["url_segments"] = segments params["global"] = globalData var _user_id int // 0 for none _user_id, params["username"], err = get_user_info_from_request(r) params["user_id"] = _user_id if errors.Is(err, http.ErrNoCookie) { } else if errors.Is(err, pgx.ErrNoRows) { } else if err != nil { http.Error(w, "Error getting user info from request: "+err.Error(), http.StatusInternalServerError) return } if _user_id == 0 { params["user_id_string"] = "" } else { params["user_id_string"] = strconv.Itoa(_user_id) } if segments[0] == ":" { switch segments[1] { case "login": handle_login(w, r, params) return case "users": handle_users(w, r, params) return case "gc": handle_gc(w, r, params) return default: http.Error(w, fmt.Sprintf("Unknown system module type: %s", segments[1]), http.StatusNotFound) return } } separator_index = -1 for i, part := range segments { if part == ":" { separator_index = i break } } params["separator_index"] = separator_index var group_path []string var module_type string var module_name string if separator_index > 0 { group_path = segments[:separator_index] } else { group_path = segments[:len(segments)-1] } params["group_path"] = group_path switch { case non_empty_last_segments_len == 0: handle_index(w, r, params) case separator_index == -1: if redirect_with_slash(w, r) { return } handle_group_index(w, r, params) case non_empty_last_segments_len == separator_index+1: http.Error(w, "Illegal path 1", http.StatusNotImplemented) return case non_empty_last_segments_len == separator_index+2: http.Error(w, "Illegal path 2", http.StatusNotImplemented) return default: module_type = segments[separator_index+1] module_name = segments[separator_index+2] switch module_type { case "repos": params["repo_name"] = module_name if non_empty_last_segments_len > separator_index+3 { switch segments[separator_index+3] { case "info": if err = handle_repo_info(w, r, params); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } return case "git-upload-pack": if err = handle_upload_pack(w, r, params); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } return } } if params["ref_type"], params["ref_name"], err = get_param_ref_and_type(r); err != nil { if errors.Is(err, err_no_ref_spec) { params["ref_type"] = "" } else { http.Error(w, "Error querying ref type: "+err.Error(), http.StatusInternalServerError) return } } // TODO: subgroups
if params["repo"], params["repo_description"], params["repo_id"], err = open_git_repo(r.Context(), group_path, module_name); err != nil {
if params["repo"], params["repo_description"], params["repo_id"], err = openRepo(r.Context(), group_path, module_name); err != nil {
http.Error(w, "Error opening repo: "+err.Error(), http.StatusInternalServerError) return } if non_empty_last_segments_len == separator_index+3 { if redirect_with_slash(w, r) { return } handle_repo_index(w, r, params) return } repo_feature := segments[separator_index+3] switch repo_feature { case "tree": params["rest"] = strings.Join(segments[separator_index+4:], "/") if len(segments) < separator_index+5 && redirect_with_slash(w, r) { return } handle_repo_tree(w, r, params) case "raw": params["rest"] = strings.Join(segments[separator_index+4:], "/") if len(segments) < separator_index+5 && redirect_with_slash(w, r) { return } handle_repo_raw(w, r, params) case "log": if non_empty_last_segments_len > separator_index+4 { http.Error(w, "Too many parameters", http.StatusBadRequest) return } if redirect_with_slash(w, r) { return } handle_repo_log(w, r, params) case "commit": if redirect_without_slash(w, r) { return } params["commit_id"] = segments[separator_index+4] handle_repo_commit(w, r, params) case "contrib": if redirect_with_slash(w, r) { return } switch non_empty_last_segments_len { case separator_index + 4: handle_repo_contrib_index(w, r, params) case separator_index + 5: params["mr_id"] = segments[separator_index+4] handle_repo_contrib_one(w, r, params) default: http.Error(w, "Too many parameters", http.StatusBadRequest) } default: http.Error(w, fmt.Sprintf("Unknown repo feature: %s", repo_feature), http.StatusNotFound) } default: http.Error(w, fmt.Sprintf("Unknown module type: %s", module_type), http.StatusNotFound) } } }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "errors" "fmt" "os" "os/exec" glider_ssh "github.com/gliderlabs/ssh" "github.com/go-git/go-git/v5" "go.lindenii.runxiyu.org/lindenii-common/cmap" )
type pack_to_hook_t struct {
type packPass struct {
session glider_ssh.Session repo *git.Repository pubkey string
direct_access bool
directAccess bool
repo_path string
user_id int user_type string repo_id int
userID int userType string repoID int
group_path []string repo_name string
contrib_requirements string
contribReq string
}
var pack_to_hook_by_cookie = cmap.Map[string, pack_to_hook_t]{}
var packPasses = cmap.Map[string, packPass]{}
// ssh_handle_receive_pack handles attempts to push to repos. func ssh_handle_receive_pack(session glider_ssh.Session, pubkey, repo_identifier string) (err error) { group_path, repo_name, repo_id, repo_path, direct_access, contrib_requirements, user_type, user_id, err := get_repo_path_perms_from_ssh_path_pubkey(session.Context(), repo_identifier, pubkey) if err != nil { return err } repo, err := git.PlainOpen(repo_path) if err != nil { return err } repo_config, err := repo.Config() if err != nil { return err } repo_config_core := repo_config.Raw.Section("core") if repo_config_core == nil { return errors.New("Repository has no core section in config") } hooksPath := repo_config_core.OptionAll("hooksPath") if len(hooksPath) != 1 || hooksPath[0] != config.Hooks.Execs { return errors.New("Repository has hooksPath set to an unexpected value") } if !direct_access { switch contrib_requirements { case "closed": if !direct_access { return errors.New("You need direct access to push to this repo.") } case "registered_user": if user_type != "registered" { return errors.New("You need to be a registered user to push to this repo.") } case "ssh_pubkey": fallthrough case "federated": if pubkey == "" { return errors.New("You need to have an SSH public key to push to this repo.") } if user_type == "" { user_id, err = add_user_ssh(session.Context(), pubkey) if err != nil { return err } fmt.Fprintln(session.Stderr(), "You are now registered as user ID", user_id) user_type = "pubkey_only" } case "public": default: panic("unknown contrib_requirements value " + contrib_requirements) } } cookie, err := random_urlsafe_string(16) if err != nil { fmt.Fprintln(session.Stderr(), "Error while generating cookie:", err) }
pack_to_hook_by_cookie.Store(cookie, pack_to_hook_t{
packPasses.Store(cookie, packPass{
session: session, pubkey: pubkey,
direct_access: direct_access,
directAccess: direct_access,
repo_path: repo_path,
user_id: user_id, repo_id: repo_id,
userID: user_id, repoID: repo_id,
group_path: group_path, repo_name: repo_name, repo: repo,
contrib_requirements: contrib_requirements, user_type: user_type,
contribReq: contrib_requirements, userType: user_type,
})
defer pack_to_hook_by_cookie.Delete(cookie)
defer packPasses.Delete(cookie)
// The Delete won't execute until proc.Wait returns unless something // horribly wrong such as a panic occurs. proc := exec.CommandContext(session.Context(), "git-receive-pack", repo_path) proc.Env = append(os.Environ(), "LINDENII_FORGE_HOOKS_SOCKET_PATH="+config.Hooks.Socket, "LINDENII_FORGE_HOOKS_COOKIE="+cookie, ) proc.Stdin = session proc.Stdout = session proc.Stderr = session.Stderr() if err = proc.Start(); err != nil { fmt.Fprintln(session.Stderr(), "Error while starting process:", err) return err } err = proc.Wait() if exitError, ok := err.(*exec.ExitError); ok { fmt.Fprintln(session.Stderr(), "Process exited with error", exitError.ExitCode()) } else if err != nil { fmt.Fprintln(session.Stderr(), "Error while waiting for process:", err) } return err }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "context" "errors" "fmt" "io" "net/url" "strings" "go.lindenii.runxiyu.org/lindenii-common/ansiec" ) var err_ssh_illegal_endpoint = errors.New("illegal endpoint during SSH access") func get_repo_path_perms_from_ssh_path_pubkey(ctx context.Context, ssh_path, ssh_pubkey string) (group_path []string, repo_name string, repo_id int, repo_path string, direct_access bool, contrib_requirements, user_type string, user_id int, err error) { var segments []string var separator_index int var module_type, module_name string segments = strings.Split(strings.TrimPrefix(ssh_path, "/"), "/") for i, segment := range segments { var err error segments[i], err = url.PathUnescape(segment) if err != nil { return []string{}, "", 0, "", false, "", "", 0, err } } if segments[0] == ":" { return []string{}, "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint } separator_index = -1 for i, part := range segments { if part == ":" { separator_index = i break } } if segments[len(segments)-1] == "" { segments = segments[:len(segments)-1] } switch { case separator_index == -1: return []string{}, "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint case len(segments) <= separator_index+2: return []string{}, "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint } group_path = segments[:separator_index] module_type = segments[separator_index+1] module_name = segments[separator_index+2] repo_name = module_name switch module_type { case "repos": _1, _2, _3, _4, _5, _6, _7 := getRepoInfo(ctx, group_path, module_name, ssh_pubkey) return group_path, repo_name, _1, _2, _3, _4, _5, _6, _7 default: return []string{}, "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint } }
func wf_error(w io.Writer, format string, args ...any) {
func writeRedError(w io.Writer, format string, args ...any) {
fmt.Fprintln(w, ansiec.Red+fmt.Sprintf(format, args...)+ansiec.Reset) }