Lindenii Project Forge
Login
Commit info
IDcfc8bd2bd3930fc91847a71a8d0092c2c85b0f4a
AuthorRunxi Yu<me@runxiyu.org>
Author dateThu, 13 Feb 2025 09:19:54 +0800
CommitterRunxi Yu<me@runxiyu.org>
Committer dateThu, 13 Feb 2025 09:19:54 +0800
Actions
Get patch
repo_index: Add repo descriptions
package main

import (
	"context"
	"errors"
	"io"
	"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"
	"go.lindenii.runxiyu.org/lindenii-common/misc"
)

var (
	err_getting_commit_tree          = errors.New("Error getting commit tree")
	err_getting_patch_of_commit      = errors.New("Error getting patch of commit")
	err_getting_parent_commit_object = errors.New("Error getting parent commit object")
)

func open_git_repo(ctx context.Context, group_name, repo_name string) (*git.Repository, error) {
func open_git_repo(ctx context.Context, group_name, repo_name string) (repo *git.Repository, description string, err error) {
	var fs_path string
	err := database.QueryRow(ctx, "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).Scan(&fs_path)
	err = database.QueryRow(ctx, "SELECT r.filesystem_path, r.description 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)
	if err != nil {
		return nil, err
		return nil, "", err
	}
	return git.PlainOpen(fs_path)
	repo, err = git.PlainOpen(fs_path)
	return
}

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_entry_t {
	display_git_tree := make([]display_git_tree_entry_t, 0)
	for _, entry := range tree.Entries {
		display_git_tree_entry := display_git_tree_entry_t{}
		os_mode, err := entry.Mode.ToOSFileMode()
		if err != nil {
			display_git_tree_entry.Mode = "x---"
		} else {
			display_git_tree_entry.Mode = os_mode.String()[:4]
		}
		display_git_tree_entry.Is_file = entry.Mode.IsFile()
		display_git_tree_entry.Size, err = tree.Size(entry.Name)
		if 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
}

var err_get_recent_commits = errors.New("Error getting recent commits")

func get_recent_commits(repo *git.Repository, head_hash plumbing.Hash, number_of_commits int) (recent_commits []*object.Commit, err error) {
	commit_iter, err := repo.Log(&git.LogOptions{From: head_hash})
	if err != nil {
		err = misc.Wrap_one_error(err_get_recent_commits, err)
		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 {
				err = misc.Wrap_one_error(err_get_recent_commits, err)
				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 {
				err = misc.Wrap_one_error(err_get_recent_commits, err)
				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, ret_err error) {
	parent_commit_object, err := commit_object.Parent(0)
	if errors.Is(err, object.ErrParentNotFound) {
		commit_tree, err := commit_object.Tree()
		if err != nil {
			ret_err = misc.Wrap_one_error(err_getting_commit_tree, err)
			return
		}
		patch, err = (&object.Tree{}).Patch(commit_tree)
		if err != nil {
			ret_err = misc.Wrap_one_error(err_getting_patch_of_commit, err)
			return
		}
	} else if err != nil {
		ret_err = misc.Wrap_one_error(err_getting_parent_commit_object, err)
		return
	} else {
		parent_commit_hash = parent_commit_object.Hash
		patch, err = parent_commit_object.Patch(commit_object)
		if err != nil {
			ret_err = misc.Wrap_one_error(err_getting_patch_of_commit, err)
			return
		}
	}
	return
}
package main

import (
	"fmt"
	"net/http"
	"strings"

	"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"
	"go.lindenii.runxiyu.org/lindenii-common/misc"
)

type usable_file_patch struct {
	From   diff.File
	To     diff.File
	Chunks []diff.Chunk
}

func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name, commit_id_specified_string := params["group_name"].(string), params["repo_name"].(string), params["commit_id"].(string)
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		return
	}
	params["repo_description"] = description
	commit_id_specified_string_without_suffix := strings.TrimSuffix(commit_id_specified_string, ".patch")
	commit_id := plumbing.NewHash(commit_id_specified_string_without_suffix)
	commit_object, err := repo.CommitObject(commit_id)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		return
	}
	if commit_id_specified_string_without_suffix != commit_id_specified_string {
		patch, err := format_patch_from_commit(commit_object)
		if err != nil {
			fmt.Fprintln(w, "Error formatting patch:", err.Error())
			return
		}
		fmt.Fprintln(w, 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)
	if err != nil {
		fmt.Fprintln(w, "Error getting patch from commit:", err.Error())
		return
	}
	params["parent_commit_hash"] = parent_commit_hash.String()
	params["patch"] = patch

	// TODO: Remove unnecessary context                                          
	// TODO: Prepend "+"/"-"/" " instead of solely distinguishing based on color
	usable_file_patches := make([]usable_file_patch, 0)
	for _, file_patch := range patch.FilePatches() {
		from, to := file_patch.Files()
		if from == nil {
			from = fake_diff_file_null
		}
		if to == nil {
			to = fake_diff_file_null
		}
		usable_file_patch := usable_file_patch{
			Chunks: file_patch.Chunks(),
			From:   from,
			To:     to,
		}
		usable_file_patches = append(usable_file_patches, usable_file_patch)
	}
	params["file_patches"] = usable_file_patches

	err = templates.ExecuteTemplate(w, "repo_commit", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		return
	}
}

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("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"),
	mode: misc.First_or_panic(filemode.New("100644")),
	path: "",
}
package main

import (
	"fmt"
	"net/http"
	"net/url"
)

func handle_repo_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name := params["group_name"].(string), params["repo_name"].(string)
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		return
	}
	params["repo_description"] = description
	head, err := repo.Head()
	if err != nil {
		fmt.Fprintln(w, "Error getting repo HEAD:", err.Error())
		return
	}
	params["ref"] = head.Name().Short()
	head_hash := head.Hash()
	recent_commits, err := get_recent_commits(repo, head_hash, 3)
	if err != nil {
		fmt.Fprintln(w, "Error getting recent commits:", err.Error())
		return
	}
	params["commits"] = recent_commits
	commit_object, err := repo.CommitObject(head_hash)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		fmt.Fprintln(w, "Error getting file tree:", err.Error())
		return
	}

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

	params["clone_url"] = "ssh://" + r.Host + "/" + url.PathEscape(group_name) + "/:/repos/" + url.PathEscape(repo_name)

	err = templates.ExecuteTemplate(w, "repo_index", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		return
	}
}
package main

import (
	"fmt"
	"net/http"

	"github.com/go-git/go-git/v5/plumbing"
)

// TODO: I probably shouldn't include *all* commits here...
func handle_repo_log(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name, ref_name := params["group_name"].(string), params["repo_name"].(string), params["ref"].(string)
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		return
	}
	params["repo_description"] = description
	ref, err := repo.Reference(plumbing.NewBranchReferenceName(ref_name), true)
	if err != nil {
		fmt.Fprintln(w, "Error getting repo reference:", err.Error())
		return
	}
	ref_hash := ref.Hash()
	commits, err := get_recent_commits(repo, ref_hash, -1)
	if err != nil {
		fmt.Fprintln(w, "Error getting recent commits:", err.Error())
		return
	}
	params["commits"] = commits

	err = templates.ExecuteTemplate(w, "repo_log", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		return
	}
}
package main

import (
	"fmt"
	"errors"
	"net/http"
	"path"
	"strings"

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

func handle_repo_raw(w http.ResponseWriter, r *http.Request, params map[string]any) {
	raw_path_spec := params["rest"].(string)
	group_name, repo_name, path_spec := params["group_name"].(string), params["repo_name"].(string), strings.TrimSuffix(raw_path_spec, "/")

	ref_type, ref_name, err := get_param_ref_and_type(r)
	if err != nil {
		if errors.Is(err, err_no_ref_spec) {
			ref_type = "head"
		} else {
			fmt.Fprintln(w, "Error querying ref type:", err.Error())
			return
		}
	}

	params["ref_type"], params["ref"], params["path_spec"] = ref_type, ref_name, path_spec

	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		return
	}
	params["repo_description"] = description

	ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
	if err != nil {
		fmt.Fprintln(w, "Error getting ref hash:", err.Error())
		return
	}

	commit_object, err := repo.CommitObject(ref_hash)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		fmt.Fprintln(w, "Error getting file tree:", err.Error())
		return
	}

	var target *object.Tree
	if path_spec == "" {
		target = tree
	} else {
		target, err = tree.Tree(path_spec)
		if err != nil {
			file, err := tree.File(path_spec)
			if err != nil {
				fmt.Fprintln(w, "Error retrieving path:", err.Error())
				return
			}
			if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' {
				http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther)
				return
			}
			file_contents, err := file.Contents()
			if err != nil {
				fmt.Fprintln(w, "Error reading file:", err.Error())
				return
			}
			fmt.Fprintln(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)

	err = templates.ExecuteTemplate(w, "repo_raw_dir", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		return
	}
}
package main

import (
	"bytes"
	"errors"
	"fmt"
	"html/template"
	"net/http"
	"path"
	"strings"

	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/plumbing/object"
)

func handle_repo_tree(w http.ResponseWriter, r *http.Request, params map[string]any) {
	raw_path_spec := params["rest"].(string)
	group_name, repo_name, path_spec := params["group_name"].(string), params["repo_name"].(string), strings.TrimSuffix(raw_path_spec, "/")
	ref_type, ref_name, err := get_param_ref_and_type(r)
	if err != nil {
		if errors.Is(err, err_no_ref_spec) {
			ref_type = "head"
		} else {
			fmt.Fprintln(w, "Error querying ref type:", err.Error())
			return
		}
	}
	params["ref_type"], params["ref"], params["path_spec"] = ref_type, ref_name, path_spec
	repo, err := open_git_repo(r.Context(), group_name, repo_name)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		return
	}
	params["repo_description"] = description

	ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
	if err != nil {
		fmt.Fprintln(w, "Error getting ref hash:", err.Error())
		return
	}
	commit_object, err := repo.CommitObject(ref_hash)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		fmt.Fprintln(w, "Error getting file tree:", err.Error())
		return
	}

	var target *object.Tree
	if path_spec == "" {
		target = tree
	} else {
		target, err = tree.Tree(path_spec)
		if err != nil {
			file, err := tree.File(path_spec)
			if err != nil {
				fmt.Fprintln(w, "Error retrieving path:", err.Error())
				return
			}
			if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' {
				http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther)
				return
			}
			file_contents, err := file.Contents()
			if err != nil {
				fmt.Fprintln(w, "Error reading file:", err.Error())
				return
			}
			lexer := chroma_lexers.Match(path_spec)
			if lexer == nil {
				lexer = chroma_lexers.Fallback
			}
			iterator, err := lexer.Tokenise(nil, file_contents)
			if err != nil {
				fmt.Fprintln(w, "Error tokenizing code:", err.Error())
				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))
			err = formatter.Format(&formatted_unencapsulated, style, iterator)
			if err != nil {
				fmt.Fprintln(w, "Error formatting code:", err.Error())
				return
			}
			formatted_encapsulated := template.HTML(formatted_unencapsulated.Bytes())
			params["file_contents"] = formatted_encapsulated

			err = templates.ExecuteTemplate(w, "repo_tree_file", params)
			if err != nil {
				fmt.Fprintln(w, "Error rendering template:", err.Error())
				return
			}
			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)

	err = templates.ExecuteTemplate(w, "repo_tree_dir", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		return
	}
}
{{- define "repo_index" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>{{ .group_name }}/repos/{{ .repo_name }} &ndash; Lindenii Forge</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>
					<tr>
						<th scope="row">Clone</th>
						<td><code>git clone {{ .clone_url }}</code></td>
					</tr>
					{{ if .repo_description }}
						<tr>
							<th scope="row">Description</th>
							<td>{{ .repo_description }}</td>
						</tr>
					{{ end }}
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper scroll">
			<input id="toggle-table-recent-commits" type="checkbox" class="toggle-table-off" />
			<table id="recent-commits" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3"><label for="toggle-table-recent-commits">Recent Commits (<a href="log/{{ .ref }}/">see all</a>)</label></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">
			<input id="toggle-table-file-tree" type="checkbox" class="toggle-table-off" />
			<table id="file-tree" class="wide">
				<thead>
					<tr class="title-row">
						<th colspan="3"><label for="toggle-table-file-tree">/ on {{ .ref }}</label></th>
					</tr>
				</thead>
				<tbody>
					{{- $ref := .ref }}
					{{- range .files }}
						<tr>
							<td class="file-mode">{{ .Mode }}</td>
							<td class="file-name"><a href="tree/{{ .Name }}">{{ .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 }}
				<input id="toggle-table-readme" type="checkbox" class="toggle-table-off" />
				<table class="wide">
					<thead>
						<tr class="title-row">
							<th><label for="toggle-table-readme">{{ .readme_filename }}</label></th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td id="readme">
								{{ .readme -}}
							</td>
						</tr>
					</tbody>
				</table>
			{{ end }}
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}