Lindenii Project Forge
Login
Commit info
ID8ed0dbe4201a58b00d6f3743178f4cbe5328e2b0
AuthorRunxi Yu<me@runxiyu.org>
Author dateThu, 06 Mar 2025 15:17:57 +0800
CommitterRunxi Yu<me@runxiyu.org>
Committer dateThu, 06 Mar 2025 20:07:48 +0800
Actions
Get patch
*: Support subgroups via SQL recursion
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>

package main

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

// get_path_perm_by_group_repo_key returns the filesystem path and direct
// access permission for a given repo and a provided ssh public key.
func get_path_perm_by_group_repo_key(ctx context.Context, group_name, repo_name, ssh_pubkey string) (repo_id int, filesystem_path string, access bool, contrib_requirements string, user_type string, user_id int, err error) {
	err = database.QueryRow(ctx,
		`SELECT 
		r.id,
		r.filesystem_path,
		CASE
			WHEN ugr.user_id IS NOT NULL THEN TRUE
			ELSE FALSE
		END AS has_role_in_group,
		r.contrib_requirements,
		COALESCE(u.type, ''),
		COALESCE(u.id, 0)
		FROM 
			groups g
		JOIN 
			repos r ON r.group_id = g.id
		LEFT JOIN 
			ssh_public_keys s ON s.key_string = $3
		LEFT JOIN 
			users u ON u.id = s.user_id
		LEFT JOIN 
			user_group_roles ugr ON ugr.group_id = g.id AND ugr.user_id = u.id
		WHERE 
			g.name = $1
		AND r.name = $2;`,
		group_name, repo_name, ssh_pubkey,
func get_path_perm_by_group_repo_key(ctx context.Context, group_path []string, repo_name, ssh_pubkey string) (repo_id int, filesystem_path string, access bool, contrib_requirements string, user_type string, user_id int, err error) {
	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.id,
	r.filesystem_path,
	CASE WHEN ugr.user_id IS NOT NULL THEN TRUE ELSE FALSE END AS has_role_in_group,
	r.contrib_requirements,
	COALESCE(u.type, ''),
	COALESCE(u.id, 0)
FROM group_path_cte g
JOIN repos r ON r.group_id = g.id
LEFT JOIN ssh_public_keys s ON s.key_string = $3
LEFT JOIN users u ON u.id = s.user_id
LEFT JOIN user_group_roles ugr ON ugr.group_id = g.id AND ugr.user_id = u.id
WHERE g.depth = cardinality($1::text[])
	AND r.name = $2
`, pgtype.FlatArray[string](group_path), repo_name, ssh_pubkey,
	).Scan(&repo_id, &filesystem_path, &access, &contrib_requirements, &user_type, &user_id)
	return
}
// 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 (
	err_get_fd    = errors.New("unable to get file descriptor")
	err_get_ucred = errors.New("failed getsockopt")
)

// hooks_handle_connection handles a connection from git_hooks_client via the
// unix socket.
func hooks_handle_connection(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 ok bool
	var hook_return_value 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 = get_ucred(conn); err != nil {
		if _, err = conn.Write([]byte{1}); err != nil {
			return
		}
		wf_error(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")
		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)
		return
	}

	pack_to_hook, ok = pack_to_hook_by_cookie.Load(string(cookie))
	if !ok {
		if _, err = conn.Write([]byte{1}); err != nil {
			return
		}
		wf_error(conn, "\nInvalid handler cookie")
		return
	}

	ssh_stderr = pack_to_hook.session.Stderr()

	_, _ = ssh_stderr.Write([]byte{'\n'})

	hook_return_value = 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)
			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)
					return 1
				}
				if b[0] == 0 {
					break
				}
				arg.WriteByte(b[0])
			}
			args = append(args, arg.String())
		}

		var stdin bytes.Buffer
		if _, err = io.Copy(&stdin, conn); err != nil {
			wf_error(conn, "Failed to read to the stdin buffer: %v", err)
		}

		switch filepath.Base(args[0]) {
		case "pre-receive":
			if pack_to_hook.direct_access {
				return 0
			} else {
				all_ok := true
				for {
					var line, old_oid, rest, new_oid, ref_name string
					var found bool
					var old_hash, new_hash plumbing.Hash
					var old_commit, new_commit *object.Commit

					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)
						return 1
					}
					line = line[:len(line)-1]

					old_oid, rest, found = strings.Cut(line, " ")
					if !found {
						wf_error(ssh_stderr, "Invalid pre-receive line: %v", line)
						return 1
					}

					new_oid, ref_name, found = strings.Cut(rest, " ")
					if !found {
						wf_error(ssh_stderr, "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

							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)
							if err != nil {
								wf_error(ssh_stderr, "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_name, pack_to_hook.repo_name)+"/contrib/"+strconv.FormatUint(uint64(new_mr_id), 10)+"/"+ansiec.Reset)
							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)
						} else { // Existing contrib branch
							var existing_merge_request_user_id int
							var is_ancestor 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)
							if err != nil {
								if errors.Is(err, pgx.ErrNoRows) {
									wf_error(ssh_stderr, "No existing merge request for existing contrib branch: %v", err)
								} else {
									wf_error(ssh_stderr, "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)")
								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)")
								continue
							}

							old_hash = plumbing.NewHash(old_oid)

							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)
								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)
								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)
								return 1
							}

							if !is_ancestor {
								// 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)")
								continue
							}

							fmt.Fprintln(ssh_stderr, ansiec.Blue+"POK"+ansiec.Reset, ref_name)
						}
					} 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/*)")
					}
				}

				fmt.Fprintln(ssh_stderr)
				if all_ok {
					fmt.Fprintln(ssh_stderr, "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)")
					return 1
				}
			}
		default:
			fmt.Fprintln(ssh_stderr, ansiec.Red+"Invalid hook:", args[0]+ansiec.Reset)
			return 1
		}
	}()

	fmt.Fprintln(ssh_stderr)

	_, _ = conn.Write([]byte{hook_return_value})
}

func serve_git_hooks(listener net.Listener) error {
	for {
		conn, err := listener.Accept()
		if err != nil {
			return err
		}
		go hooks_handle_connection(conn)
	}
}

func get_ucred(conn net.Conn) (ucred *syscall.Ucred, err error) {
	var unix_conn *net.UnixConn = conn.(*net.UnixConn)
	var fd *os.File

	if fd, err = unix_conn.File(); err != nil {
		return nil, err_get_fd
	}
	defer fd.Close()

	if ucred, err = syscall.GetsockoptUcred(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED); err != nil {
		return nil, err_get_ucred
	}
	return ucred, nil
}

func all_zero_num_string(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 (
	"context"
	"errors"
	"io"
	"os"
	"strings"

	"github.com/jackc/pgx/v5/pgtype"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
)

// open_git_repo opens a git repository by group and repo name.
func open_git_repo(ctx context.Context, group_name, repo_name string) (repo *git.Repository, description string, repo_id int, err error) {
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
	err = database.QueryRow(ctx,
		"SELECT r.filesystem_path, COALESCE(r.description, ''), r.id FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1 AND r.name = $2;",
		group_name, repo_name,
	).Scan(&fs_path, &description, &repo_id)

	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)
	if err != nil {
		return
	}

	repo, err = git.PlainOpen(fs_path)
	return
}

// go-git's tree entries are not friendly for use in HTML templates.
type display_git_tree_entry_t struct {
	Name       string
	Mode       string
	Size       int64
	Is_file    bool
	Is_subtree bool
}

func build_display_git_tree(tree *object.Tree) (display_git_tree []display_git_tree_entry_t) {
	for _, entry := range tree.Entries {
		display_git_tree_entry := display_git_tree_entry_t{}
		var err error
		var os_mode os.FileMode

		if os_mode, err = entry.Mode.ToOSFileMode(); err != nil {
			display_git_tree_entry.Mode = "x---------"
		} else {
			display_git_tree_entry.Mode = os_mode.String()
		}

		display_git_tree_entry.Is_file = entry.Mode.IsFile()

		if display_git_tree_entry.Size, err = tree.Size(entry.Name); err != nil {
			display_git_tree_entry.Size = 0
		}

		display_git_tree_entry.Name = strings.TrimPrefix(entry.Name, "/")

		display_git_tree = append(display_git_tree, display_git_tree_entry)
	}
	return display_git_tree
}

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

	commit_iter, err = repo.Log(&git.LogOptions{From: head_hash})
	if err != nil {
		return nil, err
	}
	recent_commits = make([]*object.Commit, 0)
	defer commit_iter.Close()
	if number_of_commits < 0 {
		for {
			this_recent_commit, err = commit_iter.Next()
			if errors.Is(err, io.EOF) {
				return recent_commits, nil
			} else if err != nil {
				return nil, err
			}
			recent_commits = append(recent_commits, this_recent_commit)
		}
	} else {
		for range number_of_commits {
			this_recent_commit, err = commit_iter.Next()
			if errors.Is(err, io.EOF) {
				return recent_commits, nil
			} else if err != nil {
				return nil, err
			}
			recent_commits = append(recent_commits, this_recent_commit)
		}
	}
	return recent_commits, 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

	parent_commit_object, err = commit_object.Parent(0)
	if errors.Is(err, object.ErrParentNotFound) {
		if commit_tree, err = commit_object.Tree(); err != nil {
			return
		}
		if patch, err = (&object.Tree{}).Patch(commit_tree); 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 {
			return
		}
	}
	return
}
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>

package main

import (
	"fmt"
	"net/http"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgtype"
)

func handle_group_repos(w http.ResponseWriter, r *http.Request, params map[string]any) {
	var group_name string
func handle_group_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	var group_path []string
	var repos []name_desc_t
	var subgroups []name_desc_t
	var err error

	group_name = params["group_name"].(string)
	repos, err = query_name_desc_list(r.Context(), "SELECT r.name, COALESCE(r.description, '') FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1;", group_name)
	group_path = params["group_path"].([]string)

	// Repos
	var rows pgx.Rows
	rows, err = database.Query(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 r.name, COALESCE(r.description, '')
	FROM group_path_cte c
	JOIN repos r ON r.group_id = c.id
	WHERE c.depth = cardinality($1::text[])
	`,
		pgtype.FlatArray[string](group_path),
	)
	if err != nil {
		http.Error(w, "Error getting groups: "+err.Error(), http.StatusInternalServerError)
		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, name_desc_t{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(), `
	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 g.name, COALESCE(g.description, '')
	FROM group_path_cte c
	JOIN groups g ON g.parent_group = c.id
	WHERE c.depth = cardinality($1::text[])
	`,
		pgtype.FlatArray[string](group_path),
	)
	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, name_desc_t{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

	fmt.Println(group_path)

	render_template(w, "group_repos", params)
	render_template(w, "group", params)
}

// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>

package main

import (
	"net/http"
)

func handle_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	var err error
	var groups []name_desc_t

	groups, err = query_name_desc_list(r.Context(), "SELECT name, COALESCE(description, '') FROM groups")
	groups, err = query_name_desc_list(r.Context(), "SELECT name, COALESCE(description, '') FROM groups WHERE parent_group IS NULL")
	if err != nil {
		http.Error(w, "Error querying groups: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["groups"] = groups
	render_template(w, "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"
)

func handle_repo_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	var repo *git.Repository
	var repo_name, group_name string
	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

	repo, repo_name, group_name = params["repo"].(*git.Repository), params["repo_name"].(string), params["group_name"].(string)
	repo, repo_name, group_path = params["repo"].(*git.Repository), params["repo_name"].(string), params["group_path"].([]string)

	if ref_hash, err = get_ref_hash_from_type_and_name(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil {
		http.Error(w, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError)
		return
	}

	if recent_commits, err = get_recent_commits(repo, ref_hash, 3); err != nil {
		http.Error(w, "Error getting recent commits: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["commits"] = recent_commits
	commit_object, err = repo.CommitObject(ref_hash)
	if err != nil {
		http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError)
		return
	}
	tree, err = commit_object.Tree()
	if err != nil {
		http.Error(w, "Error getting file tree: "+err.Error(), http.StatusInternalServerError)
		return
	}

	params["readme_filename"], params["readme"] = render_readme_at_tree(tree)
	params["files"] = build_display_git_tree(tree)

	params["http_clone_url"] = generate_http_remote_url(group_name, repo_name)
	params["ssh_clone_url"] = generate_ssh_remote_url(group_name, repo_name)
	params["http_clone_url"] = generate_http_remote_url(group_path, repo_name)
	params["ssh_clone_url"] = generate_ssh_remote_url(group_path, repo_name)

	render_template(w, "repo_index", params)
}
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>

package main

import (
	"fmt"
	"io"
	"net/http"
	"os/exec"

	"github.com/jackc/pgx/v5/pgtype"
)

func handle_repo_info(w http.ResponseWriter, r *http.Request, params map[string]any) (err error) {
	var group_name, repo_name, repo_path string
	var group_path []string
	var repo_name, repo_path string

	group_name, repo_name = params["group_name"].(string), params["repo_name"].(string)
	if err = database.QueryRow(r.Context(),
		"SELECT r.filesystem_path FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1 AND r.name = $2;",
		group_name, repo_name,
	if err := database.QueryRow(r.Context(), `
	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: jion 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
	FROM group_path_cte c
	JOIN repos r ON r.group_id = c.id
	WHERE c.depth = cardinality($1::text[])
		AND r.name = $2
	`,
		pgtype.FlatArray[string](group_path),
		repo_name,
	).Scan(&repo_path); err != nil {
		return err
	}

	w.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement")
	w.WriteHeader(http.StatusOK)

	cmd := exec.Command("git", "upload-pack", "--stateless-rpc", "--advertise-refs", repo_path)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	defer func() {
		_ = stdout.Close()
	}()
	cmd.Stderr = cmd.Stdout

	if err = cmd.Start(); err != nil {
		return err
	}

	if err = pack_line(w, "# service=git-upload-pack\n"); err != nil {
		return err
	}

	if err = pack_flush(w); err != nil {
		return
	}

	if _, err = io.Copy(w, stdout); err != nil {
		return err
	}

	if err = cmd.Wait(); err != nil {
		return err
	}

	return nil
}

// Taken from https://github.com/icyphox/legit, MIT license
func pack_line(w io.Writer, s string) error {
	_, err := fmt.Fprintf(w, "%04x%s", len(s)+4, s)
	return err
}

// Taken from https://github.com/icyphox/legit, MIT license
func pack_flush(w io.Writer) error {
	_, err := fmt.Fprint(w, "0000")
	return err
}
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>

package main

import (
	"io"
	"net/http"
	"os"
	"os/exec"

	"github.com/jackc/pgx/v5/pgtype"
)

func handle_upload_pack(w http.ResponseWriter, r *http.Request, params map[string]any) (err error) {
	var group_name, repo_name string
	var group_path []string
	var repo_name string
	var repo_path string
	var stdout io.ReadCloser
	var stdin io.WriteCloser
	var cmd *exec.Cmd

	group_name, repo_name = params["group_name"].(string), params["repo_name"].(string)
	group_path, repo_name = params["group_path"].([]string), params["repo_name"].(string)

	if err = database.QueryRow(r.Context(),
		"SELECT r.filesystem_path FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1 AND r.name = $2;",
		group_name, repo_name,
	if err := database.QueryRow(r.Context(), `
	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: jion 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
	FROM group_path_cte c
	JOIN repos r ON r.group_id = c.id
	WHERE c.depth = cardinality($1::text[])
		AND r.name = $2
	`,
		pgtype.FlatArray[string](group_path),
		repo_name,
	).Scan(&repo_path); err != nil {
		return err
	}


	w.Header().Set("Content-Type", "application/x-git-upload-pack-result")
	w.Header().Set("Connection", "Keep-Alive")
	w.Header().Set("Transfer-Encoding", "chunked")
	w.WriteHeader(http.StatusOK)

	cmd = exec.Command("git", "upload-pack", "--stateless-rpc", repo_path)
	cmd.Env = append(os.Environ(), "LINDENII_FORGE_HOOKS_SOCKET_PATH="+config.Hooks.Socket)
	if stdout, err = cmd.StdoutPipe(); err != nil {
		return err
	}
	cmd.Stderr = cmd.Stdout
	defer func() {
		_ = stdout.Close()
	}()

	if stdin, err = cmd.StdinPipe(); err != nil {
		return err
	}
	defer func() {
		_ = stdin.Close()
	}()

	if err = cmd.Start(); err != nil {
		return err
	}

	if _, err = io.Copy(stdin, r.Body); err != nil {
		return err
	}

	if err = stdin.Close(); err != nil {
		return err
	}

	if _, err = io.Copy(w, stdout); err != nil {
		return err
	}

	if err = cmd.Wait(); err != nil {
		return err
	}

	return nil
}
// 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 http_router_t struct{}

func (router *http_router_t) 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"] = global_data
	var _user_id int // 0 for none
	_user_id, params["username"], err = get_user_info_from_request(r)
	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"] = ""
	} else {
		params["user_id"] = 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
		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

	// TODO
	if separator_index > 1 {
		http.Error(w, "Subgroups haven't been implemented yet", http.StatusNotImplemented)
		return
	}

	var group_path []string
	var module_type string
	var module_name string
	var group_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:
		http.Error(w, "Group indexing hasn't been implemented yet", http.StatusNotImplemented)
	case non_empty_last_segments_len == separator_index+1:
		http.Error(w, "Group root hasn't been implemented yet", http.StatusNotImplemented)
	case non_empty_last_segments_len == separator_index+2:
		if redirect_with_slash(w, r) {
			return
		}
		module_type = segments[separator_index+1]
		params["group_name"] = segments[0]
		switch module_type {
		case "repos":
			handle_group_repos(w, r, params)
		default:
			http.Error(w, fmt.Sprintf("Unknown module type: %s", module_type), http.StatusNotFound)
		}
		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]
		group_name = segments[0]
		params["group_name"] = group_name
		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_name, module_name); err != nil {
			if params["repo"], params["repo_description"], params["repo_id"], err = open_git_repo(r.Context(), group_path, module_name); err != nil {
				http.Error(w, "Error opening repo: "+err.Error(), http.StatusInternalServerError)
				return
			}

			fmt.Println(non_empty_last_segments_len, separator_index, segments)

			if non_empty_last_segments_len == separator_index+3 {
				if redirect_with_slash(w, r) {
					return
				        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 (
	"net/url"
	"strings"
)

// We don't use path.Join because it collapses multiple slashes into one.

func generate_ssh_remote_url(group_name, repo_name string) string {
	return strings.TrimSuffix(config.SSH.Root, "/") + "/" + url.PathEscape(group_name) + "/:/repos/" + url.PathEscape(repo_name)
func generate_ssh_remote_url(group_path []string, repo_name string) string {
	return strings.TrimSuffix(config.SSH.Root, "/") + "/" + path_escape_cat_segments(group_path) + "/:/repos/" + url.PathEscape(repo_name)
}

func generate_http_remote_url(group_name, repo_name string) string {
	return strings.TrimSuffix(config.HTTP.Root, "/") + "/" + url.PathEscape(group_name) + "/:/repos/" + url.PathEscape(repo_name)
func generate_http_remote_url(group_path []string, repo_name string) string {
	return strings.TrimSuffix(config.HTTP.Root, "/") + "/" + path_escape_cat_segments(group_path) + "/:/repos/" + url.PathEscape(repo_name)
}
// 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 {
	session       glider_ssh.Session
	repo          *git.Repository
	pubkey        string
	direct_access bool
	repo_path     string
	user_id       int
	repo_id       int
	group_name    string
	group_path    []string
	repo_name     string
}

var pack_to_hook_by_cookie = cmap.Map[string, pack_to_hook_t]{}

// ssh_handle_receive_pack handles attempts to push to repos.
func ssh_handle_receive_pack(session glider_ssh.Session, pubkey string, repo_identifier string) (err error) {
	group_name, 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)
	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":
			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)
			}
		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)
	}

	fmt.Println(group_name, repo_name)

	pack_to_hook_by_cookie.Store(cookie, pack_to_hook_t{
		session:       session,
		pubkey:        pubkey,
		direct_access: direct_access,
		repo_path:     repo_path,
		user_id:       user_id,
		repo_id:       repo_id,
		group_name:    group_name,
		group_path:    group_path,
		repo_name:     repo_name,
		repo:          repo,
	})
	defer pack_to_hook_by_cookie.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 string, ssh_pubkey string) (group_name string, repo_name string, repo_id int, repo_path string, direct_access bool, contrib_requirements string, user_type string, user_id int, err error) {
func get_repo_path_perms_from_ssh_path_pubkey(ctx context.Context, ssh_path string, ssh_pubkey string) (group_path []string, repo_name string, repo_id int, repo_path string, direct_access bool, contrib_requirements string, 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 "", "", 0, "", false, "", "", 0, err
			return []string{}, "", 0, "", false, "", "", 0, err
		}
	}

	if segments[0] == ":" {
		return "", "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint
		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 "", "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint
		return []string{}, "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint
	case len(segments) <= separator_index+2:
		return "", "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint
		return []string{}, "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint
	}

	group_name = segments[0]
	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 := get_path_perm_by_group_repo_key(ctx, group_name, module_name, ssh_pubkey)
		return group_name, repo_name, _1, _2, _3, _4, _5, _6, _7
		_1, _2, _3, _4, _5, _6, _7 := get_path_perm_by_group_repo_key(ctx, group_path, module_name, ssh_pubkey)
		return group_path, repo_name, _1, _2, _3, _4, _5, _6, _7
	default:
		return "", "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint
		return []string{}, "", 0, "", false, "", "", 0, err_ssh_illegal_endpoint
	}
}

func wf_error(w io.Writer, format string, args ...any) {
	fmt.Fprintln(w, ansiec.Red+fmt.Sprintf(format, args...)+ansiec.Reset)
}
/*
 * SPDX-License-Identifier: AGPL-3.0-only
 * SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
 * SPDX-FileContributor: luk3yx <https://luk3yx.github.io>
 */

/* Base styles and variables */
html {
	font-family: sans-serif;
	background-color: var(--background-color);
	color: var(--text-color);
	--background-color: hsl(0, 0%, 100%);
	--text-color: hsl(0, 0%, 0%);
	--link-color: hsl(320, 50%, 36%);
	--light-text-color: hsl(0, 0%, 45%);
	--darker-border-color: hsl(0, 0%, 72%);
	--lighter-border-color: hsl(0, 0%, 85%);
	--text-decoration-color: hsl(0, 0%, 72%);
	--darker-box-background-color: hsl(0, 0%, 92%);
	--lighter-box-background-color: hsl(0, 0%, 95%);
	--primary-color: hsl(320, 50%, 36%);
	--primary-color-contrast: hsl(320, 0%, 100%);
	--danger-color: hsl(0, 50%, 36%);
	--danger-color-contrast: hsl(0, 0%, 100%);
}

/* Dark mode overrides */
@media (prefers-color-scheme: dark) {
	html {
		--background-color: hsl(0, 0%, 0%);
		--text-color: hsl(0, 0%, 100%);
		--link-color: hsl(320, 50%, 76%);
		--light-text-color: hsl(0, 0%, 78%);
		--darker-border-color: hsl(0, 0%, 35%);
		--lighter-border-color: hsl(0, 0%, 25%);
		--text-decoration-color: hsl(0, 0%, 30%);
		--darker-box-background-color: hsl(0, 0%, 20%);
		--lighter-box-background-color: hsl(0, 0%, 15%);
	}
}

/* Global layout */
body {
	margin: 0;
}
html, code, pre {
	font-size: 0.96rem; /* TODO: Not always correct */
}

/* Toggle table controls */
.toggle-table-off, .toggle-table-on {
	opacity: 0;
	position: absolute;
}
.toggle-table-off:focus-visible + table > thead > tr > th > label,
.toggle-table-on:focus-visible + table > thead > tr > th > label {
	outline: 1.5px var(--primary-color) solid;
}
.toggle-table-off + table > thead > tr > th, .toggle-table-on + table > thead > tr > th {
	padding: 0;
}
.toggle-table-off + table > thead > tr > th > label, .toggle-table-on + table > thead > tr > th > label {
	width: 100%;
	display: inline-block;
	padding: 3px 0;
	cursor: pointer;
}
.toggle-table-off:checked + table > tbody {
	display: none;
}
.toggle-table-on + table > tbody {
	display: none;
}
.toggle-table-on:checked + table > tbody {
	display: table-row-group;
}

/* Footer styles */
footer {
	margin-top: 1rem;
	margin-left: auto;
	margin-right: auto;
	display: block;
	padding: 0 5px;
	width: fit-content;
	text-align: center;
	color: var(--light-text-color);
}
footer a:link, footer a:visited {
	color: inherit;
}

/* Padding containers */
.padding-wrapper {
	margin: 1rem auto;
	max-width: 60rem;
	padding: 0 5px;
}
.padding {
	padding: 0 5px;
}

/* Link styles */
a:link, a:visited {
	text-decoration-color: var(--text-decoration-color);
	color: var(--link-color);
}

/* Readme inline code styling */
#readme code:not(pre > code) {
	background-color: var(--lighter-box-background-color);
	border-radius: 2px;
	padding: 2px;
}

/* Readme word breaks to avoid overfull hboxes */
#readme {
	word-break: break-word;
}

/* Table styles */
table {
	border: var(--lighter-border-color) solid 1px;
	border-spacing: 0px;
	border-collapse: collapse;
}
table.wide {
	width: 100%;
}
td, th {
	padding: 3px 5px;
	border: var(--lighter-border-color) solid 1px;
}
.pad {
	padding: 3px 5px;
}
th, thead, tfoot {
	background-color: var(--lighter-box-background-color);
}
th[scope=row] {
	text-align: left;
}
tr.title-row > th, th.title-row, .title-row {
	background-color: var(--lighter-box-background-color);
}
td > pre {
	margin: 0;
}
#readme > *:last-child {
	margin-bottom: 0;
}
#readme > *:first-child {
	margin-top: 0;
}

/* Table misc and scrolling */
.commit-id {
	font-family: monospace;
	word-break: break-word;
}
.scroll {
	overflow-x: auto;
}

/* Diff/chunk styles */
.chunk-unchanged {
	color: grey;
}
.chunk-addition {
	background-color: green;
}
@media (prefers-color-scheme: dark) {
	.chunk-addition {
		background-color: lime;
	}
}
.chunk-deletion {
	background-color: red;
}
.chunk-unknown {
	background-color: yellow;
}
pre.chunk {
	margin-top: 0;
	margin-bottom: 0;
}
.centering {
	text-align: center;
}

/* Toggle content sections */
.toggle-off-wrapper, .toggle-on-wrapper {
	border: var(--lighter-border-color) solid 1px;
}
.toggle-off-toggle, .toggle-on-toggle {
	opacity: 0;
	position: absolute;
}
.toggle-off-header, .toggle-on-header {
	font-weight: bold;
	cursor: pointer;
	display: block;
	width: 100%;
	background-color: var(--lighter-box-background-color);
}
.toggle-off-header > div, .toggle-on-header > div {
	padding: 3px 5px;
	display: block;
}
.toggle-on-content {
	display: none;
}
.toggle-on-toggle:focus-visible + .toggle-on-header, .toggle-off-toggle:focus-visible + .toggle-off-header {
	outline: 1.5px var(--primary-color) solid;
}
.toggle-on-toggle:checked + .toggle-on-header + .toggle-on-content {
	display: block;
}
.toggle-off-content {
	display: block;
}
.toggle-off-toggle:checked + .toggle-off-header + .toggle-off-content {
	display: none;
}

*:focus-visible {
	outline: 1.5px var(--primary-color) solid;
}

/* File display styles */
.file-patch + .file-patch {
	margin-top: 0.5rem;
}
.file-content {
	padding: 3px 5px;
}
.file-header {
	font-family: monospace;
	display: flex;
	flex-direction: row;
	align-items: center;
}
.file-header::after {
	content: "\25b6";
	font-family: sans-serif;
	margin-left: auto;
	line-height: 100%;
	margin-right: 0.25em;
}
.file-toggle:checked + .file-header::after {
	content: "\25bc";
}

/* Form elements */
textarea {
	box-sizing: border-box;
	background-color: var(--lighter-box-background-color);
	resize: vertical;
}
textarea,
input[type=text],
input[type=password] {
	font-family: sans-serif;
	font-size: smaller;
	background-color: var(--lighter-box-background-color);
	color: var(--text-color);
	border: none;
	padding: 0.3rem;
	width: 100%;
	box-sizing: border-box;
}
td.tdinput, th.tdinput {
	padding: 0;
}
td.tdinput textarea,
td.tdinput input[type=text],
td.tdinput input[type=password],
th.tdinput textarea,
th.tdinput input[type=text],
th.tdinput input[type=password] {
	background-color: transparent;
}

/* Button styles */
.btn-primary, a.btn-primary {
	background: var(--primary-color);
	color: var(--primary-color-contrast);
	border: var(--lighter-border-color) 1px solid;
	font-weight: bold;
}
.btn-danger, a.btn-danger {
	background: var(--danger-color);
	color: var(--danger-color-contrast);
	border: var(--lighter-border-color) 1px solid;
	font-weight: bold;
}
.btn-white, a.btn-white {
	background: var(--primary-color-contrast);
	color: var(--primary-color);
	border: var(--lighter-border-color) 1px solid;
}
.btn-normal, a.btn-normal,
input[type=file]::file-selector-button {
	background: var(--lighter-box-background-color);
	border: var(--lighter-border-color) 1px solid !important;
	color: var(--text-color);
}
.btn, .btn-white, .btn-danger, .btn-normal, .btn-primary,
input[type=submit],
input[type=file]::file-selector-button {
	display: inline-block;
	width: auto;
	min-width: fit-content;
	border-radius: 0;
	padding: .1rem .75rem;
	font-size: 0.9rem;
	transition: background .1s linear;
	cursor: pointer;
}
a.btn, a.btn-white, a.btn-danger, a.btn-normal, a.btn-primary {
	text-decoration: none;
}

/* Header layout */
header#main-header {
	background-color: var(--lighter-box-background-color);
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10px;
}
header#main-header > div#main-header-forge-title {
	flex-grow: 1;
}
header#main-header > div#main-header-user {
	display: flex;
	align-items: center;
}
table + table {
	margin-top: 1rem;
}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "group_path_plain" -}}
{{ $p := . }}
{{ range $i, $s := . }}{{ $s }}{{ if ne $i (len $p) }}/{{ end }}{{ end }}
{{ end }}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "group_view" -}}
{{ if .subgroups }}
	<table class="wide">
		<thead>
			<tr>
				<th colspan="2" class="title-row">Subgroups</th>
			</tr>
		</thead>
		<tbody>
			{{- range .subgroups }}
				<tr>
					<td>
						<a href="{{ .Name }}/">{{ .Name }}</a>
					</td>
					<td>
						{{ .Description }}
					</td>
				</tr>
			{{- end }}
		</tbody>
	</table>
{{ end }}
{{ if .repos }}
<table class="wide">
	<thead>
		<tr>
			<th colspan="2" class="title-row">Repos</th>
		</tr>
	</thead>
	<tbody>
		{{- range .repos }}
			<tr>
				<td>
					<a href=":/repos/{{ .Name }}/">{{ .Name }}</a>
				</td>
				<td>
					{{ .Description }}
				</td>
			</tr>
		{{- end }}
	</tbody>
</table>
{{ end }}
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "group" -}}
{{ $group_path := .group_path }}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>{{ range $i, $s := .group_path }}{{ $s }}{{ if ne $i (len $group_path) }} / {{ end }}{{ end }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="group">
		{{ template "header" . }}
		<div class="padding-wrapper">
			<p>{{ range $i, $s := .group_path }}{{ $s }}{{ if ne $i (len $group_path) }} / {{ end }}{{ end }}
			{{ template "group_view" . }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "group_repos" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Repos &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="group-repos">
		{{ template "header" . }}
		<div class="padding-wrapper">
			<table class="wide">
			<thead>
				<tr>
					<th colspan="2" class="title-row">Repos in {{ .group_name }}</th>
				</tr>
			</thead>
			<tbody>
				{{- range .repos }}
					<tr>
						<td>
							<a href="{{ .Name }}/">{{ .Name }}</a>
						</td>
						<td>
							{{ .Description }}
						</td>
					</tr>
				{{- end }}
			</tbody>
			</table>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "index" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Index &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="index">
		{{ template "header" . }}
		<div class="padding-wrapper">
			<table class="wide">
				<thead>
		<table class="wide">
			<thead>
				<tr>
					<th colspan="2" class="title-row">Groups</th>
				</tr>
			</thead>
			<tbody>
				{{- range .groups }}
					<tr>
						<th colspan="2" class="title-row">
							Groups
						</th>
						<td>
							<a href="{{ .Name }}/">{{ .Name }}</a>
						</td>
						<td>
							{{ .Description }}
						</td>
					</tr>
				</thead>
				<tbody>
					{{- range .groups }}
						<tr>
							<td>
								<a href="{{ .Name }}/:/repos/">{{ .Name }}</a>
							</td>
							<td>
								{{ .Description }}
							</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
				{{- end }}
			</tbody>
		</table>
		<div class="padding-wrapper">
			<table class="wide">
				<thead>
					<tr>
						<th colspan="2" class="title-row">
							Info
						</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<th scope="row">SSH public key</th>
						<td><code>{{ .global.server_public_key_string }}</code></td>
					</tr>
					<tr>
						<th scope="row">SSH fingerprint</th>
						<td><code>{{ .global.server_public_key_fingerprint }}</code></td>
					</tr>
				</tbody>
			</table>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_commit" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Commit {{ .commit_id }} &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>Commit {{ .commit_id }} &ndash; {{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-commit">
		{{ template "header" . }}
		<div class="padding-wrapper scroll">
			<table id="commit-info-table">
				<thead>
					<tr class="title-row">
						<th colspan="2">Commit info</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<th scope="row">ID</th>
						<td>{{ .commit_id }}</td>
					</tr>
					<tr>
						<th scope="row">Author</th>
						<td>{{ .commit_object.Author.Name }} &lt;<a href="mailto:{{ .commit_object.Author.Email }}">{{ .commit_object.Author.Email }}</a>&gt;</td>
					</tr>
					<tr>
						<th scope="row">Author date</th>
						<td>{{ .commit_object.Author.When.Format "Mon, 02 Jan 2006 15:04:05 -0700" }}</td>
					</tr>
					<tr>
						<th scope="row">Committer</th>
						<td>{{ .commit_object.Committer.Name }} &lt;<a href="mailto:{{ .commit_object.Committer.Email }}">{{ .commit_object.Committer.Email }}</a>&gt;</td>
					</tr>
					<tr>
						<th scope="row">Committer date</th>
						<td>{{ .commit_object.Committer.When.Format "Mon, 02 Jan 2006 15:04:05 -0700" }}</td>
					</tr>
					<tr>
						<th scope="row">Actions</th>
						<td><pre><a href="{{ .commit_object.Hash }}.patch">Get patch</a></pre></td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper scroll" id="this-commit-message">
			<pre>{{ .commit_object.Message }}</pre>
		</div>
		<div class="padding-wrapper">
			{{ $parent_commit_hash := .parent_commit_hash }}
			{{ $commit_object := .commit_object }}
			{{ range .file_patches }}
				<div class="file-patch toggle-on-wrapper">
					<input type="checkbox" id="toggle-{{ .From.Hash }}{{ .To.Hash }}" class="file-toggle toggle-on-toggle">
					<label for="toggle-{{ .From.Hash }}{{ .To.Hash }}" class="file-header toggle-on-header">
						<div>
							{{ if eq .From.Path "" }}
								--- /dev/null
							{{ else }}
								--- a/<a href="../tree/{{ .From.Path }}?commit={{ $parent_commit_hash }}">{{ .From.Path }}</a> {{ .From.Mode }}
							{{ end }}
							<br />
							{{ if eq .To.Path "" }}
								+++ /dev/null
							{{ else }}
								+++ b/<a href="../tree/{{ .To.Path }}?commit={{ $commit_object.Hash }}">{{ .To.Path }}</a> {{ .To.Mode }}
							{{ end }}
						</div>
					</label>
					<div class="file-content toggle-on-content scroll">
						{{ range .Chunks }}
							{{ if eq .Operation 0 }}
								<pre class="chunk chunk-unchanged">{{ .Content }}</pre>
							{{ else if eq .Operation 1 }}
								<pre class="chunk chunk-addition">{{ .Content }}</pre>
							{{ else if eq .Operation 2 }}
								<pre class="chunk chunk-deletion">{{ .Content }}</pre>
							{{ else }}
								<pre class="chunk chunk-unknown">{{ .Content }}</pre>
							{{ end }}
						{{ end }}
					</div>
				</div>
			{{ end }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_contrib_index" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Merge requests &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>Merge requests &ndash; {{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-contrib-index">
		{{ template "header" . }}
		<div class="padding-wrapper">
			<table id="recent-merge_requests" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3">Merge requests</th>
					</tr>
				</thead>
				<tbody>
					{{- range .merge_requests }}
						<tr>
							<td class="merge_request-id">{{ .ID }}</td>
							<td class="merge_request-title"><a href="{{ .ID }}/">{{ .Title }}</a></td>
							<td class="merge_request-status">{{ .Status }}</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_contrib_one" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Merge requests &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>Merge requests &ndash; {{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-contrib-one">
		{{ template "header" . }}
		<div class="padding-wrapper">
			<table id="mr-info-table">
				<thead>
					<tr class="title-row">
						<th colspan="2">Merge request info</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<th scope="row">ID</th>
						<td>{{ .mr_id }}</td>
					</tr>
					<tr>
						<th scope="row">Status</th>
						<td>{{ .mr_status }}</td>
					</tr>
					<tr>
						<th scope="row">Title</th>
						<td>{{ .mr_title }}</td>
					</tr>
					<tr>
						<th scope="row">Source ref</th>
						<td>{{ .mr_source_ref }}</td>
					</tr>
					<tr>
						<th scope="row">Destination branch</th>
						<td>{{ .mr_destination_branch }}</td>
					</tr>
					<tr>
						<th scope="row">Merge base</th>
						<td>{{ .merge_base.ID.String }}</td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			{{ $merge_base := .merge_base }}
			{{ $source_commit := .source_commit }}
			{{ range .file_patches }}
				<div class="file-patch toggle-on-wrapper">
					<input type="checkbox" id="toggle-{{ .From.Hash }}{{ .To.Hash }}" class="file-toggle toggle-on-toggle">
					<label for="toggle-{{ .From.Hash }}{{ .To.Hash }}" class="file-header toggle-on-header">
						<div>
							{{ if eq .From.Path "" }}
								--- /dev/null
							{{ else }}
								--- a/<a href="../../tree/{{ .From.Path }}?commit={{ $merge_base.Hash }}">{{ .From.Path }}</a> {{ .From.Mode }}
							{{ end }}
							<br />
							{{ if eq .To.Path "" }}
								+++ /dev/null
							{{ else }}
								+++ b/<a href="../../tree/{{ .To.Path }}?commit={{ $source_commit.Hash }}">{{ .To.Path }}</a> {{ .To.Mode }}
							{{ end }}
						</div>
					</label>
					<div class="file-content toggle-on-content scroll">
						{{ range .Chunks }}
							{{ if eq .Operation 0 }}
								<pre class="chunk chunk-unchanged">{{ .Content }}</pre>
							{{ else if eq .Operation 1 }}
								<pre class="chunk chunk-addition">{{ .Content }}</pre>
							{{ else if eq .Operation 2 }}
								<pre class="chunk chunk-deletion">{{ .Content }}</pre>
							{{ else }}
								<pre class="chunk chunk-unknown">{{ .Content }}</pre>
							{{ end }}
						{{ end }}
					</div>
				</div>
			{{ end }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_index" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>{{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>{{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-index">
		{{ template "header" . }}
		<div class="padding-wrapper">
			<table id="repo-info-table">
				<thead>
					<tr class="title-row">
						<th colspan="2">Repo info</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<th scope="row">Name</th>
						<td>{{ .repo_name }}</td>
					</tr>
					{{ if .repo_description }}
						<tr>
							<th scope="row">Description</th>
							<td>{{ .repo_description }}</td>
						</tr>
					{{ end }}
					<tr>
						<th scope="row">SSH remote</th>
						<td><code>{{ .ssh_clone_url }}</code></td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			<p>
				<a href="contrib/" class="btn-normal">Merge requests</a>
			</p>
		</div>
		<div class="padding-wrapper scroll">
			<table id="recent-commits" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3">Recent commits (<a href="log/{{ if .ref_type }}?{{ .ref_type }}={{ .ref_name }}{{ end }}">see all</a>)</th>
					</tr>
				</thead>
				<tbody>
					{{- range .commits }}
						<tr>
							<td class="commit-title"><a href="commit/{{ .ID }}">{{ .Message | first_line }}</a></td>
							<td class="commit-author">
								<a class="email-name" href="mailto:{{ .Author.Email }}">{{ .Author.Name }}</a>
							</td>
							<td class="commit-time">
								{{ .Author.When.Format "2006-01-02 15:04:05 -0700" }}
							</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper scroll">
			<table id="file-tree" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3">/{{ if .ref_name }} on {{ .ref_name }}{{ end }}</th>
					</tr>
				</thead>
				<tbody>
					{{- $ref_type := .ref_type }}
					{{- $ref := .ref_name }}
					{{- range .files }}
						<tr>
							<td class="file-mode">{{ .Mode }}</td>
							<td class="file-name"><a href="tree/{{ .Name }}{{ if not .Is_file }}/{{ end }}{{ if $ref_type }}?{{ $ref_type }}={{ $ref }}{{ end }}">{{ .Name }}</a>{{ if not .Is_file }}/{{ end }}</td>
							<td class="file-size">{{ .Size }}</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper" id="readme">
			{{ .readme }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_log" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Log &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>Log &ndash; {{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-log">
		{{ template "header" . }}
		<div class="scroll">
			<table id="commits" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="4">Commits {{ if .ref_name }} on {{ .ref_name }}{{ end }}</th>
					</tr>
					<tr>
						<th scope="col">ID</th>
						<th scope="col">Title</th>
						<th scope="col">Author</th>
						<th scope="col">Time</th>
					</tr>
				</thead>
				<tbody>
					{{- range .commits }}
						<tr>
							<td class="commit-id"><a href="../commit/{{ .ID }}">{{ .ID }}</a></td>
							<td class="commit-title">{{ .Message | first_line }}</td>
							<td class="commit-author">
								<a class="email-name" href="mailto:{{ .Author.Email }}">{{ .Author.Name }}</a>
							</td>
							<td class="commit-time">
								{{ .Author.When.Format "2006-01-02 15:04:05 -0700" }}
							</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_raw_dir" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} &ndash; {{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-raw-dir">
		{{ template "header" . }}
		<div class="padding-wrapper scroll">
			<table id="file-tree" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3">
							(Raw) /{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }}{{ if .ref_name }} on {{ .ref_name }}{{ end }}
						</th>
					</tr>
				</thead>
				<tbody>
					{{- $path_spec := .path_spec }}
					{{- $ref := .ref_name }}
					{{- $ref_type := .ref_type }}
					{{- range .files }}
						<tr>
							<td class="file-mode">{{ .Mode }}</td>
							<td class="file-name"><a href="{{ .Name }}{{ if not .Is_file }}/{{ end }}{{ if $ref_type }}?{{ $ref_type }}={{ $ref }}{{ end }}">{{ .Name }}</a>{{ if not .Is_file }}/{{ end }}</td>
							<td class="file-size">{{ .Size }}</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			<div id="refs">
			</div>
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_tree_dir" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }} &ndash; {{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-tree-dir">
		{{ template "header" . }}
		<div class="padding-wrapper scroll">
			<table id="file-tree" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3">
							/{{ .path_spec }}{{ if ne .path_spec "" }}/{{ end }}{{ if .ref_name }} on {{ .ref_name }}{{ end }}
						</th>
					</tr>
				</thead>
				<tbody>
					{{- $path_spec := .path_spec }}
					{{- $ref := .ref_name }}
					{{- $ref_type := .ref_type }}
					{{- range .files }}
						<tr>
							<td class="file-mode">{{ .Mode }}</td>
							<td class="file-name"><a href="{{ .Name }}{{ if not .Is_file }}/{{ end }}{{ if $ref_type }}?{{ $ref_type }}={{ $ref }}{{ end }}">{{ .Name }}</a>{{ if not .Is_file }}/{{ end }}</td>
							<td class="file-size">{{ .Size }}</td>
						</tr>
					{{- end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			<div id="refs">
			</div>
		</div>
		<div class="padding-wrapper">
			{{ if .readme }}
				<table class="wide">
					<thead>
						<tr class="title-row">
							<th>{{ .readme_filename }}</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td id="readme">
								{{ .readme -}}
							</td>
						</tr>
					</tbody>
				</table>
			{{ end }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{/*
	SPDX-License-Identifier: AGPL-3.0-only
	SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
*/}}
{{- define "repo_tree_file" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<link rel="stylesheet" href="/:/static/chroma.css" />
		<title>/{{ .path_spec }} &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
		<title>/{{ .path_spec }} &ndash; {{ .repo_name }} &ndash; {{ template "group_path_plain" .group_path }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-tree-file">
		{{ template "header" . }}
		<div class="padding">
			<p>
				/{{ .path_spec }} (<a href="/{{ .group_name }}/:/repos/{{ .repo_name }}/raw/{{ .path_spec }}{{ if .ref_type }}?{{ .ref_type }}={{ .ref_name }}{{ end }}">raw</a>)
				/{{ .path_spec }} (<a href="/{{ template "group_path_plain" .group_path }}/:/repos/{{ .repo_name }}/raw/{{ .path_spec }}{{ if .ref_type }}?{{ .ref_type }}={{ .ref_name }}{{ end }}">raw</a>)
			</p>
			{{ .file_contents }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>

package main

import (
	"errors"
	"net/http"
	"net/url"
	"strings"
)

var (
	err_duplicate_ref_spec = errors.New("duplicate ref spec")
	err_no_ref_spec        = errors.New("no ref spec")
)

func get_param_ref_and_type(r *http.Request) (ref_type, ref string, err error) {
	qr := r.URL.RawQuery
	q, err := url.ParseQuery(qr)
	if err != nil {
		return
	}
	done := false
	for _, _ref_type := range []string{"commit", "branch", "tag"} {
		_ref, ok := q[_ref_type]
		if ok {
			if done {
				err = err_duplicate_ref_spec
				return
			} else {
				done = true
				if len(_ref) != 1 {
					err = err_duplicate_ref_spec
					return
				}
				ref = _ref[0]
				ref_type = _ref_type
			}
		}
	}
	if !done {
		err = err_no_ref_spec
	}
	return
}

func parse_request_uri(request_uri string) (segments []string, params url.Values, err error) {
	path, params_string, _ := strings.Cut(request_uri, "?")

	segments = strings.Split(strings.TrimPrefix(path, "/"), "/")

	for i, segment := range segments {
		segments[i], err = url.PathUnescape(segment)
		if err != nil {
			return
		}
	}

	params, err = url.ParseQuery(params_string)
	return
}

func redirect_with_slash(w http.ResponseWriter, r *http.Request) bool {
	request_uri := r.RequestURI

	path_end := strings.IndexAny(request_uri, "?#")
	var path, rest string
	if path_end == -1 {
		path = request_uri
	} else {
		path = request_uri[:path_end]
		rest = request_uri[path_end:]
	}

	if !strings.HasSuffix(path, "/") {
		http.Redirect(w, r, path+"/"+rest, http.StatusSeeOther)
		return true
	}
	return false
}

func redirect_without_slash(w http.ResponseWriter, r *http.Request) bool {
	request_uri := r.RequestURI

	path_end := strings.IndexAny(request_uri, "?#")
	var path, rest string
	if path_end == -1 {
		path = request_uri
	} else {
		path = request_uri[:path_end]
		rest = request_uri[path_end:]
	}

	if strings.HasSuffix(path, "/") {
		http.Redirect(w, r, strings.TrimSuffix(path, "/")+rest, http.StatusSeeOther)
		return true
	}
	return false
}

func path_escape_cat_segments(segments []string) string {
	for i, segment := range segments {
		segments[i] = url.PathEscape(segment)
	}
	return strings.Join(segments, "/")
}