Lindenii Project Forge
Commit info | |
---|---|
ID | 3aae548374b0ca19b9e14c30a1ca6790251cc1db |
Author | Runxi Yu<me@runxiyu.org> |
Author date | Sat, 15 Feb 2025 10:23:08 +0800 |
Committer | Runxi Yu<me@runxiyu.org> |
Committer date | Sat, 15 Feb 2025 10:23:08 +0800 |
Actions | Get patch |
*.go: Reformat
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 []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) { group_name, repo_name, commit_id_specified_string := params["group_name"].(string), params["repo_name"].(string), params["commit_id"].(string) repo, description, err := open_git_repo(r.Context(), group_name, repo_name) if err != nil { http.Error(w, "Error opening repo: "+err.Error(), http.StatusInternalServerError) 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 { 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 // 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 } chunks := []usable_chunk{}
for _, chunk := range file_patch.Chunks() {
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) } 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 ( "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) trailing_slash := false if segments[len(segments)-1] == "" { non_empty_last_segments_len-- trailing_slash = true } 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["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 } } 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] params["group_name"] = segments[0] switch module_type { case "repos": params["repo_name"] = module_name 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 if non_empty_last_segments_len == separator_index+3 {
if redirect_with_slash(w, r) { return }
if redirect_with_slash(w, r) { return }
handle_repo_index(w, r, params) return } repo_feature := segments[separator_index+3] switch repo_feature { case "info": handle_repo_info(w, r, params) case "tree": params["rest"] = strings.Join(segments[separator_index+4:], "/") if len(segments) < separator_index+5 && redirect_with_slash(w, r) {
return
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 trailing_slash { http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, "/"), http.StatusSeeOther) // TODO return } params["commit_id"] = segments[separator_index+4] handle_repo_commit(w, r, params) 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")
package main import ( "fmt" "net" "os" "os/exec" "strings" glider_ssh "github.com/gliderlabs/ssh" "go.lindenii.runxiyu.org/lindenii-common/clog" go_ssh "golang.org/x/crypto/ssh" ) var ( server_public_key_string string server_public_key_fingerprint string server_public_key go_ssh.PublicKey ) func serve_ssh(listener net.Listener) error { host_key_bytes, err := os.ReadFile(config.SSH.Key) if err != nil { return err } host_key, err := go_ssh.ParsePrivateKey(host_key_bytes) if err != nil { return err } server_public_key = host_key.PublicKey() server_public_key_string = string(go_ssh.MarshalAuthorizedKey(server_public_key)) server_public_key_fingerprint = string(go_ssh.FingerprintSHA256(server_public_key)) server := &glider_ssh.Server{ Handler: func(session glider_ssh.Session) { client_public_key := session.PublicKey() var client_public_key_string string if client_public_key != nil { client_public_key_string = string(go_ssh.MarshalAuthorizedKey(client_public_key)) } clog.Info("Incoming SSH: " + session.RemoteAddr().String() + " " + strings.TrimSuffix(client_public_key_string, "\n") + " " + session.RawCommand())
fmt.Fprintln(session.Stderr(), "Lindenii Forge " + VERSION + ", source at " + strings.TrimSuffix(config.HTTP.Root, "/") + "/:/source/\r")
fmt.Fprintln(session.Stderr(), "Lindenii Forge "+VERSION+", source at "+strings.TrimSuffix(config.HTTP.Root, "/")+"/:/source/\r")
cmd := session.Command() if len(cmd) < 2 { fmt.Fprintln(session.Stderr(), "Insufficient arguments\r") return } if cmd[0] != "git-upload-pack" { fmt.Fprintln(session.Stderr(), "Unsupported command\r") return } fs_path, err := get_repo_path_from_ssh_path(session.Context(), cmd[1]) if err != nil { fmt.Fprintln(session.Stderr(), "Error while getting repo path:", err, "\r") return } proc := exec.CommandContext(session.Context(), cmd[0], fs_path) proc.Stdin = session proc.Stdout = session proc.Stderr = session.Stderr() err = proc.Start() if err != nil { fmt.Fprintln(session.Stderr(), "Error while starting process:", err) return } err = proc.Wait() if exit_error, ok := err.(*exec.ExitError); ok { fmt.Fprintln(session.Stderr(), "Process exited with error", exit_error.ExitCode()) } else if err != nil { fmt.Fprintln(session.Stderr(), "Error while waiting for process:", err) } }, PublicKeyHandler: func(ctx glider_ssh.Context, key glider_ssh.PublicKey) bool { return true }, KeyboardInteractiveHandler: func(ctx glider_ssh.Context, challenge go_ssh.KeyboardInteractiveChallenge) bool { return true }, // It is intentional that we do not check any credentials and accept all connections. // This allows all users to connect and clone repositories; when pushing is added later, // we will check their public key in the session handler, not in the auth handlers. } server.AddHostKey(host_key) go func() { err = server.Serve(listener) if err != nil { clog.Fatal(1, "Serving SSH: "+err.Error()) } }() return nil }
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")
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 nil, nil, misc.Wrap_one_error(err_bad_request, err) } } params, err = url.ParseQuery(params_string) if err != nil { return nil, nil, misc.Wrap_one_error(err_bad_request, err) } 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 }