Simplify parameter types (#18006)

Remove repeated type declarations in function definitions.
This commit is contained in:
Gusted 2021-12-20 05:41:31 +01:00 committed by GitHub
parent 25677cdc5b
commit ff2fd08228
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
59 changed files with 115 additions and 116 deletions

View file

@ -25,7 +25,7 @@ import (
"github.com/urfave/cli" "github.com/urfave/cli"
) )
func addFile(w archiver.Writer, filePath string, absPath string, verbose bool) error { func addFile(w archiver.Writer, filePath, absPath string, verbose bool) error {
if verbose { if verbose {
log.Info("Adding file %s\n", filePath) log.Info("Adding file %s\n", filePath)
} }
@ -48,7 +48,7 @@ func addFile(w archiver.Writer, filePath string, absPath string, verbose bool) e
}) })
} }
func isSubdir(upper string, lower string) (bool, error) { func isSubdir(upper, lower string) (bool, error) {
if relPath, err := filepath.Rel(upper, lower); err != nil { if relPath, err := filepath.Rel(upper, lower); err != nil {
return false, err return false, err
} else if relPath == "." || !strings.HasPrefix(relPath, ".") { } else if relPath == "." || !strings.HasPrefix(relPath, ".") {

View file

@ -68,7 +68,7 @@ func TestAPIRepoTags(t *testing.T) {
session.MakeRequest(t, req, http.StatusNotFound) session.MakeRequest(t, req, http.StatusNotFound)
} }
func createNewTagUsingAPI(t *testing.T, session *TestSession, token string, ownerName, repoName, name, target, msg string) *api.Tag { func createNewTagUsingAPI(t *testing.T, session *TestSession, token, ownerName, repoName, name, target, msg string) *api.Tag {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags?token=%s", ownerName, repoName, token) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags?token=%s", ownerName, repoName, token)
req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateTagOption{ req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateTagOption{
TagName: name, TagName: name,

View file

@ -418,7 +418,7 @@ func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *tes
} }
} }
func doProtectBranch(ctx APITestContext, branch string, userToWhitelist string, unprotectedFilePatterns string) func(t *testing.T) { func doProtectBranch(ctx APITestContext, branch, userToWhitelist, unprotectedFilePatterns string) func(t *testing.T) {
// We are going to just use the owner to set the protection. // We are going to just use the owner to set the protection.
return func(t *testing.T) { return func(t *testing.T) {
csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame))) csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)))

View file

@ -310,7 +310,7 @@ func testIssueWithBean(t *testing.T, user string, repoID int64, title, content s
return issueURL, issue return issueURL, issue
} }
func testIssueChangeInfo(t *testing.T, user, issueURL, info string, value string) { func testIssueChangeInfo(t *testing.T, user, issueURL, info, value string) {
session := loginUser(t, user) session := loginUser(t, user)
req := NewRequest(t, "GET", issueURL) req := NewRequest(t, "GET", issueURL)

View file

@ -448,7 +448,7 @@ func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) {
} }
// SearchMilestones search milestones // SearchMilestones search milestones
func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType string, keyword string) (MilestoneList, error) { func SearchMilestones(repoCond builder.Cond, page int, isClosed bool, sortType, keyword string) (MilestoneList, error) {
miles := make([]*Milestone, 0, setting.UI.IssuePagingNum) miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed) sess := db.GetEngine(db.DefaultContext).Where("is_closed = ?", isClosed)
if len(keyword) > 0 { if len(keyword) > 0 {

View file

@ -146,7 +146,7 @@ type IssueContentListItem struct {
} }
// FetchIssueContentHistoryList fetch list // FetchIssueContentHistoryList fetch list
func FetchIssueContentHistoryList(dbCtx context.Context, issueID int64, commentID int64) ([]*IssueContentListItem, error) { func FetchIssueContentHistoryList(dbCtx context.Context, issueID, commentID int64) ([]*IssueContentListItem, error) {
res := make([]*IssueContentListItem, 0) res := make([]*IssueContentListItem, 0)
err := db.GetEngine(dbCtx).Select("u.id as user_id, u.name as user_name,"+ err := db.GetEngine(dbCtx).Select("u.id as user_id, u.name as user_name,"+
"h.id as history_id, h.edited_unix, h.is_first_created, h.is_deleted"). "h.id as history_id, h.edited_unix, h.is_first_created, h.is_deleted").
@ -168,7 +168,7 @@ func FetchIssueContentHistoryList(dbCtx context.Context, issueID int64, commentI
} }
// HasIssueContentHistory check if a ContentHistory entry exists // HasIssueContentHistory check if a ContentHistory entry exists
func HasIssueContentHistory(dbCtx context.Context, issueID int64, commentID int64) (bool, error) { func HasIssueContentHistory(dbCtx context.Context, issueID, commentID int64) (bool, error) {
exists, err := db.GetEngine(dbCtx).Cols("id").Exist(&ContentHistory{ exists, err := db.GetEngine(dbCtx).Cols("id").Exist(&ContentHistory{
IssueID: issueID, IssueID: issueID,
CommentID: commentID, CommentID: commentID,

View file

@ -316,11 +316,11 @@ func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]
} }
// IsUserVisibleToViewer check if viewer is able to see user profile // IsUserVisibleToViewer check if viewer is able to see user profile
func IsUserVisibleToViewer(u *user_model.User, viewer *user_model.User) bool { func IsUserVisibleToViewer(u, viewer *user_model.User) bool {
return isUserVisibleToViewer(db.GetEngine(db.DefaultContext), u, viewer) return isUserVisibleToViewer(db.GetEngine(db.DefaultContext), u, viewer)
} }
func isUserVisibleToViewer(e db.Engine, u *user_model.User, viewer *user_model.User) bool { func isUserVisibleToViewer(e db.Engine, u, viewer *user_model.User) bool {
if viewer != nil && viewer.IsAdmin { if viewer != nil && viewer.IsAdmin {
return true return true
} }

View file

@ -76,7 +76,7 @@ func SetSetting(setting *Setting) error {
return upsertSettingValue(setting.UserID, setting.SettingKey, setting.SettingValue) return upsertSettingValue(setting.UserID, setting.SettingKey, setting.SettingValue)
} }
func upsertSettingValue(userID int64, key string, value string) error { func upsertSettingValue(userID int64, key, value string) error {
return db.WithTx(func(ctx context.Context) error { return db.WithTx(func(ctx context.Context) error {
e := db.GetEngine(ctx) e := db.GetEngine(ctx)

View file

@ -16,10 +16,10 @@ var (
blocks = []blockFunc{b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27} blocks = []blockFunc{b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27}
) )
type blockFunc func(img *image.Paletted, x, y, size int, angle int) type blockFunc func(img *image.Paletted, x, y, size, angle int)
// draw a polygon by points, and the polygon is rotated by angle. // draw a polygon by points, and the polygon is rotated by angle.
func drawBlock(img *image.Paletted, x, y, size int, angle int, points []int) { func drawBlock(img *image.Paletted, x, y, size, angle int, points []int) {
if angle != 0 { if angle != 0 {
m := size / 2 m := size / 2
rotate(points, m, m, angle) rotate(points, m, m, angle)
@ -41,7 +41,7 @@ func drawBlock(img *image.Paletted, x, y, size int, angle int, points []int) {
// | | // | |
// | | // | |
// -------- // --------
func b0(img *image.Paletted, x, y, size int, angle int) {} func b0(img *image.Paletted, x, y, size, angle int) {}
// full-filled // full-filled
// //
@ -50,7 +50,7 @@ func b0(img *image.Paletted, x, y, size int, angle int) {}
// |######| // |######|
// |######| // |######|
// -------- // --------
func b1(img *image.Paletted, x, y, size int, angle int) { func b1(img *image.Paletted, x, y, size, angle int) {
for i := x; i < x+size; i++ { for i := x; i < x+size; i++ {
for j := y; j < y+size; j++ { for j := y; j < y+size; j++ {
img.SetColorIndex(i, j, 1) img.SetColorIndex(i, j, 1)
@ -65,7 +65,7 @@ func b1(img *image.Paletted, x, y, size int, angle int) {
// | #### | // | #### |
// | | // | |
// ---------- // ----------
func b2(img *image.Paletted, x, y, size int, angle int) { func b2(img *image.Paletted, x, y, size, angle int) {
l := size / 4 l := size / 4
x += l x += l
y += l y += l
@ -88,7 +88,7 @@ func b2(img *image.Paletted, x, y, size int, angle int) {
// | ### | // | ### |
// | # | // | # |
// --------- // ---------
func b3(img *image.Paletted, x, y, size int, angle int) { func b3(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, 0, []int{ drawBlock(img, x, y, size, 0, []int{
m, 0, m, 0,
@ -108,7 +108,7 @@ func b3(img *image.Paletted, x, y, size int, angle int) {
// |## | // |## |
// |# | // |# |
// |------ // |------
func b4(img *image.Paletted, x, y, size int, angle int) { func b4(img *image.Paletted, x, y, size, angle int) {
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
0, 0, 0, 0,
size, 0, size, 0,
@ -124,7 +124,7 @@ func b4(img *image.Paletted, x, y, size int, angle int) {
// | ### | // | ### |
// | ##### | // | ##### |
// |#######| // |#######|
func b5(img *image.Paletted, x, y, size int, angle int) { func b5(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
m, 0, m, 0,
@ -141,7 +141,7 @@ func b5(img *image.Paletted, x, y, size int, angle int) {
// |### | // |### |
// |### | // |### |
// -------- // --------
func b6(img *image.Paletted, x, y, size int, angle int) { func b6(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
0, 0, 0, 0,
@ -160,7 +160,7 @@ func b6(img *image.Paletted, x, y, size int, angle int) {
// | #####| // | #####|
// | ####| // | ####|
// |-------- // |--------
func b7(img *image.Paletted, x, y, size int, angle int) { func b7(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
0, 0, 0, 0,
@ -181,7 +181,7 @@ func b7(img *image.Paletted, x, y, size int, angle int) {
// | ### ### | // | ### ### |
// |#########| // |#########|
// ----------- // -----------
func b8(img *image.Paletted, x, y, size int, angle int) { func b8(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
mm := m / 2 mm := m / 2
@ -219,7 +219,7 @@ func b8(img *image.Paletted, x, y, size int, angle int) {
// | #### | // | #### |
// | # | // | # |
// --------- // ---------
func b9(img *image.Paletted, x, y, size int, angle int) { func b9(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
0, 0, 0, 0,
@ -241,7 +241,7 @@ func b9(img *image.Paletted, x, y, size int, angle int) {
// |## | // |## |
// |# | // |# |
// ---------- // ----------
func b10(img *image.Paletted, x, y, size int, angle int) { func b10(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
m, 0, m, 0,
@ -267,7 +267,7 @@ func b10(img *image.Paletted, x, y, size int, angle int) {
// | | // | |
// | | // | |
// ---------- // ----------
func b11(img *image.Paletted, x, y, size int, angle int) { func b11(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
0, 0, 0, 0,
@ -287,7 +287,7 @@ func b11(img *image.Paletted, x, y, size int, angle int) {
// | ##### | // | ##### |
// | # | // | # |
// ----------- // -----------
func b12(img *image.Paletted, x, y, size int, angle int) { func b12(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
0, m, 0, m,
@ -306,7 +306,7 @@ func b12(img *image.Paletted, x, y, size int, angle int) {
// | ##### | // | ##### |
// |#########| // |#########|
// ----------- // -----------
func b13(img *image.Paletted, x, y, size int, angle int) { func b13(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
m, m, m, m,
@ -325,7 +325,7 @@ func b13(img *image.Paletted, x, y, size int, angle int) {
// | | // | |
// | | // | |
// --------- // ---------
func b14(img *image.Paletted, x, y, size int, angle int) { func b14(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
m, 0, m, 0,
@ -344,7 +344,7 @@ func b14(img *image.Paletted, x, y, size int, angle int) {
// | | // | |
// | | // | |
// ---------- // ----------
func b15(img *image.Paletted, x, y, size int, angle int) { func b15(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
0, 0, 0, 0,
@ -364,7 +364,7 @@ func b15(img *image.Paletted, x, y, size int, angle int) {
// | ##### | // | ##### |
// |#######| // |#######|
// --------- // ---------
func b16(img *image.Paletted, x, y, size int, angle int) { func b16(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
m, 0, m, 0,
@ -390,7 +390,7 @@ func b16(img *image.Paletted, x, y, size int, angle int) {
// | ##| // | ##|
// | ##| // | ##|
// ---------- // ----------
func b17(img *image.Paletted, x, y, size int, angle int) { func b17(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
@ -419,7 +419,7 @@ func b17(img *image.Paletted, x, y, size int, angle int) {
// |## | // |## |
// |# | // |# |
// ---------- // ----------
func b18(img *image.Paletted, x, y, size int, angle int) { func b18(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
@ -439,7 +439,7 @@ func b18(img *image.Paletted, x, y, size int, angle int) {
// |### ###| // |### ###|
// |########| // |########|
// ---------- // ----------
func b19(img *image.Paletted, x, y, size int, angle int) { func b19(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
drawBlock(img, x, y, size, angle, []int{ drawBlock(img, x, y, size, angle, []int{
@ -480,7 +480,7 @@ func b19(img *image.Paletted, x, y, size int, angle int) {
// |## | // |## |
// |# | // |# |
// ---------- // ----------
func b20(img *image.Paletted, x, y, size int, angle int) { func b20(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4
@ -501,7 +501,7 @@ func b20(img *image.Paletted, x, y, size int, angle int) {
// |## | // |## |
// |# | // |# |
// ---------- // ----------
func b21(img *image.Paletted, x, y, size int, angle int) { func b21(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4
@ -529,7 +529,7 @@ func b21(img *image.Paletted, x, y, size int, angle int) {
// |## ##| // |## ##|
// |# #| // |# #|
// ---------- // ----------
func b22(img *image.Paletted, x, y, size int, angle int) { func b22(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4
@ -557,7 +557,7 @@ func b22(img *image.Paletted, x, y, size int, angle int) {
// |## | // |## |
// |# | // |# |
// ---------- // ----------
func b23(img *image.Paletted, x, y, size int, angle int) { func b23(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4
@ -585,7 +585,7 @@ func b23(img *image.Paletted, x, y, size int, angle int) {
// |## ## | // |## ## |
// |# # | // |# # |
// ---------- // ----------
func b24(img *image.Paletted, x, y, size int, angle int) { func b24(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4
@ -613,7 +613,7 @@ func b24(img *image.Paletted, x, y, size int, angle int) {
// |###### | // |###### |
// |#### | // |#### |
// ---------- // ----------
func b25(img *image.Paletted, x, y, size int, angle int) { func b25(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4
@ -641,7 +641,7 @@ func b25(img *image.Paletted, x, y, size int, angle int) {
// |### ###| // |### ###|
// |# #| // |# #|
// ---------- // ----------
func b26(img *image.Paletted, x, y, size int, angle int) { func b26(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4
@ -683,7 +683,7 @@ func b26(img *image.Paletted, x, y, size int, angle int) {
// |### ##| // |### ##|
// |########| // |########|
// ---------- // ----------
func b27(img *image.Paletted, x, y, size int, angle int) { func b27(img *image.Paletted, x, y, size, angle int) {
m := size / 2 m := size / 2
q := size / 4 q := size / 4

View file

@ -16,7 +16,7 @@ var (
// rotate the points by center point (x,y) // rotate the points by center point (x,y)
// angle: [0,1,2,3] means [090180270] degree // angle: [0,1,2,3] means [090180270] degree
func rotate(points []int, x, y int, angle int) { func rotate(points []int, x, y, angle int) {
// the angle is only used internally, and it has been guaranteed to be 0/1/2/3, so we do not check it again // the angle is only used internally, and it has been guaranteed to be 0/1/2/3, so we do not check it again
for i := 0; i < len(points); i += 2 { for i := 0; i < len(points); i += 2 {
px, py := points[i]-x, points[i+1]-y px, py := points[i]-x, points[i+1]-y

View file

@ -149,7 +149,7 @@ func PrettyNumber(v int64) string {
} }
// Subtract deals with subtraction of all types of number. // Subtract deals with subtraction of all types of number.
func Subtract(left interface{}, right interface{}) interface{} { func Subtract(left, right interface{}) interface{} {
var rleft, rright int64 var rleft, rright int64
var fleft, fright float64 var fleft, fright float64
var isInt = true var isInt = true

View file

@ -261,14 +261,14 @@ func TestDetectEncoding(t *testing.T) {
assert.Error(t, err) assert.Error(t, err)
} }
func stringMustStartWith(t *testing.T, expected string, value string) { func stringMustStartWith(t *testing.T, expected, value string) {
assert.Equal(t, expected, string(value[:len(expected)])) assert.Equal(t, expected, string(value[:len(expected)]))
} }
func stringMustEndWith(t *testing.T, expected string, value string) { func stringMustEndWith(t *testing.T, expected, value string) {
assert.Equal(t, expected, string(value[len(value)-len(expected):])) assert.Equal(t, expected, string(value[len(value)-len(expected):]))
} }
func bytesMustStartWith(t *testing.T, expected []byte, value []byte) { func bytesMustStartWith(t *testing.T, expected, value []byte) {
assert.Equal(t, expected, value[:len(expected)]) assert.Equal(t, expected, value[:len(expected)])
} }

View file

@ -20,14 +20,14 @@ type Pagination struct {
} }
// NewPagination creates a new instance of the Pagination struct // NewPagination creates a new instance of the Pagination struct
func NewPagination(total int, page int, issueNum int, numPages int) *Pagination { func NewPagination(total, page, issueNum, numPages int) *Pagination {
p := &Pagination{} p := &Pagination{}
p.Paginater = paginater.New(total, page, issueNum, numPages) p.Paginater = paginater.New(total, page, issueNum, numPages)
return p return p
} }
// AddParam adds a value from context identified by ctxKey as link param under a given paramKey // AddParam adds a value from context identified by ctxKey as link param under a given paramKey
func (p *Pagination) AddParam(ctx *Context, paramKey string, ctxKey string) { func (p *Pagination) AddParam(ctx *Context, paramKey, ctxKey string) {
_, exists := ctx.Data[ctxKey] _, exists := ctx.Data[ctxKey]
if !exists { if !exists {
return return
@ -38,7 +38,7 @@ func (p *Pagination) AddParam(ctx *Context, paramKey string, ctxKey string) {
} }
// AddParamString adds a string parameter directly // AddParamString adds a string parameter directly
func (p *Pagination) AddParamString(key string, value string) { func (p *Pagination) AddParamString(key, value string) {
urlParam := fmt.Sprintf("%s=%v", url.QueryEscape(key), url.QueryEscape(value)) urlParam := fmt.Sprintf("%s=%v", url.QueryEscape(key), url.QueryEscape(value))
p.urlParams = append(p.urlParams, urlParam) p.urlParams = append(p.urlParams, urlParam)
} }

View file

@ -180,7 +180,7 @@ func (r *Repository) GetCommitsCount() (int64, error) {
} }
// GetCommitGraphsCount returns cached commit count for current view // GetCommitGraphsCount returns cached commit count for current view
func (r *Repository) GetCommitGraphsCount(hidePRRefs bool, branches []string, files []string) (int64, error) { func (r *Repository) GetCommitGraphsCount(hidePRRefs bool, branches, files []string) (int64, error) {
cacheKey := fmt.Sprintf("commits-count-%d-graph-%t-%s-%s", r.Repository.ID, hidePRRefs, branches, files) cacheKey := fmt.Sprintf("commits-count-%d-graph-%t-%s-%s", r.Repository.ID, hidePRRefs, branches, files)
return cache.GetInt64(cacheKey, func() (int64, error) { return cache.GetInt64(cacheKey, func() (int64, error) {
@ -206,7 +206,7 @@ func (r *Repository) BranchNameSubURL() string {
} }
// FileExists returns true if a file exists in the given repo branch // FileExists returns true if a file exists in the given repo branch
func (r *Repository) FileExists(path string, branch string) (bool, error) { func (r *Repository) FileExists(path, branch string) (bool, error) {
if branch == "" { if branch == "" {
branch = r.Repository.DefaultBranch branch = r.Repository.DefaultBranch
} }

View file

@ -14,7 +14,7 @@ import (
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
) )
func wrapNewlines(w io.Writer, prefix []byte, value []byte) (sum int64, err error) { func wrapNewlines(w io.Writer, prefix, value []byte) (sum int64, err error) {
if len(value) == 0 { if len(value) == 0 {
return return
} }

View file

@ -386,7 +386,7 @@ type DivergeObject struct {
Behind int Behind int
} }
func checkDivergence(repoPath string, baseBranch string, targetBranch string) (int, error) { func checkDivergence(repoPath, baseBranch, targetBranch string) (int, error) {
branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch) branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch)
cmd := NewCommand("rev-list", "--count", branches) cmd := NewCommand("rev-list", "--count", branches)
stdout, err := cmd.RunInDir(repoPath) stdout, err := cmd.RunInDir(repoPath)
@ -401,7 +401,7 @@ func checkDivergence(repoPath string, baseBranch string, targetBranch string) (i
} }
// GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch // GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch
func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error) { func GetDivergingCommits(repoPath, baseBranch, targetBranch string) (DivergeObject, error) {
// $(git rev-list --count master..feature) commits ahead of master // $(git rev-list --count master..feature) commits ahead of master
ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch) ahead, errorAhead := checkDivergence(repoPath, baseBranch, targetBranch)
if errorAhead != nil { if errorAhead != nil {

View file

@ -264,7 +264,7 @@ func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (in
// CommitsBetween returns a list that contains commits between [before, last). // CommitsBetween returns a list that contains commits between [before, last).
// If before is detached (removed by reset + push) it is not included. // If before is detached (removed by reset + push) it is not included.
func (repo *Repository) CommitsBetween(last *Commit, before *Commit) ([]*Commit, error) { func (repo *Repository) CommitsBetween(last, before *Commit) ([]*Commit, error) {
var stdout []byte var stdout []byte
var err error var err error
if before == nil { if before == nil {
@ -284,7 +284,7 @@ func (repo *Repository) CommitsBetween(last *Commit, before *Commit) ([]*Commit,
} }
// CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [before, last) // CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [before, last)
func (repo *Repository) CommitsBetweenLimit(last *Commit, before *Commit, limit, skip int) ([]*Commit, error) { func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip int) ([]*Commit, error) {
var stdout []byte var stdout []byte
var err error var err error
if before == nil { if before == nil {

View file

@ -27,7 +27,7 @@ type CompareInfo struct {
} }
// GetMergeBase checks and returns merge base of two branches and the reference used as base. // GetMergeBase checks and returns merge base of two branches and the reference used as base.
func (repo *Repository) GetMergeBase(tmpRemote string, base, head string) (string, string, error) { func (repo *Repository) GetMergeBase(tmpRemote, base, head string) (string, string, error) {
if tmpRemote == "" { if tmpRemote == "" {
tmpRemote = "origin" tmpRemote = "origin"
} }

View file

@ -23,7 +23,7 @@ type CommitTreeOpts struct {
} }
// CommitTree creates a commit from a given tree id for the user with provided message // CommitTree creates a commit from a given tree id for the user with provided message
func (repo *Repository) CommitTree(author *Signature, committer *Signature, tree *Tree, opts CommitTreeOpts) (SHA1, error) { func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opts CommitTreeOpts) (SHA1, error) {
err := LoadGitVersion() err := LoadGitVersion()
if err != nil { if err != nil {
return SHA1{}, err return SHA1{}, err

View file

@ -125,7 +125,7 @@ func SplitRefName(refStr string) (string, string) {
// 0 is false, true // 0 is false, true
// Any other integer is true, true // Any other integer is true, true
// Anything else will return false, false // Anything else will return false, false
func ParseBool(value string) (result bool, valid bool) { func ParseBool(value string) (result, valid bool) {
// Empty strings are true but invalid // Empty strings are true but invalid
if len(value) == 0 { if len(value) == 0 {
return true, false return true, false

View file

@ -17,7 +17,7 @@ import (
) )
// GetCommitGraph return a list of commit (GraphItems) from all branches // GetCommitGraph return a list of commit (GraphItems) from all branches
func GetCommitGraph(r *git.Repository, page int, maxAllowedColors int, hidePRRefs bool, branches, files []string) (*Graph, error) { func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bool, branches, files []string) (*Graph, error) {
format := "DATA:%D|%H|%ad|%h|%s" format := "DATA:%D|%H|%ad|%h|%s"
if page == 0 { if page == 0 {

View file

@ -39,7 +39,7 @@ func isBuiltin(s string) bool {
} }
// ParseHostMatchList parses the host list HostMatchList // ParseHostMatchList parses the host list HostMatchList
func ParseHostMatchList(settingKeyHint string, hostList string) *HostMatchList { func ParseHostMatchList(settingKeyHint, hostList string) *HostMatchList {
hl := &HostMatchList{SettingKeyHint: settingKeyHint, SettingValue: hostList} hl := &HostMatchList{SettingKeyHint: settingKeyHint, SettingValue: hostList}
for _, s := range strings.Split(hostList, ",") { for _, s := range strings.Split(hostList, ",") {
s = strings.ToLower(strings.TrimSpace(s)) s = strings.ToLower(strings.TrimSpace(s))
@ -59,7 +59,7 @@ func ParseHostMatchList(settingKeyHint string, hostList string) *HostMatchList {
} }
// ParseSimpleMatchList parse a simple matchlist (no built-in networks, no CIDR support, only wildcard pattern match) // ParseSimpleMatchList parse a simple matchlist (no built-in networks, no CIDR support, only wildcard pattern match)
func ParseSimpleMatchList(settingKeyHint string, matchList string) *HostMatchList { func ParseSimpleMatchList(settingKeyHint, matchList string) *HostMatchList {
hl := &HostMatchList{ hl := &HostMatchList{
SettingKeyHint: settingKeyHint, SettingKeyHint: settingKeyHint,
SettingValue: matchList, SettingValue: matchList,

View file

@ -13,7 +13,7 @@ import (
) )
// NewDialContext returns a DialContext for Transport, the DialContext will do allow/block list check // NewDialContext returns a DialContext for Transport, the DialContext will do allow/block list check
func NewDialContext(usage string, allowList *HostMatchList, blockList *HostMatchList) func(ctx context.Context, network, addr string) (net.Conn, error) { func NewDialContext(usage string, allowList, blockList *HostMatchList) func(ctx context.Context, network, addr string) (net.Conn, error) {
// How Go HTTP Client works with redirection: // How Go HTTP Client works with redirection:
// transport.RoundTrip URL=http://domain.com, Host=domain.com // transport.RoundTrip URL=http://domain.com, Host=domain.com
// transport.DialContext addrOrHost=domain.com:80 // transport.DialContext addrOrHost=domain.com:80

View file

@ -80,7 +80,7 @@ func (l *MultiChannelledLogger) Log(skip int, level Level, format string, v ...i
} }
// SendLog sends a log event at the provided level with the information given // SendLog sends a log event at the provided level with the information given
func (l *MultiChannelledLogger) SendLog(level Level, caller, filename string, line int, msg string, stack string) error { func (l *MultiChannelledLogger) SendLog(level Level, caller, filename string, line int, msg, stack string) error {
if l.GetLevel() > level { if l.GetLevel() > level {
return nil return nil
} }

View file

@ -73,7 +73,7 @@ func (logger *WriterLogger) GetStacktraceLevel() Level {
} }
// Copy of cheap integer to fixed-width decimal to ascii from logger. // Copy of cheap integer to fixed-width decimal to ascii from logger.
func itoa(buf *[]byte, i int, wid int) { func itoa(buf *[]byte, i, wid int) {
var logger [20]byte var logger [20]byte
bp := len(logger) - 1 bp := len(logger) - 1
for i >= 10 || wid > 1 { for i >= 10 || wid > 1 {

View file

@ -229,7 +229,7 @@ func (p *prefixedIDs) Generate(value []byte, kind ast.NodeKind) []byte {
} }
// Generate generates a new element id. // Generate generates a new element id.
func (p *prefixedIDs) GenerateWithDefault(value []byte, dft []byte) []byte { func (p *prefixedIDs) GenerateWithDefault(value, dft []byte) []byte {
result := common.CleanValue(value) result := common.CleanValue(value)
if len(result) == 0 { if len(result) == 0 {
result = dft result = dft

View file

@ -179,7 +179,7 @@ func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *r
} }
} }
func (a *actionNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func (a *actionNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
if err := models.NotifyWatchers(&models.Action{ if err := models.NotifyWatchers(&models.Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUser: doer, ActUser: doer,

View file

@ -122,7 +122,7 @@ func (*NullNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *model
} }
// NotifyCreateRepository places a place holder function // NotifyCreateRepository places a place holder function
func (*NullNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func (*NullNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
} }
// NotifyDeleteRepository places a place holder function // NotifyDeleteRepository places a place holder function
@ -134,7 +134,7 @@ func (*NullNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *
} }
// NotifyMigrateRepository places a place holder function // NotifyMigrateRepository places a place holder function
func (*NullNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func (*NullNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
} }
// NotifyPushCommits notifies commits pushed to notifiers // NotifyPushCommits notifies commits pushed to notifiers

View file

@ -115,7 +115,7 @@ func (r *indexerNotifier) NotifyDeleteRepository(doer *user_model.User, repo *re
} }
} }
func (r *indexerNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func (r *indexerNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
issue_indexer.UpdateRepoIndexer(repo) issue_indexer.UpdateRepoIndexer(repo)
if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty { if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty {
code_indexer.UpdateRepoIndexer(repo) code_indexer.UpdateRepoIndexer(repo)

View file

@ -210,14 +210,14 @@ func NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue,
} }
// NotifyCreateRepository notifies create repository to notifiers // NotifyCreateRepository notifies create repository to notifiers
func NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyCreateRepository(doer, u, repo) notifier.NotifyCreateRepository(doer, u, repo)
} }
} }
// NotifyMigrateRepository notifies create repository to notifiers // NotifyMigrateRepository notifies create repository to notifiers
func NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
for _, notifier := range notifiers { for _, notifier := range notifiers {
notifier.NotifyMigrateRepository(doer, u, repo) notifier.NotifyMigrateRepository(doer, u, repo)
} }

View file

@ -102,7 +102,7 @@ func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, r
} }
} }
func (m *webhookNotifier) NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func (m *webhookNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
// Add to hook queue for created repo after session commit. // Add to hook queue for created repo after session commit.
if err := webhook_services.PrepareWebhooks(repo, webhook.HookEventRepository, &api.RepositoryPayload{ if err := webhook_services.PrepareWebhooks(repo, webhook.HookEventRepository, &api.RepositoryPayload{
Action: api.HookRepoCreated, Action: api.HookRepoCreated,
@ -127,7 +127,7 @@ func (m *webhookNotifier) NotifyDeleteRepository(doer *user_model.User, repo *re
} }
} }
func (m *webhookNotifier) NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) { func (m *webhookNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) {
// Add to hook queue for created repo after session commit. // Add to hook queue for created repo after session commit.
if err := webhook_services.PrepareWebhooks(repo, webhook.HookEventRepository, &api.RepositoryPayload{ if err := webhook_services.PrepareWebhooks(repo, webhook.HookEventRepository, &api.RepositoryPayload{
Action: api.HookRepoCreated, Action: api.HookRepoCreated,

View file

@ -151,7 +151,7 @@ func newKeywords() {
}) })
} }
func doNewKeywords(close []string, reopen []string) { func doNewKeywords(close, reopen []string) {
issueCloseKeywordsPat = makeKeywordsPat(close) issueCloseKeywordsPat = makeKeywordsPat(close)
issueReopenKeywordsPat = makeKeywordsPat(reopen) issueReopenKeywordsPat = makeKeywordsPat(reopen)
} }
@ -467,7 +467,7 @@ func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference
return ret return ret
} }
func getCrossReference(content []byte, start, end int, fromLink bool, prOnly bool) *rawReference { func getCrossReference(content []byte, start, end int, fromLink, prOnly bool) *rawReference {
sep := bytes.IndexAny(content[start:end], "#!") sep := bytes.IndexAny(content[start:end], "#!")
if sep < 0 { if sep < 0 {
return nil return nil
@ -537,7 +537,7 @@ func findActionKeywords(content []byte, start int) (XRefAction, *RefSpan) {
} }
// IsXrefActionable returns true if the xref action is actionable (i.e. produces a result when resolved) // IsXrefActionable returns true if the xref action is actionable (i.e. produces a result when resolved)
func IsXrefActionable(ref *RenderizableReference, extTracker bool, alphaNum bool) bool { func IsXrefActionable(ref *RenderizableReference, extTracker, alphaNum bool) bool {
if extTracker { if extTracker {
// External issues cannot be automatically closed // External issues cannot be automatically closed
return false return false

View file

@ -65,7 +65,7 @@ func AesDecrypt(key, text []byte) ([]byte, error) {
} }
// EncryptSecret encrypts a string with given key into a hex string // EncryptSecret encrypts a string with given key into a hex string
func EncryptSecret(key string, str string) (string, error) { func EncryptSecret(key, str string) (string, error) {
keyHash := sha256.Sum256([]byte(key)) keyHash := sha256.Sum256([]byte(key))
plaintext := []byte(str) plaintext := []byte(str)
ciphertext, err := AesEncrypt(keyHash[:], plaintext) ciphertext, err := AesEncrypt(keyHash[:], plaintext)
@ -76,7 +76,7 @@ func EncryptSecret(key string, str string) (string, error) {
} }
// DecryptSecret decrypts a previously encrypted hex string // DecryptSecret decrypts a previously encrypted hex string
func DecryptSecret(key string, cipherhex string) (string, error) { func DecryptSecret(key, cipherhex string) (string, error) {
keyHash := sha256.Sum256([]byte(key)) keyHash := sha256.Sum256([]byte(key))
ciphertext, err := hex.DecodeString(cipherhex) ciphertext, err := hex.DecodeString(cipherhex)
if err != nil { if err != nil {

View file

@ -67,7 +67,7 @@ func AddSubLogDescription(key string, subLogDescription SubLogDescription) bool
} }
// RemoveSubLogDescription removes a sub log description // RemoveSubLogDescription removes a sub log description
func RemoveSubLogDescription(key string, name string) bool { func RemoveSubLogDescription(key, name string) bool {
descriptionLock.Lock() descriptionLock.Lock()
defer descriptionLock.Unlock() defer descriptionLock.Unlock()
desc, ok := logDescriptions[key] desc, ok := logDescriptions[key]
@ -119,7 +119,7 @@ func getLogLevel(section *ini.Section, key string, defaultValue log.Level) log.L
return log.FromString(value) return log.FromString(value)
} }
func getStacktraceLogLevel(section *ini.Section, key string, defaultValue string) string { func getStacktraceLogLevel(section *ini.Section, key, defaultValue string) string {
value := section.Key(key).MustString(defaultValue) value := section.Key(key).MustString(defaultValue)
return log.FromString(value).String() return log.FromString(value).String()
} }

View file

@ -1115,7 +1115,7 @@ func generateSaveInternalToken() {
} }
// MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash // MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash
func MakeAbsoluteAssetURL(appURL string, staticURLPrefix string) string { func MakeAbsoluteAssetURL(appURL, staticURLPrefix string) string {
parsedPrefix, err := url.Parse(strings.TrimSuffix(staticURLPrefix, "/")) parsedPrefix, err := url.Parse(strings.TrimSuffix(staticURLPrefix, "/"))
if err != nil { if err != nil {
log.Fatal("Unable to parse STATIC_URL_PREFIX: %v", err) log.Fatal("Unable to parse STATIC_URL_PREFIX: %v", err)
@ -1134,7 +1134,7 @@ func MakeAbsoluteAssetURL(appURL string, staticURLPrefix string) string {
} }
// MakeManifestData generates web app manifest JSON // MakeManifestData generates web app manifest JSON
func MakeManifestData(appName string, appURL string, absoluteAssetURL string) []byte { func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte {
type manifestIcon struct { type manifestIcon struct {
Src string `json:"src"` Src string `json:"src"`
Type string `json:"type"` Type string `json:"type"`

View file

@ -263,7 +263,7 @@ func sshConnectionFailed(conn net.Conn, err error) {
} }
// Listen starts a SSH server listens on given port. // Listen starts a SSH server listens on given port.
func Listen(host string, port int, ciphers []string, keyExchanges []string, macs []string) { func Listen(host string, port int, ciphers, keyExchanges, macs []string) {
srv := ssh.Server{ srv := ssh.Server{
Addr: net.JoinHostPort(host, strconv.Itoa(port)), Addr: net.JoinHostPort(host, strconv.Itoa(port)),
PublicKeyHandler: publicKeyHandler, PublicKeyHandler: publicKeyHandler,

View file

@ -524,7 +524,7 @@ func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (i
} }
// AvatarHTML creates the HTML for an avatar // AvatarHTML creates the HTML for an avatar
func AvatarHTML(src string, size int, class string, name string) template.HTML { func AvatarHTML(src string, size int, class, name string) template.HTML {
sizeStr := fmt.Sprintf(`%d`, size) sizeStr := fmt.Sprintf(`%d`, size)
if name == "" { if name == "" {
@ -594,7 +594,7 @@ func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTM
} }
// AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string) // AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string)
func AvatarByEmail(email string, name string, others ...interface{}) template.HTML { func AvatarByEmail(email, name string, others ...interface{}) template.HTML {
size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar image", others...) size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar image", others...)
src := avatars.GenerateEmailAvatarFastLink(email, size*setting.Avatar.RenderedSizeFactor) src := avatars.GenerateEmailAvatarFastLink(email, size*setting.Avatar.RenderedSizeFactor)

View file

@ -35,7 +35,7 @@ func (err ErrFileTypeForbidden) Error() string {
var wildcardTypeRe = regexp.MustCompile(`^[a-z]+/\*$`) var wildcardTypeRe = regexp.MustCompile(`^[a-z]+/\*$`)
// Verify validates whether a file is allowed to be uploaded. // Verify validates whether a file is allowed to be uploaded.
func Verify(buf []byte, fileName string, allowedTypesStr string) error { func Verify(buf []byte, fileName, allowedTypesStr string) error {
allowedTypesStr = strings.ReplaceAll(allowedTypesStr, "|", ",") // compat for old config format allowedTypesStr = strings.ReplaceAll(allowedTypesStr, "|", ",") // compat for old config format
allowedTypes := []string{} allowedTypes := []string{}

View file

@ -71,7 +71,7 @@ func IsInt64InSlice(target int64, slice []int64) bool {
} }
// IsEqualSlice returns true if slices are equal. // IsEqualSlice returns true if slices are equal.
func IsEqualSlice(target []string, source []string) bool { func IsEqualSlice(target, source []string) bool {
if len(target) != len(source) { if len(target) != len(source) {
return false return false
} }

View file

@ -17,7 +17,7 @@ import (
// EnsureAbsolutePath ensure that a path is absolute, making it // EnsureAbsolutePath ensure that a path is absolute, making it
// relative to absoluteBase if necessary // relative to absoluteBase if necessary
func EnsureAbsolutePath(path string, absoluteBase string) string { func EnsureAbsolutePath(path, absoluteBase string) string {
if filepath.IsAbs(path) { if filepath.IsAbs(path) {
return path return path
} }

View file

@ -119,7 +119,7 @@ func DeleteCSRFCookie(resp http.ResponseWriter) {
// SetCookie set the cookies // SetCookie set the cookies
// TODO: Copied from gitea.com/macaron/macaron and should be improved after macaron removed. // TODO: Copied from gitea.com/macaron/macaron and should be improved after macaron removed.
func SetCookie(resp http.ResponseWriter, name string, value string, others ...interface{}) { func SetCookie(resp http.ResponseWriter, name, value string, others ...interface{}) {
cookie := http.Cookie{} cookie := http.Cookie{}
cookie.Name = name cookie.Name = name
cookie.Value = url.QueryEscape(value) cookie.Value = url.QueryEscape(value)

View file

@ -251,7 +251,7 @@ func (r *Route) Any(pattern string, h ...interface{}) {
} }
// Route delegate special methods // Route delegate special methods
func (r *Route) Route(pattern string, methods string, h ...interface{}) { func (r *Route) Route(pattern, methods string, h ...interface{}) {
p := r.getPattern(pattern) p := r.getPattern(pattern)
ms := strings.Split(methods, ",") ms := strings.Split(methods, ",")
var middlewares = r.getMiddlewares(h) var middlewares = r.getMiddlewares(h)

View file

@ -29,7 +29,7 @@ func statusStringToNotificationStatus(status string) models.NotificationStatus {
} }
} }
func statusStringsToNotificationStatuses(statuses []string, defaultStatuses []string) []models.NotificationStatus { func statusStringsToNotificationStatuses(statuses, defaultStatuses []string) []models.NotificationStatus {
if len(statuses) == 0 { if len(statuses) == 0 {
statuses = defaultStatuses statuses = defaultStatuses
} }

View file

@ -41,7 +41,7 @@ const (
) )
// setCompareContext sets context data. // setCompareContext sets context data.
func setCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit, headOwner, headName string) { func setCompareContext(ctx *context.Context, base, head *git.Commit, headOwner, headName string) {
ctx.Data["BaseCommit"] = base ctx.Data["BaseCommit"] = base
ctx.Data["HeadCommit"] = head ctx.Data["HeadCommit"] = head
@ -73,7 +73,7 @@ func RawCommitURL(owner, name string, commit *git.Commit) string {
} }
// setPathsCompareContext sets context data for source and raw paths // setPathsCompareContext sets context data for source and raw paths
func setPathsCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit, headOwner, headName string) { func setPathsCompareContext(ctx *context.Context, base, head *git.Commit, headOwner, headName string) {
ctx.Data["SourcePath"] = SourceCommitURL(headOwner, headName, head) ctx.Data["SourcePath"] = SourceCommitURL(headOwner, headName, head)
ctx.Data["RawPath"] = RawCommitURL(headOwner, headName, head) ctx.Data["RawPath"] = RawCommitURL(headOwner, headName, head)
if base != nil { if base != nil {
@ -849,7 +849,7 @@ func ExcerptBlob(ctx *context.Context) {
ctx.HTML(http.StatusOK, tplBlobExcerpt) ctx.HTML(http.StatusOK, tplBlobExcerpt)
} }
func getExcerptLines(commit *git.Commit, filePath string, idxLeft int, idxRight int, chunkSize int) ([]*gitdiff.DiffLine, error) { func getExcerptLines(commit *git.Commit, filePath string, idxLeft, idxRight, chunkSize int) ([]*gitdiff.DiffLine, error) {
blob, err := commit.Tree.GetBlobByPath(filePath) blob, err := commit.Tree.GetBlobByPath(filePath)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -52,7 +52,7 @@ func renderCommitRights(ctx *context.Context) bool {
// getParentTreeFields returns list of parent tree names and corresponding tree paths // getParentTreeFields returns list of parent tree names and corresponding tree paths
// based on given tree path. // based on given tree path.
func getParentTreeFields(treePath string) (treeNames []string, treePaths []string) { func getParentTreeFields(treePath string) (treeNames, treePaths []string) {
if len(treePath) == 0 { if len(treePath) == 0 {
return treeNames, treePaths return treeNames, treePaths
} }

View file

@ -734,7 +734,7 @@ func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (str
return string(bytes), true return string(bytes), true
} }
func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs []string, possibleFiles []string) { func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs, possibleFiles []string) {
templateCandidates := make([]string, 0, len(possibleFiles)) templateCandidates := make([]string, 0, len(possibleFiles))
if ctx.FormString("template") != "" { if ctx.FormString("template") != "" {
for _, dirName := range possibleDirs { for _, dirName := range possibleDirs {

View file

@ -541,7 +541,7 @@ func handleSignIn(ctx *context.Context, u *user_model.User, remember bool) {
handleSignInFull(ctx, u, remember, true) handleSignInFull(ctx, u, remember, true)
} }
func handleSignInFull(ctx *context.Context, u *user_model.User, remember bool, obeyRedirect bool) string { func handleSignInFull(ctx *context.Context, u *user_model.User, remember, obeyRedirect bool) string {
if remember { if remember {
days := 86400 * setting.LogInRememberDays days := 86400 * setting.LogInRememberDays
ctx.SetCookie(setting.CookieUserName, u.Name, days) ctx.SetCookie(setting.CookieUserName, u.Name, days)

View file

@ -723,7 +723,7 @@ func handleAccessTokenError(ctx *context.Context, acErr AccessTokenError) {
ctx.JSON(http.StatusBadRequest, acErr) ctx.JSON(http.StatusBadRequest, acErr)
} }
func handleServerError(ctx *context.Context, state string, redirectURI string) { func handleServerError(ctx *context.Context, state, redirectURI string) {
handleAuthorizeError(ctx, AuthorizeError{ handleAuthorizeError(ctx, AuthorizeError{
ErrorCode: ErrorCodeServerError, ErrorCode: ErrorCodeServerError,
ErrorDescription: "A server error occurred", ErrorDescription: "A server error occurred",

View file

@ -40,7 +40,7 @@ func NewAttachment(attach *repo_model.Attachment, file io.Reader) (*repo_model.A
} }
// UploadAttachment upload new attachment into storage and update database // UploadAttachment upload new attachment into storage and update database
func UploadAttachment(file io.Reader, actorID, repoID, releaseID int64, fileName string, allowedTypes string) (*repo_model.Attachment, error) { func UploadAttachment(file io.Reader, actorID, repoID, releaseID int64, fileName, allowedTypes string) (*repo_model.Attachment, error) {
buf := make([]byte, 1024) buf := make([]byte, 1024)
n, _ := util.ReadAtMost(file, buf) n, _ := util.ReadAtMost(file, buf)
buf = buf[:n] buf = buf[:n]

View file

@ -111,7 +111,7 @@ func (csv *csvReader) readNextRow() ([]string, error) {
} }
// CreateCsvDiff creates a tabular diff based on two CSV readers. // CreateCsvDiff creates a tabular diff based on two CSV readers.
func CreateCsvDiff(diffFile *DiffFile, baseReader *csv.Reader, headReader *csv.Reader) ([]*TableDiffSection, error) { func CreateCsvDiff(diffFile *DiffFile, baseReader, headReader *csv.Reader) ([]*TableDiffSection, error) {
if baseReader != nil && headReader != nil { if baseReader != nil && headReader != nil {
return createCsvDiff(diffFile, baseReader, headReader) return createCsvDiff(diffFile, baseReader, headReader)
} }
@ -149,7 +149,7 @@ func createCsvDiffSingle(reader *csv.Reader, celltype TableDiffCellType) ([]*Tab
return []*TableDiffSection{{Rows: rows}}, nil return []*TableDiffSection{{Rows: rows}}, nil
} }
func createCsvDiff(diffFile *DiffFile, baseReader *csv.Reader, headReader *csv.Reader) ([]*TableDiffSection, error) { func createCsvDiff(diffFile *DiffFile, baseReader, headReader *csv.Reader) ([]*TableDiffSection, error) {
// Given the baseReader and headReader, we are going to create CSV Reader for each, baseCSVReader and b respectively // Given the baseReader and headReader, we are going to create CSV Reader for each, baseCSVReader and b respectively
baseCSVReader, err := createCsvReader(baseReader, maxRowsToInspect) baseCSVReader, err := createCsvReader(baseReader, maxRowsToInspect)
if err != nil { if err != nil {
@ -346,7 +346,7 @@ func createCsvDiff(diffFile *DiffFile, baseReader *csv.Reader, headReader *csv.R
} }
// getColumnMapping creates a mapping of columns between a and b // getColumnMapping creates a mapping of columns between a and b
func getColumnMapping(baseCSVReader *csvReader, headCSVReader *csvReader) ([]int, []int) { func getColumnMapping(baseCSVReader, headCSVReader *csvReader) ([]int, []int) {
baseRow, _ := baseCSVReader.GetRow(0) baseRow, _ := baseCSVReader.GetRow(0)
headRow, _ := headCSVReader.GetRow(0) headRow, _ := headCSVReader.GetRow(0)

View file

@ -57,7 +57,7 @@ func ToggleAssignee(issue *models.Issue, doer *user_model.User, assigneeID int64
} }
// ReviewRequest add or remove a review request from a user for this PR, and make comment for it. // ReviewRequest add or remove a review request from a user for this PR, and make comment for it.
func ReviewRequest(issue *models.Issue, doer *user_model.User, reviewer *user_model.User, isAdd bool) (comment *models.Comment, err error) { func ReviewRequest(issue *models.Issue, doer, reviewer *user_model.User, isAdd bool) (comment *models.Comment, err error) {
if isAdd { if isAdd {
comment, err = models.AddReviewRequest(issue, reviewer, doer) comment, err = models.AddReviewRequest(issue, reviewer, doer)
} else { } else {

View file

@ -606,7 +606,7 @@ func updateOptionsUnits(opts *base.MigrateOptions, units []string) {
} }
// RestoreRepository restore a repository from the disk directory // RestoreRepository restore a repository from the disk directory
func RestoreRepository(ctx context.Context, baseDir string, ownerName, repoName string, units []string) error { func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string, units []string) error {
doer, err := user_model.GetAdminUser() doer, err := user_model.GetAdminUser()
if err != nil { if err != nil {
return err return err

View file

@ -26,7 +26,7 @@ type RepositoryRestorer struct {
} }
// NewRepositoryRestorer creates a repository restorer which could restore repository from a dumped folder // NewRepositoryRestorer creates a repository restorer which could restore repository from a dumped folder
func NewRepositoryRestorer(ctx context.Context, baseDir string, owner, repoName string) (*RepositoryRestorer, error) { func NewRepositoryRestorer(ctx context.Context, baseDir, owner, repoName string) (*RepositoryRestorer, error) {
baseDir, err := filepath.Abs(baseDir) baseDir, err := filepath.Abs(baseDir)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -22,8 +22,7 @@ import (
) )
// CreateCodeComment creates a comment on the code line // CreateCodeComment creates a comment on the code line
func CreateCodeComment(doer *user_model.User, gitRepo *git.Repository, issue *models.Issue, line int64, content string, treePath string, isReview bool, replyReviewID int64, latestCommitID string) (*models.Comment, error) { func CreateCodeComment(doer *user_model.User, gitRepo *git.Repository, issue *models.Issue, line int64, content, treePath string, isReview bool, replyReviewID int64, latestCommitID string) (*models.Comment, error) {
var ( var (
existsReview bool existsReview bool
err error err error

View file

@ -188,12 +188,12 @@ func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, erro
} }
// CommitTree creates a commit from a given tree for the user with provided message // CommitTree creates a commit from a given tree for the user with provided message
func (t *TemporaryUploadRepository) CommitTree(author, committer *user_model.User, treeHash string, message string, signoff bool) (string, error) { func (t *TemporaryUploadRepository) CommitTree(author, committer *user_model.User, treeHash, message string, signoff bool) (string, error) {
return t.CommitTreeWithDate(author, committer, treeHash, message, signoff, time.Now(), time.Now()) return t.CommitTreeWithDate(author, committer, treeHash, message, signoff, time.Now(), time.Now())
} }
// CommitTreeWithDate creates a commit from a given tree for the user with provided message // CommitTreeWithDate creates a commit from a given tree for the user with provided message
func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *user_model.User, treeHash string, message string, signoff bool, authorDate, committerDate time.Time) (string, error) { func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *user_model.User, treeHash, message string, signoff bool, authorDate, committerDate time.Time) (string, error) {
authorSig := author.NewGitSig() authorSig := author.NewGitSig()
committerSig := committer.NewGitSig() committerSig := committer.NewGitSig()
@ -263,7 +263,7 @@ func (t *TemporaryUploadRepository) CommitTreeWithDate(author, committer *user_m
} }
// Push the provided commitHash to the repository branch by the provided user // Push the provided commitHash to the repository branch by the provided user
func (t *TemporaryUploadRepository) Push(doer *user_model.User, commitHash string, branch string) error { func (t *TemporaryUploadRepository) Push(doer *user_model.User, commitHash, branch string) error {
// Because calls hooks we need to pass in the environment // Because calls hooks we need to pass in the environment
env := models.PushingEnvironment(doer, t.repo) env := models.PushingEnvironment(doer, t.repo)
if err := git.Push(t.gitRepo.Ctx, t.basePath, git.PushOptions{ if err := git.Push(t.gitRepo.Ctx, t.basePath, git.PushOptions{

View file

@ -442,7 +442,7 @@ func CreateOrUpdateRepoFile(repo *repo_model.Repository, doer *user_model.User,
} }
// VerifyBranchProtection verify the branch protection for modifying the given treePath on the given branch // VerifyBranchProtection verify the branch protection for modifying the given treePath on the given branch
func VerifyBranchProtection(repo *repo_model.Repository, doer *user_model.User, branchName string, treePath string) error { func VerifyBranchProtection(repo *repo_model.Repository, doer *user_model.User, branchName, treePath string) error {
protectedBranch, err := models.GetProtectedBranchBy(repo.ID, branchName) protectedBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
if err != nil { if err != nil {
return err return err

View file

@ -18,12 +18,12 @@ import (
type linkFormatter = func(string, string) string type linkFormatter = func(string, string) string
// noneLinkFormatter does not create a link but just returns the text // noneLinkFormatter does not create a link but just returns the text
func noneLinkFormatter(url string, text string) string { func noneLinkFormatter(url, text string) string {
return text return text
} }
// htmlLinkFormatter creates a HTML link // htmlLinkFormatter creates a HTML link
func htmlLinkFormatter(url string, text string) string { func htmlLinkFormatter(url, text string) string {
return fmt.Sprintf(`<a href="%s">%s</a>`, html.EscapeString(url), html.EscapeString(text)) return fmt.Sprintf(`<a href="%s">%s</a>`, html.EscapeString(url), html.EscapeString(text))
} }

View file

@ -87,7 +87,7 @@ func (m *MatrixPayloadUnsafe) JSONPayload() ([]byte, error) {
} }
// MatrixLinkFormatter creates a link compatible with Matrix // MatrixLinkFormatter creates a link compatible with Matrix
func MatrixLinkFormatter(url string, text string) string { func MatrixLinkFormatter(url, text string) string {
return fmt.Sprintf(`<a href="%s">%s</a>`, html.EscapeString(url), html.EscapeString(text)) return fmt.Sprintf(`<a href="%s">%s</a>`, html.EscapeString(url), html.EscapeString(text))
} }

View file

@ -85,7 +85,7 @@ func SlackShortTextFormatter(s string) string {
} }
// SlackLinkFormatter creates a link compatible with slack // SlackLinkFormatter creates a link compatible with slack
func SlackLinkFormatter(url string, text string) string { func SlackLinkFormatter(url, text string) string {
return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text)) return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text))
} }