Hi… I am well aware that this diff view is very suboptimal. It will be fixed when the refactored server comes along!
*: Migrate to the new path scheme
package main import ( "net/http" "os" "path/filepath" "strings" )
func handle_group_repos(w http.ResponseWriter, r *http.Request) {
func handle_group_repos(w http.ResponseWriter, r *http.Request, params map[string]string) {
data := make(map[string]any)
group_name := r.PathValue("group_name")
group_name := params["group_name"]
data["group_name"] = group_name
entries, err := os.ReadDir(filepath.Join(config.Git.Root, group_name))
if err != nil {
_, _ = w.Write([]byte("Error listing repos: " + err.Error()))
return
}
repos := []string{}
for _, entry := range entries {
this_name := entry.Name()
if strings.HasSuffix(this_name, ".git") {
repos = append(repos, strings.TrimSuffix(this_name, ".git"))
}
}
data["repos"] = repos
err = templates.ExecuteTemplate(w, "group_repos", data)
if err != nil {
_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
return
}
}
package main
import (
"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) {
func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]string) {
data := make(map[string]any)
group_name, repo_name, commit_id_specified_string := r.PathValue("group_name"), r.PathValue("repo_name"), r.PathValue("commit_id")
group_name, repo_name, commit_id_specified_string := params["group_name"], params["repo_name"], params["commit_id"]
data["group_name"], data["repo_name"] = group_name, repo_name
repo, err := open_git_repo(group_name, repo_name)
if err != nil {
_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
return
}
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 {
_, _ = w.Write([]byte("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 {
_, _ = w.Write([]byte("Error formatting patch: " + err.Error()))
return
}
_, _ = w.Write([]byte(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
}
data["commit_object"] = commit_object
data["commit_id"] = commit_id_string
parent_commit_hash, patch, err := get_patch_from_commit(commit_object)
if err != nil {
_, _ = w.Write([]byte("Error getting patch from commit: " + err.Error()))
return
}
data["parent_commit_hash"] = parent_commit_hash.String()
data["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)
}
data["file_patches"] = usable_file_patches
err = templates.ExecuteTemplate(w, "repo_commit", data)
if err != nil {
_, _ = w.Write([]byte("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 ( "net/http" )
func handle_repo_index(w http.ResponseWriter, r *http.Request) {
func handle_repo_index(w http.ResponseWriter, r *http.Request, params map[string]string) {
data := make(map[string]any)
group_name, repo_name := r.PathValue("group_name"), r.PathValue("repo_name")
group_name, repo_name := params["group_name"], params["repo_name"]
data["group_name"], data["repo_name"] = group_name, repo_name
repo, err := open_git_repo(group_name, repo_name)
if err != nil {
_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
return
}
head, err := repo.Head()
if err != nil {
_, _ = w.Write([]byte("Error getting repo HEAD: " + err.Error()))
return
}
data["ref"] = head.Name().Short()
head_hash := head.Hash()
recent_commits, err := get_recent_commits(repo, head_hash, 3)
if err != nil {
_, _ = w.Write([]byte("Error getting recent commits: " + err.Error()))
return
}
data["commits"] = recent_commits
commit_object, err := repo.CommitObject(head_hash)
if err != nil {
_, _ = w.Write([]byte("Error getting commit object: " + err.Error()))
return
}
tree, err := commit_object.Tree()
if err != nil {
_, _ = w.Write([]byte("Error getting file tree: " + err.Error()))
return
}
data["readme_filename"], data["readme"] = render_readme_at_tree(tree)
data["files"] = build_display_git_tree(tree)
err = templates.ExecuteTemplate(w, "repo_index", data)
if err != nil {
_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
return
}
}
package main import ( "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) {
func handle_repo_log(w http.ResponseWriter, r *http.Request, params map[string]string) {
data := make(map[string]any)
group_name, repo_name, ref_name := r.PathValue("group_name"), r.PathValue("repo_name"), r.PathValue("ref")
group_name, repo_name, ref_name := params["group_name"], params["repo_name"], params["ref"]
data["group_name"], data["repo_name"], data["ref"] = group_name, repo_name, ref_name
repo, err := open_git_repo(group_name, repo_name)
if err != nil {
_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
return
}
ref, err := repo.Reference(plumbing.NewBranchReferenceName(ref_name), true)
if err != nil {
_, _ = w.Write([]byte("Error getting repo reference: " + err.Error()))
return
}
ref_hash := ref.Hash()
commits, err := get_recent_commits(repo, ref_hash, -1)
if err != nil {
_, _ = w.Write([]byte("Error getting recent commits: " + err.Error()))
return
}
data["commits"] = commits
err = templates.ExecuteTemplate(w, "repo_log", data)
if err != nil {
_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
return
}
}
package main import ( "errors" "net/http" "path" "strings" "github.com/go-git/go-git/v5/plumbing/object" )
func handle_repo_raw(w http.ResponseWriter, r *http.Request) {
func handle_repo_raw(w http.ResponseWriter, r *http.Request, params map[string]string) {
data := make(map[string]any)
raw_path_spec := r.PathValue("rest")
group_name, repo_name, path_spec := r.PathValue("group_name"), r.PathValue("repo_name"), strings.TrimSuffix(raw_path_spec, "/")
raw_path_spec := params["rest"] group_name, repo_name, path_spec := params["group_name"], params["repo_name"], 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 {
_, _ = w.Write([]byte("Error querying ref type: " + err.Error()))
return
}
}
data["ref_type"], data["ref"], data["group_name"], data["repo_name"], data["path_spec"] = ref_type, ref_name, group_name, repo_name, path_spec
repo, err := open_git_repo(group_name, repo_name)
if err != nil {
_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
return
}
ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
if err != nil {
_, _ = w.Write([]byte("Error getting ref hash: " + err.Error()))
return
}
commit_object, err := repo.CommitObject(ref_hash)
if err != nil {
_, _ = w.Write([]byte("Error getting commit object: " + err.Error()))
return
}
tree, err := commit_object.Tree()
if err != nil {
_, _ = w.Write([]byte("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 {
_, _ = w.Write([]byte("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 {
_, _ = w.Write([]byte("Error reading file: " + err.Error()))
return
}
_, _ = w.Write([]byte(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
}
data["files"] = build_display_git_tree(target)
err = templates.ExecuteTemplate(w, "repo_raw_dir", data)
if err != nil {
_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
return
}
}
package main import ( "bytes" "errors" "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) {
func handle_repo_tree(w http.ResponseWriter, r *http.Request, params map[string]string) {
data := make(map[string]any)
raw_path_spec := r.PathValue("rest")
group_name, repo_name, path_spec := r.PathValue("group_name"), r.PathValue("repo_name"), strings.TrimSuffix(raw_path_spec, "/")
raw_path_spec := params["rest"] group_name, repo_name, path_spec := params["group_name"], params["repo_name"], 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 {
_, _ = w.Write([]byte("Error querying ref type: " + err.Error()))
return
}
}
data["ref_type"], data["ref"], data["group_name"], data["repo_name"], data["path_spec"] = ref_type, ref_name, group_name, repo_name, path_spec
repo, err := open_git_repo(group_name, repo_name)
if err != nil {
_, _ = w.Write([]byte("Error opening repo: " + err.Error()))
return
}
ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
if err != nil {
_, _ = w.Write([]byte("Error getting ref hash: " + err.Error()))
return
}
commit_object, err := repo.CommitObject(ref_hash)
if err != nil {
_, _ = w.Write([]byte("Error getting commit object: " + err.Error()))
return
}
tree, err := commit_object.Tree()
if err != nil {
_, _ = w.Write([]byte("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 {
_, _ = w.Write([]byte("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 {
_, _ = w.Write([]byte("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 {
_, _ = w.Write([]byte("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 {
_, _ = w.Write([]byte("Error formatting code: " + err.Error()))
return
}
formatted_encapsulated := template.HTML(formatted_unencapsulated.Bytes())
data["file_contents"] = formatted_encapsulated
err = templates.ExecuteTemplate(w, "repo_tree_file", data)
if err != nil {
_, _ = w.Write([]byte("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
}
data["readme_filename"], data["readme"] = render_readme_at_tree(target)
data["files"] = build_display_git_tree(target)
err = templates.ExecuteTemplate(w, "repo_tree_dir", data)
if err != nil {
_, _ = w.Write([]byte("Error rendering template: " + err.Error()))
return
}
}
package main
import (
"flag"
"net"
"net/http"
"go.lindenii.runxiyu.org/lindenii-common/clog"
)
func main() {
config_path := flag.String(
"config",
"/etc/lindenii/forge.scfg",
"path to configuration file",
)
flag.Parse()
err := load_config(*config_path)
if err != nil {
clog.Fatal(1, "Loading configuration: "+err.Error())
}
err = load_templates()
if err != nil {
clog.Fatal(1, "Loading templates: "+err.Error())
}
err = serve_static()
if err != nil {
clog.Fatal(1, "Serving static: "+err.Error())
}
serve_source()
http.HandleFunc("/{$}", handle_index)
http.HandleFunc("/g/{group_name}/repos/{$}", handle_group_repos)
http.HandleFunc("/g/{group_name}/repos/{repo_name}/{$}", handle_repo_index)
http.HandleFunc("/g/{group_name}/repos/{repo_name}/tree/{rest...}", handle_repo_tree)
http.HandleFunc("/g/{group_name}/repos/{repo_name}/raw/{rest...}", handle_repo_raw)
http.HandleFunc("/g/{group_name}/repos/{repo_name}/log/{ref}/", handle_repo_log)
http.HandleFunc("/g/{group_name}/repos/{repo_name}/commit/{commit_id}", handle_repo_commit)
// http.HandleFunc("/{$}", handle_index)
// http.HandleFunc("/g/{group_name}/repos/{$}", handle_group_repos)
// http.HandleFunc("/g/{group_name}/repos/{repo_name}/{$}", handle_repo_index)
// http.HandleFunc("/g/{group_name}/repos/{repo_name}/tree/{rest...}", handle_repo_tree)
// http.HandleFunc("/g/{group_name}/repos/{repo_name}/raw/{rest...}", handle_repo_raw)
// http.HandleFunc("/g/{group_name}/repos/{repo_name}/log/{ref}/", handle_repo_log)
// http.HandleFunc("/g/{group_name}/repos/{repo_name}/commit/{commit_id}", handle_repo_commit)
listener, err := net.Listen(config.HTTP.Net, config.HTTP.Addr)
if err != nil {
clog.Fatal(1, "Listening: "+err.Error())
}
err = http.Serve(listener, nil)
err = http.Serve(listener, &http_router_t{})
if err != nil {
clog.Fatal(1, "Serving: "+err.Error())
}
}
package main import ( "embed" "html/template" "io/fs" "net/http" ) //go:embed .gitignore LICENSE README.md //go:embed *.go go.mod go.sum //go:embed *.scfg //go:embed static/* templates/* var source_fs embed.FS
func serve_source() {
http.Handle("/source/",
http.StripPrefix(
"/source/",
http.FileServer(http.FS(source_fs)),
),
var source_handler http.Handler
func init() {
source_handler = http.StripPrefix(
"/:/source/",
http.FileServer(http.FS(source_fs)),
)
}
//go:embed templates/* static/*
var resources_fs embed.FS
var templates *template.Template
func load_templates() (err error) {
templates, err = template.New("templates").Funcs(template.FuncMap{
"first_line": first_line,
"base_name": base_name,
}).ParseFS(resources_fs, "templates/*")
return err
}
func serve_static() (err error) {
var static_handler http.Handler
func init() {
static_fs, err := fs.Sub(resources_fs, "static")
if err != nil {
return err
panic(err)
}
http.Handle("/static/",
http.StripPrefix(
"/static/",
http.FileServer(http.FS(static_fs)),
),
)
return nil
static_handler = http.StripPrefix("/:/static/", http.FileServer(http.FS(static_fs)))
}
package main
import (
"errors"
"fmt"
"net/http"
"strings"
)
type http_router_t struct{}
func (router *http_router_t) ServeHTTP(w http.ResponseWriter, r *http.Request) {
segments, _, err := parse_request_uri(r.RequestURI)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if segments[0] == ":" {
switch segments[1] {
case "static":
static_handler.ServeHTTP(w, r)
case "source":
source_handler.ServeHTTP(w, r)
default:
fmt.Fprintln(w, "Unknown system module type:", segments[1])
}
return
}
separator_index := -1
for i, part := range segments {
if part == ":" {
separator_index = i
break
}
}
non_empty_last_segments_len := len(segments)
dir_mode := false
if segments[len(segments)-1] == "" {
non_empty_last_segments_len--
dir_mode = true
}
params := make(map[string]string)
_ = params
switch {
case non_empty_last_segments_len == 0:
handle_index(w, r)
case separator_index == -1:
fmt.Fprintln(w, "Group indexing hasn't been implemented yet")
case non_empty_last_segments_len == separator_index+1:
fmt.Fprintln(w, "Group root hasn't been implemented yet")
case non_empty_last_segments_len == separator_index+2:
module_type := segments[separator_index+1]
params["group_name"] = segments[0]
switch module_type {
case "repos":
handle_group_repos(w, r, params)
default:
fmt.Fprintln(w, "Unknown module type:", module_type)
}
default:
module_type := segments[separator_index+1]
module_name := segments[separator_index+2]
params["group_name"] = segments[0]
switch module_type {
case "repos":
params["repo_name"] = module_name
// TODO: subgroups
if non_empty_last_segments_len == separator_index+3 {
if !dir_mode {
http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther)
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:], "/")
handle_repo_tree(w, r, params)
case "raw":
params["rest"] = strings.Join(segments[separator_index+4:], "/")
handle_repo_raw(w, r, params)
case "log":
params["ref"] = segments[separator_index+4]
handle_repo_log(w, r, params)
case "commit":
params["commit_id"] = segments[separator_index+4]
handle_repo_commit(w, r, params)
}
default:
fmt.Fprintln(w, "Unknown module type:", module_type)
}
}
}
var err_bad_request = errors.New("Bad Request")
{{- define "footer" -}}
<a href="https://lindenii.runxiyu.org/forge/">Lindenii Forge</a> (<a href="/source/">source</a>, <a href="https://forge.lindenii.runxiyu.org/g/lindenii/repos/forge/">upstream</a>)
<a href="https://lindenii.runxiyu.org/forge/">Lindenii Forge</a> (<a href="/:/source/">source</a>, <a href="https://forge.lindenii.runxiyu.org/g/lindenii/repos/forge/">upstream</a>)
{{- end -}}
{{- define "head_common" -}}
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/static/style.css" />
<link rel="stylesheet" href="/:/static/style.css" />
{{- end -}}
{{- define "repo_header" -}}
<a href="/">Lindenii Forge</a>
/
g
<a href="/{{ .group_name }}/">{{ .group_name }}</a>
/
<a href="/g/{{ .group_name }}/">{{ .group_name }}</a>
<a href="/{{ .group_name }}/:">:</a>
/
<a href="/g/{{ .group_name }}/repos/">repos</a>
<a href="/{{ .group_name }}/:/repos/">repos</a>
/
<a href="/g/{{ .group_name }}/repos/{{ .repo_name }}/">{{ .repo_name }}</a>
<a href="/{{ .group_name }}/:/repos/{{ .repo_name }}/">{{ .repo_name }}</a>
{{- end -}}
{{- define "index" -}}
<!DOCTYPE html>
<html lang="en">
<head>
{{ template "head_common" . }}
<title>Groups – Lindenii Forge</title>
</head>
<body class="index">
<div class="padding-wrapper">
<h1>
Groups
</h1>
<ul>
{{- range .groups }}
<li>
<a href="g/{{ . }}/repos/">{{ . }}</a>
<a href="{{ . }}/:/repos/">{{ . }}</a>
</li>
{{- end }}
</ul>
</div>
<footer>
{{ template "footer" . }}
</footer>
</body>
</html>
{{- end -}}
{{- define "repo_tree_file" -}}
<!DOCTYPE html>
<html lang="en">
<head>
{{ template "head_common" . }}
<link rel="stylesheet" href="/static/chroma.css" />
<title>{{ .group_name }}/repos/{{ .repo_name }}/{{ .path_spec }} – Lindenii Forge</title>
</head>
<body class="repo-tree-file">
<header>
{{ template "repo_header" . }}
</header>
<p>
/{{ .path_spec }} (<a href="/g/{{ .group_name }}/repos/{{ .repo_name }}/raw/{{ .path_spec }}{{ if not (eq .ref_type "head") }}?{{ .ref_type }}={{ .ref }}{{ end }}">raw</a>)
/{{ .path_spec }} (<a href="/{{ .group_name }}/:/repos/{{ .repo_name }}/raw/{{ .path_spec }}{{ if not (eq .ref_type "head") }}?{{ .ref_type }}={{ .ref }}{{ end }}">raw</a>)
</p>
{{ .file_contents }}
<footer>
{{ template "footer" . }}
</footer>
</body>
</html>
{{- end -}}
package main import ( "errors" "net/http" "net/url"
"strings" "go.lindenii.runxiyu.org/lindenii-common/misc"
)
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], _ = url.QueryUnescape(segment)
}
params, err = url.ParseQuery(params_string)
if err != nil {
return nil, nil, misc.Wrap_one_error(err_bad_request, err)
}
return
}