Lindenii Project Forge
Login
Commit info
IDded9d435b081ab552d8c5d4e1f655e7b26a8be0a
AuthorRunxi Yu<me@runxiyu.org>
Author dateWed, 19 Feb 2025 08:45:09 +0800
CommitterRunxi Yu<me@runxiyu.org>
Committer dateWed, 19 Feb 2025 08:49:05 +0800
Actions
Get patch
repo/contrib: Display merge request diffs
package main

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

	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/filemode"
	"github.com/go-git/go-git/v5/plumbing/format/diff"
	"go.lindenii.runxiyu.org/lindenii-common/misc"
)

// The file patch type from go-git isn't really usable in HTML templates
// either.
type usable_file_patch struct {
	From   diff.File
	To     diff.File
	Chunks []usable_chunk
}

type usable_chunk struct {
	Operation diff.Operation
	Content   string
}

func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]any) {
	repo, commit_id_specified_string := params["repo"].(*git.Repository), params["commit_id"].(string)

	commit_id_specified_string_without_suffix := strings.TrimSuffix(commit_id_specified_string, ".patch")
	commit_id := plumbing.NewHash(commit_id_specified_string_without_suffix)
	commit_object, err := repo.CommitObject(commit_id)
	if err != nil {
		http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError)
		return
	}
	if commit_id_specified_string_without_suffix != commit_id_specified_string {
		patch, err := format_patch_from_commit(commit_object)
		if err != nil {
			http.Error(w, "Error formatting patch: "+err.Error(), http.StatusInternalServerError)
			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 {
		http.Error(w, "Error getting patch from commit: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["parent_commit_hash"] = parent_commit_hash.String()
	params["patch"] = patch

	params["file_patches"] = make_usable_file_patches(patch)

	render_template(w, "repo_commit", params)
}

type fake_diff_file struct {
	hash plumbing.Hash
	mode filemode.FileMode
	path string
}

func (f fake_diff_file) Hash() plumbing.Hash {
	return f.hash
}

func (f fake_diff_file) Mode() filemode.FileMode {
	return f.mode
}

func (f fake_diff_file) Path() string {
	return f.path
}

var fake_diff_file_null = fake_diff_file{
	hash: plumbing.NewHash("0000000000000000000000000000000000000000"),
	mode: misc.First_or_panic(filemode.New("100644")),
	path: "",
}

func make_usable_file_patches(patch diff.Patch) (usable_file_patches []usable_file_patch) {
	// TODO: Remove unnecessary context
	// TODO: Prepend "+"/"-"/" " instead of solely distinguishing based on color
	usable_file_patches := make([]usable_file_patch, 0)
	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
		}
		chunks := []usable_chunk{}
		for _, chunk := range file_patch.Chunks() {
			content := chunk.Content()
			if len(content) > 0 && content[0] == '\n' {
				content = "\n" + content
			} // Horrible hack to fix how browsers newlines that immediately proceed <pre>
			chunks = append(chunks, usable_chunk{
				Operation: chunk.Type(),
				Content:   content,
			})
		}
		usable_file_patch := usable_file_patch{
			Chunks: chunks,
			From:   from,
			To:     to,
		}
		usable_file_patches = append(usable_file_patches, usable_file_patch)
	}
	params["file_patches"] = usable_file_patches

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

import (
	"net/http"
)

func handle_repo_contrib_num(w http.ResponseWriter, r *http.Request, params map[string]any) {
	render_template(w, "repo_contrib_num", params)
}
package main

import (
	"net/http"
	"strconv"

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

func handle_repo_contrib_one(w http.ResponseWriter, r *http.Request, params map[string]any) {
	mr_id_string := params["mr_id"].(string)
	mr_id, err := strconv.ParseInt(mr_id_string, 10, strconv.IntSize)
	if err != nil {
		http.Error(w, "Merge request ID not an integer: "+err.Error(), http.StatusBadRequest)
		return
	}

	var title, status, source_ref, destination_branch string
	err = database.QueryRow(r.Context(), "SELECT title, status, source_ref, destination_branch FROM merge_requests WHERE id = $1", mr_id).Scan(&title, &status, &source_ref, &destination_branch)
	if err != nil {
		http.Error(w, "Error querying merge request: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["mr_title"], params["mr_status"], params["mr_source_ref"], params["mr_destination_branch"] = title, status, source_ref, destination_branch

	repo := params["repo"].(*git.Repository)

	source_ref_hash, err := get_ref_hash_from_type_and_name(repo, "branch", source_ref)
	if err != nil {
		http.Error(w, "Error getting source ref hash: "+err.Error(), http.StatusInternalServerError)
		return
	}
	source_commit, err := repo.CommitObject(source_ref_hash)
	if err != nil {
		http.Error(w, "Error getting source commit: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["source_commit"] = source_commit

	destination_branch_hash, err := get_ref_hash_from_type_and_name(repo, "branch", destination_branch)
	if err != nil {
		http.Error(w, "Error getting destination branch hash: "+err.Error(), http.StatusInternalServerError)
		return
	}
	destination_commit, err := repo.CommitObject(destination_branch_hash)
	if err != nil {
		http.Error(w, "Error getting destination commit: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["source_commit"] = source_commit

	patch, err := destination_commit.Patch(source_commit)
	params["file_patches"] = make_usable_file_patches(patch)

	render_template(w, "repo_contrib_one", params)
}
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)

	segments, _, err := parse_request_uri(r.RequestURI)
	if 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 := make(map[string]any)
	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
	}

	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)
		}
	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":
					err = handle_repo_info(w, r, params)
					if err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
					return
				case "git-upload-pack":
					err = handle_upload_pack(w, r, params)
					if err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
					return
				}
			}

			params["ref_type"], params["ref_name"], err = get_param_ref_and_type(r)
			if 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

			params["repo"], params["repo_description"], params["repo_id"], err = open_git_repo(r.Context(), group_name, module_name)
			if err != nil {
				http.Error(w, "Error opening repo: "+err.Error(), http.StatusInternalServerError)
				return
			}

			if non_empty_last_segments_len == separator_index+3 {
				if redirect_with_slash(w, r) {
					return
				}
				handle_repo_index(w, r, params)
				return
			}

			repo_feature := segments[separator_index+3]
			switch repo_feature {
			case "tree":
				params["rest"] = strings.Join(segments[separator_index+4:], "/")
				if len(segments) < separator_index+5 && redirect_with_slash(w, r) {
					return
				}
				handle_repo_tree(w, r, params)
			case "raw":
				params["rest"] = strings.Join(segments[separator_index+4:], "/")
				if len(segments) < separator_index+5 && redirect_with_slash(w, r) {
					return
				}
				handle_repo_raw(w, r, params)
			case "log":
				if non_empty_last_segments_len > separator_index+4 {
					http.Error(w, "Too many parameters", http.StatusBadRequest)
					return
				}
				if redirect_with_slash(w, r) {
					return
				}
				handle_repo_log(w, r, params)
			case "commit":
				if redirect_without_slash(w, r) {
					return
				}
				params["commit_id"] = segments[separator_index+4]
				handle_repo_commit(w, r, params)
			case "contrib":
				if redirect_with_slash(w, r) {
					return
				}
				switch non_empty_last_segments_len {
				case separator_index+4:
					handle_repo_contrib_index(w, r, params)
				case separator_index+5:
					handle_repo_contrib_num(w, r, params)
					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)
		}
	}
}

var err_bad_request = errors.New("Bad Request")
{{- define "repo_contrib_num" -}}
<!DOCTYPE html>
<html lang="en">
	<head>
		{{ template "head_common" . }}
		<title>Merge requests &ndash; {{ .repo_name }} &ndash; {{ .group_name }} &ndash; {{ .global.forge_title }}</title>
	</head>
	<body class="repo-contrib-num">
		{{ template "header" . }}
		<div class="padding-wrapper">
			Test
		</div>
		<footer>
			{{ template "footer" . }}
		</footer>
	</body>
</html>
{{- end -}}
{{- 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>
	</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>
				</tbody>
			</table>
		</div>
		<div class="padding-wrapper">
			{{ $destination_commit := .destination_commit }}
			{{ $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={{ $destination_commit.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 -}}