ronantakizawa/codereview-bench huggingface dataset:
Repository: go-gitea/gitea
File: services/repository/delete.go (Go)

Code before:
	if repo.NumForks > 0 {
		if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
			log.Error("reset 'fork_id' and 'is_fork': %v", err)
		}
	}

	// Get all attachments with both issue_id and release_id are zero
	var newAttachments []*repo_model.Attachment
	if err := sess.Where(builder.Eq{
		"repo_id":    repo.ID,
		"issue_id":   0,
		"release_id": 0,
	}).Find(&newAttachments); err != nil {
		return err
	}

	newAttachmentPaths := make([]string, 0, len(newAttachments))
	for _, attach := range newAttachments {
		newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath())
	}

	if _, err := sess.Where("repo_id=?", repo.ID).Delete(new(repo_model.Attachment)); err != nil {
		return err
	}

	// update packages linked to this repository
	if err = packages_model.UnlinkRepositoryFromAllPackages(ctx, repoID); err != nil {
		return err
	}

	if err = committer.Commit(); err != nil {
		return err
	}

	committer.Close()

	if needRewriteKeysFile {
		if err := asymkey_service.RewriteAllPublicKeys(ctx); err != nil {
			log.Error("RewriteAllPublicKeys failed: %v", err)
		}
	}

	// We should always delete the files after the database transaction succeed. If
	// we delete the file but the database rollback, the repository will be broken.

	// Remove repository files.
	repoPath := repo.RepoPath()
	system_model.RemoveAllWithNotice(ctx, "Delete repository files", repoPath)

	// Remove wiki files
	if repo.HasWiki() {

Review comment (suggestion):
```suggestion
	// unlink packages linked to this repository
```

Code after:
	if repo.NumForks > 0 {
		if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
			log.Error("reset 'fork_id' and 'is_fork': %v", err)
		}
	}

	// Get all attachments with both issue_id and release_id are zero
	var newAttachments []*repo_model.Attachment
	if err := sess.Where(builder.Eq{
		"repo_id":    repo.ID,
		"issue_id":   0,
		"release_id": 0,
	}).Find(&newAttachments); err != nil {
		return err
	}

	newAttachmentPaths := make([]string, 0, len(newAttachments))
	for _, attach := range newAttachments {
		newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath())
	}

	if _, err := sess.Where("repo_id=?", repo.ID).Delete(new(repo_model.Attachment)); err != nil {
		return err
	}

	// unlink packages linked to this repository
	if err = packages_model.UnlinkRepositoryFromAllPackages(ctx, repoID); err != nil {
		return err
	}

	if err = committer.Commit(); err != nil {
		return err
	}

	committer.Close()

	if needRewriteKeysFile {
		if err := asymkey_service.RewriteAllPublicKeys(ctx); err != nil {
			log.Error("RewriteAllPublicKeys failed: %v", err)
		}
	}

	// We should always delete the files after the database transaction succeed. If
	// we delete the file but the database rollback, the repository will be broken.

	// Remove repository files.
	repoPath := repo.RepoPath()
	system_model.RemoveAllWithNotice(ctx, "Delete repository files", repoPath)

	// Remove wiki files
	if repo.HasWiki() {
Repository: go-gitea/gitea
File: services/issue/pull.go (Go)

Code before:
		return nil, nil
	}
	if err := pr.LoadHeadRepo(ctx); err != nil {
		return nil, err
	}
	if err := pr.LoadBaseRepo(ctx); err != nil {
		return nil, err
	}

	if pr.BaseRepo.IsFork {
		return nil, nil
	}

	repo, err := gitrepo.OpenRepository(ctx, pr.BaseRepo)
	if err != nil {
		return nil, err
	}
	defer repo.Close()

	commit, err := repo.GetBranchCommit(pr.BaseRepo.DefaultBranch)
	if err != nil {
		return nil, err
	}

	var data string
	files := []string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"}
	for _, file := range files {
		if blob, err := commit.GetBlobByPath(file); err == nil {
			data, err = blob.GetBlobContent(setting.UI.MaxDisplayFileSize)
			if err == nil {
				break
			}
		}
	}

	rules, _ := issues_model.GetCodeOwnersFromContent(ctx, data)

	// get the mergebase
	mergeBase, err := getMergeBase(repo, pr, git.BranchPrefix+pr.BaseBranch, pr.GetGitRefName())
	if err != nil {
		return nil, err
	}

	// https://github.com/go-gitea/gitea/issues/29763, we need to get the files changed
	// between the merge base and the head commit but not the base branch and the head commit
	changedFiles, err := repo.GetFilesChangedBetween(mergeBase, pr.GetGitRefName())
	if err != nil {
		return nil, err
	}

	uniqUsers := make(map[int64]*user_model.User)

Review comment (refactor):
we duplicate same info everywhere. maybe we should use single variable for this?

https://github.com/go-gitea/gitea/blob/aba96f65cd687868c6eff5a079cfc7b25740642d/routers/web/repo/view_file.go#L81-L84

https://github.com/go-gitea/gitea/blob/aba96f65cd687868c6eff5a079cfc7b25740642d/services/issue/pull.go#L43-L45

Code after:

func PullRequestCodeOwnersReview(ctx context.Context, pr *issues_model.PullRequest) ([]*ReviewRequestNotifier, error) {
	return PullRequestCodeOwnersReviewSpecialCommits(ctx, pr, "", "") // no commit is provided, then it uses PR's base&head branch
}

func PullRequestCodeOwnersReviewSpecialCommits(ctx context.Context, pr *issues_model.PullRequest, startCommitID, endCommitID string) ([]*ReviewRequestNotifier, error) {
	if err := pr.LoadIssue(ctx); err != nil {
		return nil, err
	}
	issue := pr.Issue
	if pr.IsWorkInProgress(ctx) {
		return nil, nil
	}
	if err := pr.LoadHeadRepo(ctx); err != nil {
		return nil, err
	}
	if err := pr.LoadBaseRepo(ctx); err != nil {
		return nil, err
	}
	pr.Issue.Repo = pr.BaseRepo

	if pr.BaseRepo.IsFork {
		return nil, nil
	}

	repo, err := gitrepo.OpenRepository(ctx, pr.BaseRepo)
	if err != nil {
		return nil, err
	}
	defer repo.Close()

	commit, err := repo.GetBranchCommit(pr.BaseRepo.DefaultBranch)
	if err != nil {
		return nil, err
	}

	var data string
	for _, file := range codeOwnerFiles {
		if blob, err := commit.GetBlobByPath(file); err == nil {
			data, err = blob.GetBlobContent(setting.UI.MaxDisplayFileSize)
			if err == nil {
				break
			}
		}
	}
	if data == "" {
		return nil, nil
	}

	rules, _ := issues_model.GetCodeOwnersFromContent(ctx, data)
	if len(rules) == 0 {
Repository: go-gitea/gitea
File: services/issue/pull.go (Go)

Code before:
	}
	defer func() {
		if err := repo.RemoveRemote(tmpRemote); err != nil {
			log.Error("getMergeBase: RemoveRemote: %v", err)
		}
	}()

	mergeBase, _, err := repo.GetMergeBase(tmpRemote, baseBranch, headBranch)
	return mergeBase, err
}

type ReviewRequestNotifier struct {
	Comment    *issues_model.Comment
	IsAdd      bool
	Reviewer   *user_model.User
	ReviewTeam *org_model.Team
}

var codeOwnerFiles = []string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"}

func IsCodeOwnerFile(f string) bool {
	return slices.Contains(codeOwnerFiles, f)
}

func PullRequestCodeOwnersReview(ctx context.Context, pr *issues_model.PullRequest) ([]*ReviewRequestNotifier, error) {
	return PullRequestCodeOwnersReviewSpecialCommits(ctx, pr, "", "")
}

func PullRequestCodeOwnersReviewSpecialCommits(ctx context.Context, pr *issues_model.PullRequest, startCommitID, endCommitID string) ([]*ReviewRequestNotifier, error) {
	if err := pr.LoadIssue(ctx); err != nil {
		return nil, err
	}
	issue := pr.Issue
	if pr.IsWorkInProgress(ctx) {
		return nil, nil
	}
	if err := pr.LoadHeadRepo(ctx); err != nil {
		return nil, err
	}
	if err := pr.LoadBaseRepo(ctx); err != nil {
		return nil, err
	}
	pr.Issue.Repo = pr.BaseRepo

	if pr.BaseRepo.IsFork {
		return nil, nil
	}

	repo, err := gitrepo.OpenRepository(ctx, pr.BaseRepo)
	if err != nil {
		return nil, err

Review comment (suggestion):
```suggestion
	return PullRequestCodeOwnersReviewSpecialCommits(ctx, pr, "", "") // no commit is provided, then it uses PR's base&head branch
```

Code after:
	}
	defer func() {
		if err := repo.RemoveRemote(tmpRemote); err != nil {
			log.Error("getMergeBase: RemoveRemote: %v", err)
		}
	}()

	mergeBase, _, err := repo.GetMergeBase(tmpRemote, baseBranch, headBranch)
	return mergeBase, err
}

type ReviewRequestNotifier struct {
	Comment    *issues_model.Comment
	IsAdd      bool
	Reviewer   *user_model.User
	ReviewTeam *org_model.Team
}

var codeOwnerFiles = []string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"}

func IsCodeOwnerFile(f string) bool {
	return slices.Contains(codeOwnerFiles, f)
}

func PullRequestCodeOwnersReview(ctx context.Context, pr *issues_model.PullRequest) ([]*ReviewRequestNotifier, error) {
	return PullRequestCodeOwnersReviewSpecialCommits(ctx, pr, "", "") // no commit is provided, then it uses PR's base&head branch
}

func PullRequestCodeOwnersReviewSpecialCommits(ctx context.Context, pr *issues_model.PullRequest, startCommitID, endCommitID string) ([]*ReviewRequestNotifier, error) {
	if err := pr.LoadIssue(ctx); err != nil {
		return nil, err
	}
	issue := pr.Issue
	if pr.IsWorkInProgress(ctx) {
		return nil, nil
	}
	if err := pr.LoadHeadRepo(ctx); err != nil {
		return nil, err
	}
	if err := pr.LoadBaseRepo(ctx); err != nil {
		return nil, err
	}
	pr.Issue.Repo = pr.BaseRepo

	if pr.BaseRepo.IsFork {
		return nil, nil
	}

	repo, err := gitrepo.OpenRepository(ctx, pr.BaseRepo)
	if err != nil {
		return nil, err
Repository: go-gitea/gitea
File: web_src/js/index.ts (TypeScript)

Code before:

// Start performance trace by accessing a URL by "https://localhost/?_ui_performance_trace=1" or "https://localhost/?key=value&_ui_performance_trace=1"
// It is a quick check, no side effect so no need to do slow URL parsing.
const traceInitPerformance = !window.location.search.includes('_ui_performance_trace=1') ? null : new class {
  results: {name: string, dur: number}[] = [];
  recordCall(name: string, func: ()=>void) {
    const start = performance.now();
    func();
    this.results.push({name, dur: performance.now() - start});
  }
  printResults() {
    this.results = this.results.sort((a, b) => b.dur - a.dur);
    for (let i = 0; i < 20 && i < this.results.length; i++) {
      // eslint-disable-next-line no-console
      console.log(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
    }
  }
}();

function callInitFunctions(functions: (() => any)[]) {
  if (traceInitPerformance) {
    for (const func of functions) traceInitPerformance.recordCall(func.name, func);
  } else {
    for (const func of functions) func();
  }
}

onDomReady(() => {
  const initStartTime = performance.now();
  callInitFunctions([
    initGlobalDropdown,
    initGlobalTabularMenu,
    initGlobalFetchAction,
    initGlobalTooltips,
    initGlobalButtonClickOnEnter,
    initGlobalButtons,
    initGlobalCopyToClipboardListener,
    initGlobalEnterQuickSubmit,
    initGlobalFormDirtyLeaveConfirm,
    initGlobalComboMarkdownEditor,
    initGlobalDeleteButton,
    initGlobalInput,

    initCommonOrganization,
    initCommonIssueListQuickGoto,

    initCompSearchUserBox,
    initCompWebHookEditor,

    initInstall,


Review comment (suggestion):
Can these functions be moved out of `index.ts` to like `modules/init.ts`? I prefer index.ts to be kept clean and only call the inits.

Code after:
initSubmitEventPolyfill();

onDomReady(() => {
  const initStartTime = performance.now();
  const initPerformanceTracer = callInitFunctions([
    initGlobalDropdown,
    initGlobalTabularMenu,
    initGlobalFetchAction,
    initGlobalTooltips,
    initGlobalButtonClickOnEnter,
    initGlobalButtons,
    initGlobalCopyToClipboardListener,
    initGlobalEnterQuickSubmit,
    initGlobalFormDirtyLeaveConfirm,
    initGlobalComboMarkdownEditor,
    initGlobalDeleteButton,
    initGlobalInput,

    initCommonOrganization,
    initCommonIssueListQuickGoto,

    initCompSearchUserBox,
    initCompWebHookEditor,

    initInstall,

    initHeadNavbarContentToggle,
    initFootLanguageMenu,

    initCommentContent,
    initContextPopups,
    initHeatmap,
    initImageDiff,
    initMarkupAnchors,
    initMarkupContent,
    initSshKeyFormParser,
    initStopwatch,
    initTableSort,
    initFindFileInRepo,
    initCopyContent,

    initAdminCommon,
    initAdminUserListSearchForm,
    initAdminConfigs,
    initAdminSelfCheck,

    initDashboardRepoList,

    initNotificationCount,
    initNotificationsTable,
Repository: go-gitea/gitea
File: web_src/js/modules/init.ts (TypeScript)

Code before:
export class InitPerformanceTracer {
  results: {name: string, dur: number}[] = [];
  recordCall(name: string, func: ()=>void) {
    const start = performance.now();
    func();
    this.results.push({name, dur: performance.now() - start});
  }
  printResults() {
    this.results = this.results.sort((a, b) => b.dur - a.dur);
    for (let i = 0; i < 20 && i < this.results.length; i++) {
      // eslint-disable-next-line no-console
      console.log(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
    }
  }
}

export function callInitFunctions(functions: (() => any)[]): InitPerformanceTracer | null {
  // Start performance trace by accessing a URL by "https://localhost/?_ui_performance_trace=1" or "https://localhost/?key=value&_ui_performance_trace=1"
  // It is a quick check, no side effect so no need to do slow URL parsing.
  const perfTracer = !window.location.search.includes('_ui_performance_trace=1') ? null : new InitPerformanceTracer();
  if (perfTracer) {
    for (const func of functions) perfTracer.recordCall(func.name, func);
  } else {
    for (const func of functions) func();
  }
  return perfTracer;
}


Review comment (performance):
```suggestion
    for (const [index, {name, dur}] of this.results.entries()) {
      if (index >= 20) break;
      console.info(`performance trace: ${name} ${dur.toFixed(3)}`);
    }
```

Code after:
export class InitPerformanceTracer {
  results: {name: string, dur: number}[] = [];
  recordCall(name: string, func: ()=>void) {
    const start = performance.now();
    func();
    this.results.push({name, dur: performance.now() - start});
  }
  printResults() {
    this.results = this.results.sort((a, b) => b.dur - a.dur);
    for (let i = 0; i < 20 && i < this.results.length; i++) {
      console.info(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
    }
  }
}

export function callInitFunctions(functions: (() => any)[]): InitPerformanceTracer | null {
  // Start performance trace by accessing a URL by "https://localhost/?_ui_performance_trace=1" or "https://localhost/?key=value&_ui_performance_trace=1"
  // It is a quick check, no side effect so no need to do slow URL parsing.
  const perfTracer = !window.location.search.includes('_ui_performance_trace=1') ? null : new InitPerformanceTracer();
  if (perfTracer) {
    for (const func of functions) perfTracer.recordCall(func.name, func);
  } else {
    for (const func of functions) func();
  }
  return perfTracer;
}
Repository: go-gitea/gitea
File: web_src/js/modules/init.ts (TypeScript)

Code before:
export class InitPerformanceTracer {
  results: {name: string, dur: number}[] = [];
  recordCall(name: string, func: ()=>void) {
    const start = performance.now();
    func();
    this.results.push({name, dur: performance.now() - start});
  }
  printResults() {
    this.results = this.results.sort((a, b) => b.dur - a.dur);
    for (let i = 0; i < 20 && i < this.results.length; i++) {
      // eslint-disable-next-line no-console
      console.log(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
    }
  }
}

export function callInitFunctions(functions: (() => any)[]): InitPerformanceTracer | null {
  // Start performance trace by accessing a URL by "https://localhost/?_ui_performance_trace=1" or "https://localhost/?key=value&_ui_performance_trace=1"
  // It is a quick check, no side effect so no need to do slow URL parsing.
  const perfTracer = !window.location.search.includes('_ui_performance_trace=1') ? null : new InitPerformanceTracer();
  if (perfTracer) {
    for (const func of functions) perfTracer.recordCall(func.name, func);
  } else {
    for (const func of functions) func();
  }
  return perfTracer;
}


Review comment (suggestion):
```suggestion
  for (const func of functions) {
    perfTracer?.recordCall(func.name, func) ?? func();
  }
```

Code after:
export class InitPerformanceTracer {
  results: {name: string, dur: number}[] = [];
  recordCall(name: string, func: ()=>void) {
    const start = performance.now();
    func();
    this.results.push({name, dur: performance.now() - start});
  }
  printResults() {
    this.results = this.results.sort((a, b) => b.dur - a.dur);
    for (let i = 0; i < 20 && i < this.results.length; i++) {
      console.info(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
    }
  }
}

export function callInitFunctions(functions: (() => any)[]): InitPerformanceTracer | null {
  // Start performance trace by accessing a URL by "https://localhost/?_ui_performance_trace=1" or "https://localhost/?key=value&_ui_performance_trace=1"
  // It is a quick check, no side effect so no need to do slow URL parsing.
  const perfTracer = !window.location.search.includes('_ui_performance_trace=1') ? null : new InitPerformanceTracer();
  if (perfTracer) {
    for (const func of functions) perfTracer.recordCall(func.name, func);
  } else {
    for (const func of functions) func();
  }
  return perfTracer;
}
Repository: go-gitea/gitea
File: web_src/js/modules/init.ts (TypeScript)

Code before:
export class InitPerformanceTracer {
  results: {name: string, dur: number}[] = [];
  recordCall(name: string, func: ()=>void) {
    const start = performance.now();
    func();
    this.results.push({name, dur: performance.now() - start});
  }
  printResults() {
    this.results = this.results.sort((a, b) => b.dur - a.dur);
    for (let i = 0; i < 20 && i < this.results.length; i++) {
      // eslint-disable-next-line no-console
      console.log(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
    }
  }
}

export function callInitFunctions(functions: (() => any)[]): InitPerformanceTracer | null {
  // Start performance trace by accessing a URL by "https://localhost/?_ui_performance_trace=1" or "https://localhost/?key=value&_ui_performance_trace=1"
  // It is a quick check, no side effect so no need to do slow URL parsing.
  const perfTracer = !window.location.search.includes('_ui_performance_trace=1') ? null : new InitPerformanceTracer();
  if (perfTracer) {
    for (const func of functions) perfTracer.recordCall(func.name, func);
  } else {
    for (const func of functions) func();
  }
  return perfTracer;
}


Review comment (performance):
```suggestion
      console.info(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
```

Code after:
export class InitPerformanceTracer {
  results: {name: string, dur: number}[] = [];
  recordCall(name: string, func: ()=>void) {
    const start = performance.now();
    func();
    this.results.push({name, dur: performance.now() - start});
  }
  printResults() {
    this.results = this.results.sort((a, b) => b.dur - a.dur);
    for (let i = 0; i < 20 && i < this.results.length; i++) {
      console.info(`performance trace: ${this.results[i].name} ${this.results[i].dur.toFixed(3)}`);
    }
  }
}

export function callInitFunctions(functions: (() => any)[]): InitPerformanceTracer | null {
  // Start performance trace by accessing a URL by "https://localhost/?_ui_performance_trace=1" or "https://localhost/?key=value&_ui_performance_trace=1"
  // It is a quick check, no side effect so no need to do slow URL parsing.
  const perfTracer = !window.location.search.includes('_ui_performance_trace=1') ? null : new InitPerformanceTracer();
  if (perfTracer) {
    for (const func of functions) perfTracer.recordCall(func.name, func);
  } else {
    for (const func of functions) func();
  }
  return perfTracer;
}
Repository: go-gitea/gitea
File: routers/api/v1/repo/actions_run.go (Go)

Code before:
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package repo

import (
	actions_model "code.gitea.io/gitea/models/actions"
	"code.gitea.io/gitea/routers/common"
	"code.gitea.io/gitea/services/context"
)

func DownloadActionsRunJobLogs(ctx *context.APIContext) {
	// swagger:operation GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs repository downloadActionsRunJobLogs
	// ---
	// summary: Downloads the logs for a workflow run redirects to blob url
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: name of the owner
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repository
	//   type: string
	//   required: true
	// - name: job_id
	//   in: path
	//   description: id of the job
	//   type: integer
	//   required: true
	// responses:
	//   "200":
	//     description: output blob content
	//   "400":
	//     "$ref": "#/responses/error"
	//   "404":
	//     "$ref": "#/responses/notFound"

Review comment (suggestion):
```suggestion
	// summary: Downloads the job logs for a workflow run
```
reasoning
- remove mention that the result is a redirect it is a http 200 download here 
  - did emulate such a redirect for artifact download just because of the weird logic in actions/download-artifact

- mention that this log is from a job not the whole workflow run

Code after:
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package repo

import (
	"errors"

	actions_model "code.gitea.io/gitea/models/actions"
	"code.gitea.io/gitea/modules/util"
	"code.gitea.io/gitea/routers/common"
	"code.gitea.io/gitea/services/context"
)

func DownloadActionsRunJobLogs(ctx *context.APIContext) {
	// swagger:operation GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs repository downloadActionsRunJobLogs
	// ---
	// summary: Downloads the job logs for a workflow run
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: name of the owner
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repository
	//   type: string
	//   required: true
	// - name: job_id
	//   in: path
	//   description: id of the job
	//   type: integer
	//   required: true
	// responses:
	//   "200":
	//     description: output blob content
	//   "400":