From 99fd8a9cf96a51fcd9e50445cb035cc9ecd012de Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Sat, 22 Mar 2025 13:44:03 +0800 Subject: [PATCH] Variable name lengths --- .golangci.yaml | 3 +-- fedauth.go | 12 ++++++------ git_hooks_handle.go | 46 ++++++++++++++++++++++++---------------------- git_misc.go | 6 +++--- http_auth.go | 6 +++--- http_handle_gc.go | 4 ++-- http_handle_group_index.go | 54 +++++++++++++++++++++++++++--------------------------- http_handle_index.go | 8 ++++---- http_handle_login.go | 32 ++++++++++++++++---------------- http_handle_repo_commit.go | 30 +++++++++++++++--------------- http_handle_repo_contrib_index.go | 20 ++++++++++---------- http_handle_repo_contrib_one.go | 22 +++++++++++----------- http_handle_repo_index.go | 4 ++-- http_handle_repo_info.go | 14 +++++++------- http_handle_repo_log.go | 8 ++++---- http_handle_repo_raw.go | 20 ++++++++++---------- http_handle_repo_tree.go | 24 ++++++++++++------------ http_handle_repo_upload_pack.go | 16 ++++++++-------- http_handle_users.go | 4 ++-- http_server.go | 92 +++++++++++++++++++++++++++--------------------------- irc.go | 14 +++++++------- resources.go | 11 +++++++---- url.go | 26 +++++++++++++------------- users.go | 12 ++++++------ diff --git a/.golangci.yaml b/.golangci.yaml index 71397ccb8f92aa2790e1ca57b93d122cdea96705..97ad78687d410e2bae80d323fc43a9da3e380001 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -13,6 +13,7 @@ - lll # long lines are acceptable - mnd # it's a bit ridiculous to replace all of them - nakedret # patterns should be consistent - nonamedreturns # i like named returns + - wrapcheck # wrapping all errors is just not necessary - maintidx # e - nestif # e - gocognit # e @@ -22,8 +23,6 @@ - goconst # e - funlen # e - wsl # e - nlreturn # e - - wrapcheck # e - - varnamelen # e issues: max-issues-per-linter: 0 diff --git a/fedauth.go b/fedauth.go index 2012e19a4471ed76199c4c6e86d4da0dc45e5d8c..0528fa3b86bf5f0173fbe8ddc59590fbc0859b0c 100644 --- a/fedauth.go +++ b/fedauth.go @@ -72,20 +72,20 @@ if !matched { return false, nil } - var tx pgx.Tx - if tx, err = database.Begin(ctx); err != nil { + var txn pgx.Tx + if txn, err = database.Begin(ctx); err != nil { return false, err } defer func() { - _ = tx.Rollback(ctx) + _ = txn.Rollback(ctx) }() - if _, err = tx.Exec(ctx, `UPDATE users SET type = 'federated' WHERE id = $1 AND type = 'pubkey_only'`, userID); err != nil { + if _, err = txn.Exec(ctx, `UPDATE users SET type = 'federated' WHERE id = $1 AND type = 'pubkey_only'`, userID); err != nil { return false, err } - if _, err = tx.Exec(ctx, `INSERT INTO federated_identities (user_id, service, remote_username) VALUES ($1, $2, $3)`, userID, service, remoteUsername); err != nil { + if _, err = txn.Exec(ctx, `INSERT INTO federated_identities (user_id, service, remote_username) VALUES ($1, $2, $3)`, userID, service, remoteUsername); err != nil { return false, err } - if err = tx.Commit(ctx); err != nil { + if err = txn.Commit(ctx); err != nil { return false, err } diff --git a/git_hooks_handle.go b/git_hooks_handle.go index ca46d61f925a50487f333e2b3e298a1c6d27f6ea..f41507c8666f056193d124323c0db5e4a14f2977 100644 --- a/git_hooks_handle.go +++ b/git_hooks_handle.go @@ -39,7 +39,6 @@ var err error var cookie []byte var packPass packPass var sshStderr io.Writer - var ok bool var hookRet byte defer conn.Close() @@ -73,13 +72,16 @@ writeRedError(conn, "\nFailed to read cookie: %v", err) return } - packPass, ok = packPasses.Load(string(cookie)) - if !ok { - if _, err = conn.Write([]byte{1}); err != nil { + { + var ok bool + packPass, ok = packPasses.Load(string(cookie)) + if !ok { + if _, err = conn.Write([]byte{1}); err != nil { + return + } + writeRedError(conn, "\nInvalid handler cookie") return } - writeRedError(conn, "\nInvalid handler cookie") - return } sshStderr = packPass.session.Stderr() @@ -96,16 +98,16 @@ var args []string for range argc64 { var arg bytes.Buffer for { - b := make([]byte, 1) - n, err := conn.Read(b) + nextByte := make([]byte, 1) + n, err := conn.Read(nextByte) if err != nil || n != 1 { writeRedError(sshStderr, "Failed to read arg: %v", err) return 1 } - if b[0] == 0 { + if nextByte[0] == 0 { break } - arg.WriteByte(b[0]) + arg.WriteByte(nextByte[0]) } args = append(args, arg.String()) } @@ -114,16 +116,16 @@ gitEnv := make(map[string]string) for { var envLine bytes.Buffer for { - b := make([]byte, 1) - n, err := conn.Read(b) + nextByte := make([]byte, 1) + n, err := conn.Read(nextByte) if err != nil || n != 1 { writeRedError(sshStderr, "Failed to read environment variable: %v", err) return 1 } - if b[0] == 0 { + if nextByte[0] == 0 { break } - envLine.WriteByte(b[0]) + envLine.WriteByte(nextByte[0]) } if envLine.Len() == 0 { break @@ -168,10 +170,10 @@ if pushOptCount == 0 { writeRedError(sshStderr, "This repo requires contributors to be either federated or registered users. You must supply your federated user ID as a push option. For example, git push -o fedid=sr.ht:runxiyu") return 1 } - for i := range pushOptCount { - pushOpt, ok := gitEnv[fmt.Sprintf("GIT_PUSH_OPTION_%d", i)] + for pushOptIndex := range pushOptCount { + pushOpt, ok := gitEnv[fmt.Sprintf("GIT_PUSH_OPTION_%d", pushOptIndex)] if !ok { - writeRedError(sshStderr, "Failed to get push option %d", i) + writeRedError(sshStderr, "Failed to get push option %d", pushOptIndex) return 1 } if strings.HasPrefix(pushOpt, "fedid=") { @@ -194,7 +196,7 @@ } break } - if i == pushOptCount-1 { + if pushOptIndex == pushOptCount-1 { writeRedError(sshStderr, "This repo requires contributors to be either federated or registered users. You must supply your federated user ID as a push option. For example, git push -o fedid=sr.ht:runxiyu") return 1 } @@ -344,14 +346,14 @@ } func getUcred(conn net.Conn) (ucred *syscall.Ucred, err error) { unixConn := conn.(*net.UnixConn) - var fd *os.File + var unixConnFD *os.File - if fd, err = unixConn.File(); err != nil { + if unixConnFD, err = unixConn.File(); err != nil { return nil, errGetFD } - defer fd.Close() + defer unixConnFD.Close() - if ucred, err = syscall.GetsockoptUcred(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED); err != nil { + if ucred, err = syscall.GetsockoptUcred(int(unixConnFD.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED); err != nil { return nil, errGetUcred } return ucred, nil diff --git a/git_misc.go b/git_misc.go index cd2930ea456d3ec63ee23aac8deff6cb9bfed8ce..8b5dbf6528a77bbf861735619d17a79a6bbfa1ba 100644 --- a/git_misc.go +++ b/git_misc.go @@ -118,15 +118,15 @@ } func iterSeqLimit[T any](s iter.Seq[T], n uint) iter.Seq[T] { return func(yield func(T) bool) { - var i uint + var iterations uint for v := range s { - if i > n-1 { + if iterations > n-1 { return } if !yield(v) { return } - i++ + iterations++ } } } diff --git a/http_auth.go b/http_auth.go index db7df096159e90ade6e2f94ce58eab5212071516..9fb5a2e503120a4894d803fabcfc2579cb03d410 100644 --- a/http_auth.go +++ b/http_auth.go @@ -7,15 +7,15 @@ import ( "net/http" ) -func getUserFromRequest(r *http.Request) (id int, username string, err error) { +func getUserFromRequest(request *http.Request) (id int, username string, err error) { var sessionCookie *http.Cookie - if sessionCookie, err = r.Cookie("session"); err != nil { + if sessionCookie, err = request.Cookie("session"); err != nil { return } err = database.QueryRow( - r.Context(), + request.Context(), "SELECT user_id, COALESCE(username, '') FROM users u JOIN sessions s ON u.id = s.user_id WHERE s.session_id = $1;", sessionCookie.Value, ).Scan(&id, &username) diff --git a/http_handle_gc.go b/http_handle_gc.go index 5f98d0e483da93f99d7b6a654bb57bc977d91ee5..73bd2a662e5f5825eab2c7480dec284189cb66c2 100644 --- a/http_handle_gc.go +++ b/http_handle_gc.go @@ -8,7 +8,7 @@ "net/http" "runtime" ) -func httpHandleGC(w http.ResponseWriter, r *http.Request, _ map[string]any) { +func httpHandleGC(writer http.ResponseWriter, request *http.Request, _ map[string]any) { runtime.GC() - http.Redirect(w, r, "/", http.StatusSeeOther) + http.Redirect(writer, request, "/", http.StatusSeeOther) } diff --git a/http_handle_group_index.go b/http_handle_group_index.go index 27d71c52a9368e2958d890efb0dd1fe2f39980df..0667a118d8d20f1f1fb687899176bdf423597203 100644 --- a/http_handle_group_index.go +++ b/http_handle_group_index.go @@ -13,7 +13,7 @@ "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" ) -func httpHandleGroupIndex(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleGroupIndex(writer http.ResponseWriter, request *http.Request, params map[string]any) { var groupPath []string var repos []nameDesc var subgroups []nameDesc @@ -24,7 +24,7 @@ groupPath = params["group_path"].([]string) // The group itself - err = database.QueryRow(r.Context(), ` + err = database.QueryRow(request.Context(), ` WITH RECURSIVE group_path_cte AS ( SELECT id, @@ -56,44 +56,44 @@ pgtype.FlatArray[string](groupPath), ).Scan(&groupID, &groupDesc) if errors.Is(err, pgx.ErrNoRows) { - errorPage404(w, params) + errorPage404(writer, params) return } else if err != nil { - http.Error(w, "Error getting group: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting group: "+err.Error(), http.StatusInternalServerError) return } // ACL var count int - err = database.QueryRow(r.Context(), ` + err = database.QueryRow(request.Context(), ` SELECT COUNT(*) FROM user_group_roles WHERE user_id = $1 AND group_id = $2 `, params["user_id"].(int), groupID).Scan(&count) if err != nil { - http.Error(w, "Error checking access: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error checking access: "+err.Error(), http.StatusInternalServerError) return } directAccess := (count > 0) - if r.Method == http.MethodPost { + if request.Method == http.MethodPost { if !directAccess { - http.Error(w, "You do not have direct access to this group", http.StatusForbidden) + http.Error(writer, "You do not have direct access to this group", http.StatusForbidden) return } - repoName := r.FormValue("repo_name") - repoDesc := r.FormValue("repo_desc") - contribReq := r.FormValue("repo_contrib") + repoName := request.FormValue("repo_name") + repoDesc := request.FormValue("repo_desc") + contribReq := request.FormValue("repo_contrib") if repoName == "" { - http.Error(w, "Repo name is required", http.StatusBadRequest) + http.Error(writer, "Repo name is required", http.StatusBadRequest) return } var newRepoID int err := database.QueryRow( - r.Context(), + request.Context(), `INSERT INTO repos (name, description, group_id, contrib_requirements) VALUES ($1, $2, $3, $4) RETURNING id`, @@ -103,14 +103,14 @@ groupID, contribReq, ).Scan(&newRepoID) if err != nil { - http.Error(w, "Error creating repo: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error creating repo: "+err.Error(), http.StatusInternalServerError) return } filePath := filepath.Join(config.Git.RepoDir, strconv.Itoa(newRepoID)+".git") _, err = database.Exec( - r.Context(), + request.Context(), `UPDATE repos SET filesystem_path = $1 WHERE id = $2`, @@ -118,28 +118,28 @@ filePath, newRepoID, ) if err != nil { - http.Error(w, "Error updating repo path: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error updating repo path: "+err.Error(), http.StatusInternalServerError) return } if err = gitInit(filePath); err != nil { - http.Error(w, "Error initializing repo: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error initializing repo: "+err.Error(), http.StatusInternalServerError) return } - redirectUnconditionally(w, r) + redirectUnconditionally(writer, request) return } // Repos var rows pgx.Rows - rows, err = database.Query(r.Context(), ` + rows, err = database.Query(request.Context(), ` SELECT name, COALESCE(description, '') FROM repos WHERE group_id = $1 `, groupID) if err != nil { - http.Error(w, "Error getting repos: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting repos: "+err.Error(), http.StatusInternalServerError) return } defer rows.Close() @@ -147,24 +147,24 @@ 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) + http.Error(writer, "Error getting repos: "+err.Error(), http.StatusInternalServerError) return } repos = append(repos, nameDesc{name, description}) } if err = rows.Err(); err != nil { - http.Error(w, "Error getting repos: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting repos: "+err.Error(), http.StatusInternalServerError) return } // Subgroups - rows, err = database.Query(r.Context(), ` + rows, err = database.Query(request.Context(), ` SELECT name, COALESCE(description, '') FROM groups WHERE parent_group = $1 `, groupID) if err != nil { - http.Error(w, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) return } defer rows.Close() @@ -172,13 +172,13 @@ 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) + http.Error(writer, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) return } subgroups = append(subgroups, nameDesc{name, description}) } if err = rows.Err(); err != nil { - http.Error(w, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting subgroups: "+err.Error(), http.StatusInternalServerError) return } @@ -187,5 +187,5 @@ params["subgroups"] = subgroups params["description"] = groupDesc params["direct_access"] = directAccess - renderTemplate(w, "group", params) + renderTemplate(writer, "group", params) } diff --git a/http_handle_index.go b/http_handle_index.go index 360c033013e0b120291c444a7bc35ad8a75d1b67..16d343a9c70c60d4f3809575e01c0683eed9ce31 100644 --- a/http_handle_index.go +++ b/http_handle_index.go @@ -10,13 +10,13 @@ "github.com/dustin/go-humanize" ) -func httpHandleIndex(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleIndex(writer http.ResponseWriter, request *http.Request, params map[string]any) { var err error var groups []nameDesc - groups, err = queryNameDesc(r.Context(), "SELECT name, COALESCE(description, '') FROM groups WHERE parent_group IS NULL") + groups, err = queryNameDesc(request.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) + http.Error(writer, "Error querying groups: "+err.Error(), http.StatusInternalServerError) return } params["groups"] = groups @@ -25,5 +25,5 @@ // Memory currently allocated memstats := runtime.MemStats{} //exhaustruct:ignore runtime.ReadMemStats(&memstats) params["mem"] = humanize.IBytes(memstats.Alloc) - renderTemplate(w, "index", params) + renderTemplate(writer, "index", params) } diff --git a/http_handle_login.go b/http_handle_login.go index c6c1be1df4644cfe334f0f36a90f3b38abe36314..ed56e0ad4f3ef3ea2b825aa8a3b228e88b7ccbf8 100644 --- a/http_handle_login.go +++ b/http_handle_login.go @@ -15,7 +15,7 @@ "github.com/alexedwards/argon2id" "github.com/jackc/pgx/v5" ) -func httpHandleLogin(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleLogin(writer http.ResponseWriter, request *http.Request, params map[string]any) { var username, password string var userID int var passwordHash string @@ -26,46 +26,46 @@ var now time.Time var expiry time.Time var cookie http.Cookie - if r.Method != http.MethodPost { - renderTemplate(w, "login", params) + if request.Method != http.MethodPost { + renderTemplate(writer, "login", params) return } - username = r.PostFormValue("username") - password = r.PostFormValue("password") + username = request.PostFormValue("username") + password = request.PostFormValue("password") - err = database.QueryRow(r.Context(), + err = database.QueryRow(request.Context(), "SELECT id, COALESCE(password, '') FROM users WHERE username = $1", username, ).Scan(&userID, &passwordHash) if err != nil { if errors.Is(err, pgx.ErrNoRows) { params["login_error"] = "Unknown username" - renderTemplate(w, "login", params) + renderTemplate(writer, "login", params) return } - http.Error(w, "Error querying user information: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error querying user information: "+err.Error(), http.StatusInternalServerError) return } if passwordHash == "" { params["login_error"] = "User has no password" - renderTemplate(w, "login", params) + renderTemplate(writer, "login", params) return } if passwordMatches, err = argon2id.ComparePasswordAndHash(password, passwordHash); err != nil { - http.Error(w, "Error comparing password and hash: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error comparing password and hash: "+err.Error(), http.StatusInternalServerError) return } if !passwordMatches { params["login_error"] = "Invalid password" - renderTemplate(w, "login", params) + renderTemplate(writer, "login", params) return } if cookieValue, err = randomUrlsafeStr(16); err != nil { - http.Error(w, "Error getting random string: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting random string: "+err.Error(), http.StatusInternalServerError) return } @@ -82,15 +82,15 @@ Expires: expiry, Path: "/", } //exhaustruct:ignore - http.SetCookie(w, &cookie) + http.SetCookie(writer, &cookie) - _, err = database.Exec(r.Context(), "INSERT INTO sessions (user_id, session_id) VALUES ($1, $2)", userID, cookieValue) + _, err = database.Exec(request.Context(), "INSERT INTO sessions (user_id, session_id) VALUES ($1, $2)", userID, cookieValue) if err != nil { - http.Error(w, "Error inserting session: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error inserting session: "+err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, "/", http.StatusSeeOther) + http.Redirect(writer, request, "/", http.StatusSeeOther) } // randomUrlsafeStr generates a random string of the given entropic size diff --git a/http_handle_repo_commit.go b/http_handle_repo_commit.go index 94aa85d8b03c2333ded02d8b956ceedda4a46aa9..b3c2172fe74bb3b14f1a802f946e319aa063676e 100644 --- a/http_handle_repo_commit.go +++ b/http_handle_repo_commit.go @@ -29,7 +29,7 @@ Operation diff.Operation Content string } -func httpHandleRepoCommit(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleRepoCommit(writer http.ResponseWriter, request *http.Request, params map[string]any) { var repo *git.Repository var commitIDStrSpec, commitIDStrSpecNoSuffix string var commitID plumbing.Hash @@ -44,22 +44,22 @@ commitIDStrSpecNoSuffix = strings.TrimSuffix(commitIDStrSpec, ".patch") commitID = plumbing.NewHash(commitIDStrSpecNoSuffix) if commitObj, err = repo.CommitObject(commitID); err != nil { - http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) return } if commitIDStrSpecNoSuffix != commitIDStrSpec { var patchStr string if patchStr, err = fmtCommitPatch(commitObj); err != nil { - http.Error(w, "Error formatting patch: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error formatting patch: "+err.Error(), http.StatusInternalServerError) return } - fmt.Fprintln(w, patchStr) + fmt.Fprintln(writer, patchStr) return } commitIDStr = commitObj.Hash.String() if commitIDStr != commitIDStrSpec { - http.Redirect(w, r, commitIDStr, http.StatusSeeOther) + http.Redirect(writer, request, commitIDStr, http.StatusSeeOther) return } @@ -68,7 +68,7 @@ params["commit_id"] = commitIDStr parentCommitHash, patch, err = fmtCommitAsPatch(commitObj) if err != nil { - http.Error(w, "Error getting patch from commit: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting patch from commit: "+err.Error(), http.StatusInternalServerError) return } params["parent_commitHash"] = parentCommitHash.String() @@ -76,7 +76,7 @@ params["patch"] = patch params["file_patches"] = makeUsableFilePatches(patch) - renderTemplate(w, "repo_commit", params) + renderTemplate(writer, "repo_commit", params) } type fakeDiffFile struct { @@ -108,16 +108,16 @@ // TODO: Remove unnecessary context // TODO: Prepend "+"/"-"/" " instead of solely distinguishing based on color for _, filePatch := range patch.FilePatches() { - var from, to diff.File + var fromFile, toFile diff.File var ufp usableFilePatch chunks := []usableChunk{} - from, to = filePatch.Files() - if from == nil { - from = nullFakeDiffFile + fromFile, toFile = filePatch.Files() + if fromFile == nil { + fromFile = nullFakeDiffFile } - if to == nil { - to = nullFakeDiffFile + if toFile == nil { + toFile = nullFakeDiffFile } for _, chunk := range filePatch.Chunks() { var content string @@ -133,8 +133,8 @@ }) } ufp = usableFilePatch{ Chunks: chunks, - From: from, - To: to, + From: fromFile, + To: toFile, } usableFilePatches = append(usableFilePatches, ufp) } diff --git a/http_handle_repo_contrib_index.go b/http_handle_repo_contrib_index.go index 41c4d1889e50419c1be5be9ae9f0c545cc640054..af3f8b6d7c20d4464f2794c6d3c6606ae0026352 100644 --- a/http_handle_repo_contrib_index.go +++ b/http_handle_repo_contrib_index.go @@ -15,34 +15,34 @@ Title string Status string } -func httpHandleRepoContribIndex(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleRepoContribIndex(writer http.ResponseWriter, request *http.Request, params map[string]any) { var rows pgx.Rows var result []idTitleStatus var err error - if rows, err = database.Query(r.Context(), + if rows, err = database.Query(request.Context(), "SELECT id, COALESCE(title, 'Untitled'), status FROM merge_requests WHERE repo_id = $1", params["repo_id"], ); err != nil { - http.Error(w, "Error querying merge requests: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error querying merge requests: "+err.Error(), http.StatusInternalServerError) return } defer rows.Close() for rows.Next() { - var id int - var title, status string - if err = rows.Scan(&id, &title, &status); err != nil { - http.Error(w, "Error scanning merge request: "+err.Error(), http.StatusInternalServerError) + var mrID int + var mrTitle, mrStatus string + if err = rows.Scan(&mrID, &mrTitle, &mrStatus); err != nil { + http.Error(writer, "Error scanning merge request: "+err.Error(), http.StatusInternalServerError) return } - result = append(result, idTitleStatus{id, title, status}) + result = append(result, idTitleStatus{mrID, mrTitle, mrStatus}) } if err = rows.Err(); err != nil { - http.Error(w, "Error ranging over merge requests: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error ranging over merge requests: "+err.Error(), http.StatusInternalServerError) return } params["merge_requests"] = result - renderTemplate(w, "repo_contrib_index", params) + renderTemplate(writer, "repo_contrib_index", params) } diff --git a/http_handle_repo_contrib_one.go b/http_handle_repo_contrib_one.go index 74bd2ca5d96cfba20ed713a23f2452c7c9940d0a..29e2ef64f6f59c9a69a780e90a31aea0cb84ffcb 100644 --- a/http_handle_repo_contrib_one.go +++ b/http_handle_repo_contrib_one.go @@ -12,7 +12,7 @@ "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" ) -func httpHandleRepoContribOne(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleRepoContribOne(writer http.ResponseWriter, request *http.Request, params map[string]any) { var mrIDStr string var mrIDInt int var err error @@ -26,27 +26,27 @@ mrIDStr = params["mr_id"].(string) mrIDInt64, err := strconv.ParseInt(mrIDStr, 10, strconv.IntSize) if err != nil { - http.Error(w, "Merge request ID not an integer: "+err.Error(), http.StatusBadRequest) + http.Error(writer, "Merge request ID not an integer: "+err.Error(), http.StatusBadRequest) return } mrIDInt = int(mrIDInt64) - if err = database.QueryRow(r.Context(), + if err = database.QueryRow(request.Context(), "SELECT COALESCE(title, ''), status, source_ref, COALESCE(destination_branch, '') FROM merge_requests WHERE id = $1", mrIDInt, ).Scan(&title, &status, &srcRefStr, &dstBranchStr); err != nil { - http.Error(w, "Error querying merge request: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error querying merge request: "+err.Error(), http.StatusInternalServerError) return } repo = params["repo"].(*git.Repository) if srcRefHash, err = getRefHash(repo, "branch", srcRefStr); err != nil { - http.Error(w, "Error getting source ref hash: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting source ref hash: "+err.Error(), http.StatusInternalServerError) return } if srcCommit, err = repo.CommitObject(srcRefHash); err != nil { - http.Error(w, "Error getting source commit: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting source commit: "+err.Error(), http.StatusInternalServerError) return } params["source_commit"] = srcCommit @@ -58,18 +58,18 @@ } else { dstBranchHash, err = getRefHash(repo, "branch", dstBranchStr) } if err != nil { - http.Error(w, "Error getting destination branch hash: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting destination branch hash: "+err.Error(), http.StatusInternalServerError) return } if dstCommit, err = repo.CommitObject(dstBranchHash); err != nil { - http.Error(w, "Error getting destination commit: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting destination commit: "+err.Error(), http.StatusInternalServerError) return } params["destination_commit"] = dstCommit if mergeBases, err = srcCommit.MergeBase(dstCommit); err != nil { - http.Error(w, "Error getting merge base: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting merge base: "+err.Error(), http.StatusInternalServerError) return } mergeBaseCommit = mergeBases[0] @@ -77,12 +77,12 @@ params["merge_base"] = mergeBaseCommit patch, err := mergeBaseCommit.Patch(srcCommit) if err != nil { - http.Error(w, "Error getting patch: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting patch: "+err.Error(), http.StatusInternalServerError) return } params["file_patches"] = makeUsableFilePatches(patch) params["mr_title"], params["mr_status"], params["mr_source_ref"], params["mr_destination_branch"] = title, status, srcRefStr, dstBranchStr - renderTemplate(w, "repo_contrib_one", params) + renderTemplate(writer, "repo_contrib_one", params) } diff --git a/http_handle_repo_index.go b/http_handle_repo_index.go index df1ee5e8b36828523da9e8726c4f8f45ab7e664d..7dc7826dbb2cb5d61a553efbbc67949200117f4b 100644 --- a/http_handle_repo_index.go +++ b/http_handle_repo_index.go @@ -14,7 +14,7 @@ "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/storer" ) -func httpHandleRepoIndex(w http.ResponseWriter, _ *http.Request, params map[string]any) { +func httpHandleRepoIndex(writer http.ResponseWriter, _ *http.Request, params map[string]any) { var repo *git.Repository var repoName string var groupPath []string @@ -73,5 +73,5 @@ params["http_clone_url"] = genHTTPRemoteURL(groupPath, repoName) params["ssh_clone_url"] = genSSHRemoteURL(groupPath, repoName) params["notes"] = notes - renderTemplate(w, "repo_index", params) + renderTemplate(writer, "repo_index", params) } diff --git a/http_handle_repo_info.go b/http_handle_repo_info.go index 389936c32b9235e06a9e86d6f5d9d8235615a6cf..9857b773364b5325e99a395913ad2855ff10a4ea 100644 --- a/http_handle_repo_info.go +++ b/http_handle_repo_info.go @@ -12,12 +12,12 @@ "github.com/jackc/pgx/v5/pgtype" ) -func httpHandleRepoInfo(w http.ResponseWriter, r *http.Request, params map[string]any) (err error) { +func httpHandleRepoInfo(writer http.ResponseWriter, request *http.Request, params map[string]any) (err error) { groupPath := params["group_path"].([]string) repoName := params["repo_name"].(string) var repoPath string - if err := database.QueryRow(r.Context(), ` + if err := database.QueryRow(request.Context(), ` WITH RECURSIVE group_path_cte AS ( -- Start: match the first name in the path where parent_group IS NULL SELECT @@ -54,8 +54,8 @@ ).Scan(&repoPath); err != nil { return err } - w.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement") - w.WriteHeader(http.StatusOK) + writer.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement") + writer.WriteHeader(http.StatusOK) cmd := exec.Command("git", "upload-pack", "--stateless-rpc", "--advertise-refs", repoPath) stdout, err := cmd.StdoutPipe() @@ -71,15 +71,15 @@ if err = cmd.Start(); err != nil { return err } - if err = packLine(w, "# service=git-upload-pack\n"); err != nil { + if err = packLine(writer, "# service=git-upload-pack\n"); err != nil { return err } - if err = packFlush(w); err != nil { + if err = packFlush(writer); err != nil { return } - if _, err = io.Copy(w, stdout); err != nil { + if _, err = io.Copy(writer, stdout); err != nil { return err } diff --git a/http_handle_repo_log.go b/http_handle_repo_log.go index 2dec6bd8bf49a9274cbddf9a5813a699cf88b694..8d54d2896157929d9490a60779a7d0f8f0bf71c5 100644 --- a/http_handle_repo_log.go +++ b/http_handle_repo_log.go @@ -12,7 +12,7 @@ "github.com/go-git/go-git/v5/plumbing/object" ) // TODO: I probably shouldn't include *all* commits here... -func httpHandleRepoLog(w http.ResponseWriter, _ *http.Request, params map[string]any) { +func httpHandleRepoLog(writer http.ResponseWriter, _ *http.Request, params map[string]any) { var repo *git.Repository var refHash plumbing.Hash var err error @@ -21,15 +21,15 @@ repo = params["repo"].(*git.Repository) if refHash, err = getRefHash(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil { - http.Error(w, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) return } if commits, err = getRecentCommits(repo, refHash, -1); err != nil { - http.Error(w, "Error getting recent commits: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting recent commits: "+err.Error(), http.StatusInternalServerError) return } params["commits"] = commits - renderTemplate(w, "repo_log", params) + renderTemplate(writer, "repo_log", params) } diff --git a/http_handle_repo_raw.go b/http_handle_repo_raw.go index 8664ceb9500b71b65c8682c2af1e237b4a08f140..db20791265eacc2df601cb73c2f82377fc748aab 100644 --- a/http_handle_repo_raw.go +++ b/http_handle_repo_raw.go @@ -13,7 +13,7 @@ "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" ) -func httpHandleRepoRaw(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleRepoRaw(writer http.ResponseWriter, request *http.Request, params map[string]any) { var rawPathSpec, pathSpec string var repo *git.Repository var refHash plumbing.Hash @@ -26,16 +26,16 @@ repo, pathSpec = params["repo"].(*git.Repository), strings.TrimSuffix(rawPathSpec, "/") params["path_spec"] = pathSpec if refHash, err = getRefHash(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil { - http.Error(w, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) return } if commitObj, err = repo.CommitObject(refHash); err != nil { - http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) return } if tree, err = commitObj.Tree(); err != nil { - http.Error(w, "Error getting file tree: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting file tree: "+err.Error(), http.StatusInternalServerError) return } @@ -47,26 +47,26 @@ if target, err = tree.Tree(pathSpec); err != nil { var file *object.File var fileContent string if file, err = tree.File(pathSpec); err != nil { - http.Error(w, "Error retrieving path: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error retrieving path: "+err.Error(), http.StatusInternalServerError) return } - if redirectNoDir(w, r) { + if redirectNoDir(writer, request) { return } if fileContent, err = file.Contents(); err != nil { - http.Error(w, "Error reading file: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error reading file: "+err.Error(), http.StatusInternalServerError) return } - fmt.Fprint(w, fileContent) + fmt.Fprint(writer, fileContent) return } } - if redirectDir(w, r) { + if redirectDir(writer, request) { return } params["files"] = makeDisplayTree(target) - renderTemplate(w, "repo_raw_dir", params) + renderTemplate(writer, "repo_raw_dir", params) } diff --git a/http_handle_repo_tree.go b/http_handle_repo_tree.go index 36eefc03c261bdc7a0721fba9d17e98183f2d029..1238fd5955f5e33bb859c906ec3c1f09a9f634ff 100644 --- a/http_handle_repo_tree.go +++ b/http_handle_repo_tree.go @@ -19,7 +19,7 @@ "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" ) -func httpHandleRepoTree(w http.ResponseWriter, r *http.Request, params map[string]any) { +func httpHandleRepoTree(writer http.ResponseWriter, request *http.Request, params map[string]any) { var rawPathSpec, pathSpec string var repo *git.Repository var refHash plumbing.Hash @@ -32,15 +32,15 @@ repo, pathSpec = params["repo"].(*git.Repository), strings.TrimSuffix(rawPathSpec, "/") params["path_spec"] = pathSpec if refHash, err = getRefHash(repo, params["ref_type"].(string), params["ref_name"].(string)); err != nil { - http.Error(w, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting ref hash: "+err.Error(), http.StatusInternalServerError) return } if commitObject, err = repo.CommitObject(refHash); err != nil { - http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) return } if tree, err = commitObject.Tree(); err != nil { - http.Error(w, "Error getting file tree: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting file tree: "+err.Error(), http.StatusInternalServerError) return } @@ -58,14 +58,14 @@ var formatter *chromaHTML.Formatter var formattedHTML template.HTML if file, err = tree.File(pathSpec); err != nil { - http.Error(w, "Error retrieving path: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error retrieving path: "+err.Error(), http.StatusInternalServerError) return } - if redirectNoDir(w, r) { + if redirectNoDir(writer, request) { return } if fileContent, err = file.Contents(); err != nil { - http.Error(w, "Error reading file: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error reading file: "+err.Error(), http.StatusInternalServerError) return } lexer = chromaLexers.Match(pathSpec) @@ -73,31 +73,31 @@ if lexer == nil { lexer = chromaLexers.Fallback } if iterator, err = lexer.Tokenise(nil, fileContent); err != nil { - http.Error(w, "Error tokenizing code: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error tokenizing code: "+err.Error(), http.StatusInternalServerError) return } var formattedHTMLStr bytes.Buffer style = chromaStyles.Get("autumn") formatter = chromaHTML.New(chromaHTML.WithClasses(true), chromaHTML.TabWidth(8)) if err = formatter.Format(&formattedHTMLStr, style, iterator); err != nil { - http.Error(w, "Error formatting code: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error formatting code: "+err.Error(), http.StatusInternalServerError) return } formattedHTML = template.HTML(formattedHTMLStr.Bytes()) //#nosec G203 params["file_contents"] = formattedHTML - renderTemplate(w, "repo_tree_file", params) + renderTemplate(writer, "repo_tree_file", params) return } } if len(rawPathSpec) != 0 && rawPathSpec[len(rawPathSpec)-1] != '/' { - http.Redirect(w, r, path.Base(pathSpec)+"/", http.StatusSeeOther) + http.Redirect(writer, request, path.Base(pathSpec)+"/", http.StatusSeeOther) return } params["readme_filename"], params["readme"] = renderReadmeAtTree(target) params["files"] = makeDisplayTree(target) - renderTemplate(w, "repo_tree_dir", params) + renderTemplate(writer, "repo_tree_dir", params) } diff --git a/http_handle_repo_upload_pack.go b/http_handle_repo_upload_pack.go index a88297d26441d2d6e4dbd79d6ed1f29a79750d78..a5a0036e0fc62e8e538b0efaf92d11a5c5384dca 100644 --- a/http_handle_repo_upload_pack.go +++ b/http_handle_repo_upload_pack.go @@ -12,7 +12,7 @@ "github.com/jackc/pgx/v5/pgtype" ) -func httpHandleUploadPack(w http.ResponseWriter, r *http.Request, params map[string]any) (err error) { +func httpHandleUploadPack(writer http.ResponseWriter, request *http.Request, params map[string]any) (err error) { var groupPath []string var repoName string var repoPath string @@ -22,7 +22,7 @@ var cmd *exec.Cmd groupPath, repoName = params["group_path"].([]string), params["repo_name"].(string) - if err := database.QueryRow(r.Context(), ` + if err := database.QueryRow(request.Context(), ` WITH RECURSIVE group_path_cte AS ( -- Start: match the first name in the path where parent_group IS NULL SELECT @@ -59,10 +59,10 @@ ).Scan(&repoPath); 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) + writer.Header().Set("Content-Type", "application/x-git-upload-pack-result") + writer.Header().Set("Connection", "Keep-Alive") + writer.Header().Set("Transfer-Encoding", "chunked") + writer.WriteHeader(http.StatusOK) cmd = exec.Command("git", "upload-pack", "--stateless-rpc", repoPath) cmd.Env = append(os.Environ(), "LINDENII_FORGE_HOOKS_SOCKET_PATH="+config.Hooks.Socket) @@ -85,7 +85,7 @@ if err = cmd.Start(); err != nil { return err } - if _, err = io.Copy(stdin, r.Body); err != nil { + if _, err = io.Copy(stdin, request.Body); err != nil { return err } @@ -93,7 +93,7 @@ if err = stdin.Close(); err != nil { return err } - if _, err = io.Copy(w, stdout); err != nil { + if _, err = io.Copy(writer, stdout); err != nil { return err } diff --git a/http_handle_users.go b/http_handle_users.go index df0c99ac58f88e8a4105fabede587a7c66e70006..2570de7323b684646ae6e09abd6f17105aeb3485 100644 --- a/http_handle_users.go +++ b/http_handle_users.go @@ -7,6 +7,6 @@ import ( "net/http" ) -func httpHandleUsers(w http.ResponseWriter, _ *http.Request, _ map[string]any) { - http.Error(w, "Not implemented", http.StatusNotImplemented) +func httpHandleUsers(writer http.ResponseWriter, _ *http.Request, _ map[string]any) { + http.Error(writer, "Not implemented", http.StatusNotImplemented) } diff --git a/http_server.go b/http_server.go index 983f579a12567e398180c122294d66bd1fd993c7..10b7d0382a562f2661176b2ab420dae53b5d3001 100644 --- a/http_server.go +++ b/http_server.go @@ -15,16 +15,16 @@ ) type forgeHTTPRouter struct{} -func (router *forgeHTTPRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { - clog.Info("Incoming HTTP: " + r.RemoteAddr + " " + r.Method + " " + r.RequestURI) +func (router *forgeHTTPRouter) ServeHTTP(writer http.ResponseWriter, request *http.Request) { + clog.Info("Incoming HTTP: " + request.RemoteAddr + " " + request.Method + " " + request.RequestURI) var segments []string var err error var sepIndex int params := make(map[string]any) - if segments, _, err = parseReqURI(r.RequestURI); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) + if segments, _, err = parseReqURI(request.RequestURI); err != nil { + http.Error(writer, err.Error(), http.StatusBadRequest) return } if segments[len(segments)-1] == "" { @@ -34,10 +34,10 @@ params["url_segments"] = segments params["global"] = globalData var userID int // 0 for none - userID, params["username"], err = getUserFromRequest(r) + userID, params["username"], err = getUserFromRequest(request) params["user_id"] = userID if err != nil && !errors.Is(err, http.ErrNoCookie) && !errors.Is(err, pgx.ErrNoRows) { - http.Error(w, "Error getting user info from request: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error getting user info from request: "+err.Error(), http.StatusInternalServerError) return } @@ -48,24 +48,24 @@ params["user_id_string"] = strconv.Itoa(userID) } if len(segments) == 0 { - httpHandleIndex(w, r, params) + httpHandleIndex(writer, request, params) return } if segments[0] == ":" { if len(segments) < 2 { - errorPage404(w, params) + errorPage404(writer, params) return - } else if len(segments) == 2 && redirectDir(w, r) { + } else if len(segments) == 2 && redirectDir(writer, request) { return } switch segments[1] { case "static": - staticHandler.ServeHTTP(w, r) + staticHandler.ServeHTTP(writer, request) return case "source": - sourceHandler.ServeHTTP(w, r) + sourceHandler.ServeHTTP(writer, request) return } } @@ -73,16 +73,16 @@ if segments[0] == ":" { switch segments[1] { case "login": - httpHandleLogin(w, r, params) + httpHandleLogin(writer, request, params) return case "users": - httpHandleUsers(w, r, params) + httpHandleUsers(writer, request, params) return case "gc": - httpHandleGC(w, r, params) + httpHandleGC(writer, request, params) return default: - errorPage404(w, params) + errorPage404(writer, params) return } } @@ -110,15 +110,15 @@ params["group_path"] = groupPath switch { case sepIndex == -1: - if redirectDir(w, r) { + if redirectDir(writer, request) { return } - httpHandleGroupIndex(w, r, params) + httpHandleGroupIndex(writer, request, params) case len(segments) == sepIndex+1: - errorPage404(w, params) + errorPage404(writer, params) return case len(segments) == sepIndex+2: - errorPage404(w, params) + errorPage404(writer, params) return default: moduleType = segments[sepIndex+1] @@ -130,39 +130,39 @@ if len(segments) > sepIndex+3 { switch segments[sepIndex+3] { case "info": - if err = httpHandleRepoInfo(w, r, params); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + if err = httpHandleRepoInfo(writer, request, params); err != nil { + http.Error(writer, err.Error(), http.StatusInternalServerError) } return case "git-upload-pack": - if err = httpHandleUploadPack(w, r, params); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + if err = httpHandleUploadPack(writer, request, params); err != nil { + http.Error(writer, err.Error(), http.StatusInternalServerError) } return } } - if params["ref_type"], params["ref_name"], err = getParamRefTypeName(r); err != nil { + if params["ref_type"], params["ref_name"], err = getParamRefTypeName(request); err != nil { if errors.Is(err, errNoRefSpec) { params["ref_type"] = "" } else { - http.Error(w, "Error querying ref type: "+err.Error(), http.StatusInternalServerError) + http.Error(writer, "Error querying ref type: "+err.Error(), http.StatusInternalServerError) return } } // TODO: subgroups - if params["repo"], params["repo_description"], params["repo_id"], err = openRepo(r.Context(), groupPath, moduleName); err != nil { - http.Error(w, "Error opening repo: "+err.Error(), http.StatusInternalServerError) + if params["repo"], params["repo_description"], params["repo_id"], err = openRepo(request.Context(), groupPath, moduleName); err != nil { + http.Error(writer, "Error opening repo: "+err.Error(), http.StatusInternalServerError) return } if len(segments) == sepIndex+3 { - if redirectDir(w, r) { + if redirectDir(writer, request) { return } - httpHandleRepoIndex(w, r, params) + httpHandleRepoIndex(writer, request, params) return } @@ -170,58 +170,58 @@ repoFeature := segments[sepIndex+3] switch repoFeature { case "tree": if anyContain(segments[sepIndex+4:], "/") { - errorPage400(w, params, "Repo tree paths may not contain slashes in any segments") + errorPage400(writer, params, "Repo tree paths may not contain slashes in any segments") return } params["rest"] = strings.Join(segments[sepIndex+4:], "/") - if len(segments) < sepIndex+5 && redirectDir(w, r) { + if len(segments) < sepIndex+5 && redirectDir(writer, request) { return } - httpHandleRepoTree(w, r, params) + httpHandleRepoTree(writer, request, params) case "raw": if anyContain(segments[sepIndex+4:], "/") { - errorPage400(w, params, "Repo tree paths may not contain slashes in any segments") + errorPage400(writer, params, "Repo tree paths may not contain slashes in any segments") return } params["rest"] = strings.Join(segments[sepIndex+4:], "/") - if len(segments) < sepIndex+5 && redirectDir(w, r) { + if len(segments) < sepIndex+5 && redirectDir(writer, request) { return } - httpHandleRepoRaw(w, r, params) + httpHandleRepoRaw(writer, request, params) case "log": if len(segments) > sepIndex+4 { - http.Error(w, "Too many parameters", http.StatusBadRequest) + http.Error(writer, "Too many parameters", http.StatusBadRequest) return } - if redirectDir(w, r) { + if redirectDir(writer, request) { return } - httpHandleRepoLog(w, r, params) + httpHandleRepoLog(writer, request, params) case "commit": - if redirectNoDir(w, r) { + if redirectNoDir(writer, request) { return } params["commit_id"] = segments[sepIndex+4] - httpHandleRepoCommit(w, r, params) + httpHandleRepoCommit(writer, request, params) case "contrib": - if redirectDir(w, r) { + if redirectDir(writer, request) { return } switch len(segments) { case sepIndex + 4: - httpHandleRepoContribIndex(w, r, params) + httpHandleRepoContribIndex(writer, request, params) case sepIndex + 5: params["mr_id"] = segments[sepIndex+4] - httpHandleRepoContribOne(w, r, params) + httpHandleRepoContribOne(writer, request, params) default: - http.Error(w, "Too many parameters", http.StatusBadRequest) + http.Error(writer, "Too many parameters", http.StatusBadRequest) } default: - errorPage404(w, params) + errorPage404(writer, params) return } default: - errorPage404(w, params) + errorPage404(writer, params) return } } diff --git a/irc.go b/irc.go index 4ca34d42b00deea48f72fb9be535035d15b40763..c6fe3ad2b4f63532458eeffa198c56520653acaf 100644 --- a/irc.go +++ b/irc.go @@ -100,20 +100,20 @@ for { select { case err = <-readLoopError: return err - case s := <-ircSendBuffered: - _, err = logAndWriteLn(s) + case line := <-ircSendBuffered: + _, err = logAndWriteLn(line) if err != nil { select { - case ircSendBuffered <- s: + case ircSendBuffered <- line: default: - clog.Error("unable to requeue IRC message: " + s) + clog.Error("unable to requeue IRC message: " + line) } writeLoopAbort <- struct{}{} return err } - case se := <-ircSendDirectChan: - _, err = logAndWriteLn(se.content) - se.errorBack <- err + case lineErrorBack := <-ircSendDirectChan: + _, err = logAndWriteLn(lineErrorBack.content) + lineErrorBack.errorBack <- err if err != nil { writeLoopAbort <- struct{}{} return err diff --git a/resources.go b/resources.go index dcfc2a56277a06dc54a691588b5f58fa672b0ea4..18f9849b7964efeb91bebef63cc4800f269483f7 100644 --- a/resources.go +++ b/resources.go @@ -36,9 +36,12 @@ var templates *template.Template func loadTemplates() (err error) { - m := minify.New() - minifier := html.Minifier{TemplateDelims: [2]string{"{{", "}}"}, KeepDefaultAttrVals: true} //exhaustruct:ignore - m.Add("text/html", &minifier) + minifier := minify.New() + minifierOptions := html.Minifier{ + TemplateDelims: [2]string{"{{", "}}"}, + KeepDefaultAttrVals: true, + } //exhaustruct:ignore + minifier.Add("text/html", &minifierOptions) templates = template.New("templates").Funcs(template.FuncMap{ "first_line": firstLine, @@ -58,7 +61,7 @@ if err != nil { return err } - minified, err := m.Bytes("text/html", content) + minified, err := minifier.Bytes("text/html", content) if err != nil { return err } diff --git a/url.go b/url.go index 57cb196bc554af149c11b668baf2f4fa4ac580d3..a981a92c0ad556960739a13aa9bcb2f01d241c9d 100644 --- a/url.go +++ b/url.go @@ -15,15 +15,15 @@ errDupRefSpec = errors.New("duplicate ref spec") errNoRefSpec = errors.New("no ref spec") ) -func getParamRefTypeName(r *http.Request) (retRefType, retRefName string, err error) { - qr := r.URL.RawQuery - q, err := url.ParseQuery(qr) +func getParamRefTypeName(request *http.Request) (retRefType, retRefName string, err error) { + rawQuery := request.URL.RawQuery + queryValues, err := url.ParseQuery(rawQuery) if err != nil { return } done := false for _, refType := range []string{"commit", "branch", "tag"} { - refName, ok := q[refType] + refName, ok := queryValues[refType] if ok { if done { err = errDupRefSpec @@ -60,8 +60,8 @@ params, err = url.ParseQuery(paramsStr) return } -func redirectDir(w http.ResponseWriter, r *http.Request) bool { - requestURI := r.RequestURI +func redirectDir(writer http.ResponseWriter, request *http.Request) bool { + requestURI := request.RequestURI pathEnd := strings.IndexAny(requestURI, "?#") var path, rest string @@ -73,14 +73,14 @@ rest = requestURI[pathEnd:] } if !strings.HasSuffix(path, "/") { - http.Redirect(w, r, path+"/"+rest, http.StatusSeeOther) + http.Redirect(writer, request, path+"/"+rest, http.StatusSeeOther) return true } return false } -func redirectNoDir(w http.ResponseWriter, r *http.Request) bool { - requestURI := r.RequestURI +func redirectNoDir(writer http.ResponseWriter, request *http.Request) bool { + requestURI := request.RequestURI pathEnd := strings.IndexAny(requestURI, "?#") var path, rest string @@ -92,14 +92,14 @@ rest = requestURI[pathEnd:] } if strings.HasSuffix(path, "/") { - http.Redirect(w, r, strings.TrimSuffix(path, "/")+rest, http.StatusSeeOther) + http.Redirect(writer, request, strings.TrimSuffix(path, "/")+rest, http.StatusSeeOther) return true } return false } -func redirectUnconditionally(w http.ResponseWriter, r *http.Request) { - requestURI := r.RequestURI +func redirectUnconditionally(writer http.ResponseWriter, request *http.Request) { + requestURI := request.RequestURI pathEnd := strings.IndexAny(requestURI, "?#") var path, rest string @@ -110,7 +110,7 @@ path = requestURI[:pathEnd] rest = requestURI[pathEnd:] } - http.Redirect(w, r, path+rest, http.StatusSeeOther) + http.Redirect(writer, request, path+rest, http.StatusSeeOther) } func segmentsToURL(segments []string) string { diff --git a/users.go b/users.go index f8dae4be106dfacbeab39d5a03fa0539c62636bd..47375bea3e8367d076299b2dde452250e8ea5c4a 100644 --- a/users.go +++ b/users.go @@ -10,23 +10,23 @@ "github.com/jackc/pgx/v5" ) func addUserSSH(ctx context.Context, pubkey string) (userID int, err error) { - var tx pgx.Tx + var txn pgx.Tx - if tx, err = database.Begin(ctx); err != nil { + if txn, err = database.Begin(ctx); err != nil { return } defer func() { - _ = tx.Rollback(ctx) + _ = txn.Rollback(ctx) }() - if err = tx.QueryRow(ctx, `INSERT INTO users (type) VALUES ('pubkey_only') RETURNING id`).Scan(&userID); err != nil { + if err = txn.QueryRow(ctx, `INSERT INTO users (type) VALUES ('pubkey_only') RETURNING id`).Scan(&userID); err != nil { return } - if _, err = tx.Exec(ctx, `INSERT INTO ssh_public_keys (key_string, user_id) VALUES ($1, $2)`, pubkey, userID); err != nil { + if _, err = txn.Exec(ctx, `INSERT INTO ssh_public_keys (key_string, user_id) VALUES ($1, $2)`, pubkey, userID); err != nil { return } - err = tx.Commit(ctx) + err = txn.Commit(ctx) return } -- 2.48.1