pull/7947/merge
dependabot[bot] 2025-04-02 14:43:13 +00:00 committed by GitHub
commit b75a89e5fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
37 changed files with 540 additions and 569 deletions

View File

@ -34,7 +34,7 @@ jobs:
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: 1.23.x
go-version: 1.24.x
- name: Install Task
uses: arduino/setup-task@v2
with:
@ -52,7 +52,7 @@ jobs:
exit 1
fi
- name: Run golangci-lint
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v7
with:
version: latest
args: --timeout=30m
@ -61,7 +61,7 @@ jobs:
name: Test
strategy:
matrix:
go-version: [ 1.23.x ]
go-version: [ 1.24.x ]
platform: [ ubuntu-latest, macos-latest ]
runs-on: ${{ matrix.platform }}
steps:
@ -101,7 +101,7 @@ jobs:
name: Test Windows
strategy:
matrix:
go-version: [ 1.23.x ]
go-version: [ 1.24.x ]
platform: [ windows-latest ]
runs-on: ${{ matrix.platform }}
steps:
@ -139,7 +139,7 @@ jobs:
name: Postgres
strategy:
matrix:
go-version: [ 1.23.x ]
go-version: [ 1.24.x ]
platform: [ ubuntu-latest ]
runs-on: ${{ matrix.platform }}
services:
@ -175,7 +175,7 @@ jobs:
name: MySQL
strategy:
matrix:
go-version: [ 1.23.x ]
go-version: [ 1.24.x ]
platform: [ ubuntu-20.04 ]
runs-on: ${{ matrix.platform }}
steps:
@ -200,7 +200,7 @@ jobs:
name: SQLite - Go
strategy:
matrix:
go-version: [ 1.23.x ]
go-version: [ 1.24.x ]
platform: [ ubuntu-latest ]
runs-on: ${{ matrix.platform }}
steps:

View File

@ -1,29 +1,41 @@
linters-settings:
staticcheck:
checks: [
"all",
"-SA1019" # There are valid use cases of strings.Title
]
nakedret:
max-func-lines: 0 # Disallow any unnamed return statement
govet:
disable:
# printf: non-constant format string in call to fmt.Errorf (govet)
# showing up since golangci-lint version 1.60.1
- printf
version: "2"
linters:
enable:
- unused
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- nakedret
- gofmt
- rowserrcheck
- unconvert
- goimports
- unparam
settings:
govet:
disable:
# printf: non-constant format string in call to fmt.Errorf (govet)
# showing up since golangci-lint version 1.60.1
- printf
staticcheck:
checks:
- all
- "-SA1019" # This project is under active refactoring and not all code is up to date.
- "-QF1001" # I'm a math noob
nakedret:
max-func-lines: 0 # Disallow any unnamed return statement
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofmt
- goimports
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$

View File

@ -10,7 +10,7 @@ All notable changes to Gogs are documented in this file.
### Changed
- The required Go version to compile source code changed to 1.23.4.
- The required Go version to compile source code changed to 1.24.
- The build tag `cert` has been removed, and the `gogs cert` subcommand is now always available. [#7883](https://github.com/gogs/gogs/pull/7883)
### Fixed

18
go.mod
View File

@ -1,6 +1,6 @@
module gogs.io/gogs
go 1.23.4
go 1.24
require (
github.com/Masterminds/semver/v3 v3.3.1
@ -55,7 +55,7 @@ require (
gorm.io/driver/sqlite v1.4.2
gorm.io/driver/sqlserver v1.4.1
gorm.io/gorm v1.25.12
modernc.org/sqlite v1.36.0
modernc.org/sqlite v1.37.0
unknwon.dev/clog/v2 v2.2.0
xorm.io/builder v0.3.6
xorm.io/core v0.7.2
@ -121,19 +121,19 @@ require (
go.bobheadxi.dev/streamline v1.2.1 // indirect
go.opentelemetry.io/otel v1.11.0 // indirect
go.opentelemetry.io/otel/trace v1.11.0 // indirect
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0 // indirect
golang.org/x/mod v0.19.0 // indirect
golang.org/x/sync v0.11.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect
golang.org/x/mod v0.24.0 // indirect
golang.org/x/sync v0.12.0 // indirect
golang.org/x/sys v0.31.0 // indirect
google.golang.org/protobuf v1.36.1 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/bufio.v1 v1.0.0-20140618132640-567b2bfa514e // indirect
gopkg.in/redis.v2 v2.3.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.61.13 // indirect
modernc.org/libc v1.62.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.8.2 // indirect
modernc.org/memory v1.9.1 // indirect
)
// +heroku goVersion go1.23
// +heroku goVersion go1.24
// +heroku install ./

48
go.sum
View File

@ -179,8 +179,8 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@ -465,8 +465,8 @@ golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ss
golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0 h1:pVgRXcIictcr+lBQIFeiwuwtDIs4eL21OuM9nyAADmo=
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@ -476,8 +476,8 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@ -524,8 +524,8 @@ golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@ -565,8 +565,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
@ -608,8 +608,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@ -690,26 +690,26 @@ gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
modernc.org/cc/v4 v4.24.4 h1:TFkx1s6dCkQpd6dKurBNmpo+G8Zl4Sq/ztJ+2+DEsh0=
modernc.org/cc/v4 v4.24.4/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.23.16 h1:Z2N+kk38b7SfySC1ZkpGLN2vthNJP1+ZzGZIlH7uBxo=
modernc.org/ccgo/v4 v4.23.16/go.mod h1:nNma8goMTY7aQZQNTyN9AIoJfxav4nvTnvKThAeMDdo=
modernc.org/cc/v4 v4.25.2 h1:T2oH7sZdGvTaie0BRNFbIYsabzCxUQg8nLqCdQ2i0ic=
modernc.org/cc/v4 v4.25.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.25.1 h1:TFSzPrAGmDsdnhT9X2UrcPMI3N/mJ9/X9ykKXwLhDsU=
modernc.org/ccgo/v4 v4.25.1/go.mod h1:njjuAYiPflywOOrm3B7kCB444ONP5pAVr8PIEoE0uDw=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.6.3 h1:aJVhcqAte49LF+mGveZ5KPlsp4tdGdAOT4sipJXADjw=
modernc.org/gc/v2 v2.6.3/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8=
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/libc v1.62.1 h1:s0+fv5E3FymN8eJVmnk0llBe6rOxCu/DEU+XygRbS8s=
modernc.org/libc v1.62.1/go.mod h1:iXhATfJQLjG3NWy56a6WVU73lWOcdYVxsvwCgoPljuo=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.8.2 h1:cL9L4bcoAObu4NkxOlKWBWtNHIsnnACGF/TbqQ6sbcI=
modernc.org/memory v1.8.2/go.mod h1:ZbjSvMO5NQ1A2i3bWeDiVMxIorXwdClKE/0SZ+BMotU=
modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g=
modernc.org/memory v1.9.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.36.0 h1:EQXNRn4nIS+gfsKeUTymHIz1waxuv5BzU7558dHSfH8=
modernc.org/sqlite v1.36.0/go.mod h1:7MPwH7Z6bREicF9ZVUR78P1IKuxfZ8mRIDHD0iD+8TU=
modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI=
modernc.org/sqlite v1.37.0/go.mod h1:5YiWv+YviqGMuGw4V+PNplcyaJ5v+vQd7TQOgkACoJM=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=

View File

@ -11,7 +11,7 @@ import (
"fmt"
"strings"
ldap "github.com/go-ldap/ldap/v3"
"github.com/go-ldap/ldap/v3"
log "unknwon.dev/clog/v2"
)
@ -166,7 +166,7 @@ func dial(ls *Config) (*ldap.Conn, error) {
conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
if err != nil {
return nil, fmt.Errorf("Dial: %v", err)
return nil, fmt.Errorf("dial: %v", err)
}
if ls.SecurityProtocol == SecurityProtocolStartTLS {

View File

@ -78,12 +78,12 @@ func runImportLocale(c *cli.Context) error {
// this breaks INI parser, we need to fix that.
sr, err := os.Open(source)
if err != nil {
return fmt.Errorf("Open: %v", err)
return fmt.Errorf("open: %v", err)
}
tw, err := os.Create(target)
if err != nil {
return fmt.Errorf("Create: %v", err)
return fmt.Errorf("create: %v", err)
}
scanner := bufio.NewScanner(sr)

View File

@ -96,15 +96,6 @@ func (c *Context) UserID() int64 {
return c.User.ID
}
// HasError returns true if error occurs in form validation.
func (c *Context) HasApiError() bool {
hasErr, ok := c.Data["HasError"]
if !ok {
return false
}
return hasErr.(bool)
}
func (c *Context) GetErrMsg() string {
return c.Data["ErrorMsg"].(string)
}

View File

@ -49,8 +49,8 @@ func AttachmentLocalPath(uuid string) string {
}
// LocalPath returns where attachment is stored in local file system.
func (attach *Attachment) LocalPath() string {
return AttachmentLocalPath(attach.UUID)
func (a *Attachment) LocalPath() string {
return AttachmentLocalPath(a.UUID)
}
// NewAttachment creates a new attachment object.
@ -72,9 +72,9 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment,
defer fw.Close()
if _, err = fw.Write(buf); err != nil {
return nil, fmt.Errorf("Write: %v", err)
return nil, fmt.Errorf("write: %v", err)
} else if _, err = io.Copy(fw, file); err != nil {
return nil, fmt.Errorf("Copy: %v", err)
return nil, fmt.Errorf("copy: %v", err)
}
if _, err := x.Insert(attach); err != nil {
@ -183,8 +183,8 @@ func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
}
// DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueId)
func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueID)
if err != nil {
return 0, err
}
@ -193,8 +193,8 @@ func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
}
// DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentId)
func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentID)
if err != nil {
return 0, err
}

View File

@ -166,21 +166,21 @@ func (c *Comment) EventTag() string {
// mailParticipants sends new comment emails to repository watchers
// and mentioned people.
func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
mentions := markup.FindAllMentions(cmt.Content)
if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
func (c *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
mentions := markup.FindAllMentions(c.Content)
if err = updateIssueMentions(e, c.IssueID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
}
switch opType {
case ActionCommentIssue:
issue.Content = cmt.Content
issue.Content = c.Content
case ActionCloseIssue:
issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
case ActionReopenIssue:
issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
}
if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
if err = mailIssueCommentToParticipants(issue, c.Poster, mentions); err != nil {
log.Error("mailIssueCommentToParticipants: %v", err)
}

View File

@ -6,7 +6,7 @@ package errors
import "errors"
var InternalServerError = errors.New("internal server error")
var ErrInternalServerError = errors.New("internal server error")
// New is a wrapper of real errors.New function.
func New(text string) error {

View File

@ -354,7 +354,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if issue.IsPull {
@ -485,7 +485,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if issue.IsPull {
@ -770,11 +770,11 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
LableIDs: labelIDs,
Attachments: uuids,
}); err != nil {
return fmt.Errorf("newIssue: %v", err)
return fmt.Errorf("new issue: %v", err)
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if err = NotifyWatchers(&Action{
@ -1108,9 +1108,9 @@ func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
}
// PairsContains returns true when pairs list contains given issue.
func PairsContains(ius []*IssueUser, issueId, uid int64) int {
func PairsContains(ius []*IssueUser, issueID, uid int64) int {
for i := range ius {
if ius[i].IssueID == issueId &&
if ius[i].IssueID == issueID &&
ius[i].UserID == uid {
return i
}

View File

@ -65,17 +65,17 @@ type Label struct {
IsChecked bool `xorm:"-" json:"-" gorm:"-"`
}
func (label *Label) APIFormat() *api.Label {
func (l *Label) APIFormat() *api.Label {
return &api.Label{
ID: label.ID,
Name: label.Name,
Color: strings.TrimLeft(label.Color, "#"),
ID: l.ID,
Name: l.Name,
Color: strings.TrimLeft(l.Color, "#"),
}
}
// CalOpenIssues calculates the open issues of label.
func (label *Label) CalOpenIssues() {
label.NumOpenIssues = label.NumIssues - label.NumClosedIssues
func (l *Label) CalOpenIssues() {
l.NumOpenIssues = l.NumIssues - l.NumClosedIssues
}
// ForegroundColor calculates the text color for labels based

View File

@ -27,25 +27,25 @@ type mailerUser struct {
user *User
}
func (this mailerUser) ID() int64 {
return this.user.ID
func (mu mailerUser) ID() int64 {
return mu.user.ID
}
func (this mailerUser) DisplayName() string {
return this.user.DisplayName()
func (mu mailerUser) DisplayName() string {
return mu.user.DisplayName()
}
func (this mailerUser) Email() string {
return this.user.Email
func (mu mailerUser) Email() string {
return mu.user.Email
}
func (this mailerUser) GenerateEmailActivateCode(email string) string {
func (mu mailerUser) GenerateEmailActivateCode(email string) string {
return userutil.GenerateActivateCode(
this.user.ID,
mu.user.ID,
email,
this.user.Name,
this.user.Password,
this.user.Rands,
mu.user.Name,
mu.user.Password,
mu.user.Rands,
)
}
@ -58,16 +58,16 @@ type mailerRepo struct {
repo *Repository
}
func (this mailerRepo) FullName() string {
return this.repo.FullName()
func (mr mailerRepo) FullName() string {
return mr.repo.FullName()
}
func (this mailerRepo) HTMLURL() string {
return this.repo.HTMLURL()
func (mr mailerRepo) HTMLURL() string {
return mr.repo.HTMLURL()
}
func (this mailerRepo) ComposeMetas() map[string]string {
return this.repo.ComposeMetas()
func (mr mailerRepo) ComposeMetas() map[string]string {
return mr.repo.ComposeMetas()
}
func NewMailerRepo(repo *Repository) email.Repository {
@ -79,16 +79,16 @@ type mailerIssue struct {
issue *Issue
}
func (this mailerIssue) MailSubject() string {
return this.issue.MailSubject()
func (mi mailerIssue) MailSubject() string {
return mi.issue.MailSubject()
}
func (this mailerIssue) Content() string {
return this.issue.Content
func (mi mailerIssue) Content() string {
return mi.issue.Content
}
func (this mailerIssue) HTMLURL() string {
return this.issue.HTMLURL()
func (mi mailerIssue) HTMLURL() string {
return mi.issue.HTMLURL()
}
func NewMailerIssue(issue *Issue) email.Issue {

View File

@ -261,14 +261,14 @@ func IsOrganizationOwner(orgID, userID int64) bool {
}
// IsOrganizationMember returns true if given user is member of organization.
func IsOrganizationMember(orgId, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
func IsOrganizationMember(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).Get(new(OrgUser))
return has
}
// IsPublicMembership returns true if given user public his/her membership.
func IsPublicMembership(orgId, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
func IsPublicMembership(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).And("is_public=?", true).Get(new(OrgUser))
return has
}

View File

@ -213,49 +213,49 @@ type Repository struct {
UpdatedUnix int64
}
func (repo *Repository) BeforeInsert() {
repo.CreatedUnix = time.Now().Unix()
repo.UpdatedUnix = repo.CreatedUnix
func (r *Repository) BeforeInsert() {
r.CreatedUnix = time.Now().Unix()
r.UpdatedUnix = r.CreatedUnix
}
func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
func (r *Repository) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "default_branch":
// FIXME: use db migration to solve all at once.
if repo.DefaultBranch == "" {
repo.DefaultBranch = conf.Repository.DefaultBranch
if r.DefaultBranch == "" {
r.DefaultBranch = conf.Repository.DefaultBranch
}
case "num_closed_issues":
repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
r.NumOpenIssues = r.NumIssues - r.NumClosedIssues
case "num_closed_pulls":
repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
r.NumOpenPulls = r.NumPulls - r.NumClosedPulls
case "num_closed_milestones":
repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
r.NumOpenMilestones = r.NumMilestones - r.NumClosedMilestones
case "external_tracker_style":
if repo.ExternalTrackerStyle == "" {
repo.ExternalTrackerStyle = markup.IssueNameStyleNumeric
if r.ExternalTrackerStyle == "" {
r.ExternalTrackerStyle = markup.IssueNameStyleNumeric
}
case "created_unix":
repo.Created = time.Unix(repo.CreatedUnix, 0).Local()
r.Created = time.Unix(r.CreatedUnix, 0).Local()
case "updated_unix":
repo.Updated = time.Unix(repo.UpdatedUnix, 0)
r.Updated = time.Unix(r.UpdatedUnix, 0)
}
}
func (repo *Repository) loadAttributes(e Engine) (err error) {
if repo.Owner == nil {
repo.Owner, err = getUserByID(e, repo.OwnerID)
func (r *Repository) loadAttributes(e Engine) (err error) {
if r.Owner == nil {
r.Owner, err = getUserByID(e, r.OwnerID)
if err != nil {
return fmt.Errorf("getUserByID [%d]: %v", repo.OwnerID, err)
return fmt.Errorf("getUserByID [%d]: %v", r.OwnerID, err)
}
}
if repo.IsFork && repo.BaseRepo == nil {
repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
if r.IsFork && r.BaseRepo == nil {
r.BaseRepo, err = getRepositoryByID(e, r.ForkID)
if err != nil {
if IsErrRepoNotExist(err) {
repo.IsFork = false
repo.ForkID = 0
r.IsFork = false
r.ForkID = 0
} else {
return fmt.Errorf("get fork repository by ID: %v", err)
}
@ -265,57 +265,57 @@ func (repo *Repository) loadAttributes(e Engine) (err error) {
return nil
}
func (repo *Repository) LoadAttributes() error {
return repo.loadAttributes(x)
func (r *Repository) LoadAttributes() error {
return r.loadAttributes(x)
}
// IsPartialPublic returns true if repository is public or allow public access to wiki or issues.
func (repo *Repository) IsPartialPublic() bool {
return !repo.IsPrivate || repo.AllowPublicWiki || repo.AllowPublicIssues
func (r *Repository) IsPartialPublic() bool {
return !r.IsPrivate || r.AllowPublicWiki || r.AllowPublicIssues
}
func (repo *Repository) CanGuestViewWiki() bool {
return repo.EnableWiki && !repo.EnableExternalWiki && repo.AllowPublicWiki
func (r *Repository) CanGuestViewWiki() bool {
return r.EnableWiki && !r.EnableExternalWiki && r.AllowPublicWiki
}
func (repo *Repository) CanGuestViewIssues() bool {
return repo.EnableIssues && !repo.EnableExternalTracker && repo.AllowPublicIssues
func (r *Repository) CanGuestViewIssues() bool {
return r.EnableIssues && !r.EnableExternalTracker && r.AllowPublicIssues
}
// MustOwner always returns a valid *User object to avoid conceptually impossible error handling.
// It creates a fake object that contains error details when error occurs.
func (repo *Repository) MustOwner() *User {
return repo.mustOwner(x)
func (r *Repository) MustOwner() *User {
return r.mustOwner(x)
}
func (repo *Repository) FullName() string {
return repo.MustOwner().Name + "/" + repo.Name
func (r *Repository) FullName() string {
return r.MustOwner().Name + "/" + r.Name
}
// Deprecated: Use repoutil.HTMLURL instead.
func (repo *Repository) HTMLURL() string {
return conf.Server.ExternalURL + repo.FullName()
func (r *Repository) HTMLURL() string {
return conf.Server.ExternalURL + r.FullName()
}
// CustomAvatarPath returns repository custom avatar file path.
func (repo *Repository) CustomAvatarPath() string {
return filepath.Join(conf.Picture.RepositoryAvatarUploadPath, com.ToStr(repo.ID))
func (r *Repository) CustomAvatarPath() string {
return filepath.Join(conf.Picture.RepositoryAvatarUploadPath, com.ToStr(r.ID))
}
// RelAvatarLink returns relative avatar link to the site domain,
// which includes app sub-url as prefix.
// Since Gravatar support not needed here - just check for image path.
func (repo *Repository) RelAvatarLink() string {
defaultImgUrl := ""
if !com.IsExist(repo.CustomAvatarPath()) {
return defaultImgUrl
func (r *Repository) RelAvatarLink() string {
defaultImgURL := ""
if !com.IsExist(r.CustomAvatarPath()) {
return defaultImgURL
}
return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, REPO_AVATAR_URL_PREFIX, repo.ID)
return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, REPO_AVATAR_URL_PREFIX, r.ID)
}
// AvatarLink returns repository avatar absolute link.
func (repo *Repository) AvatarLink() string {
link := repo.RelAvatarLink()
func (r *Repository) AvatarLink() string {
link := r.RelAvatarLink()
if link[0] == '/' && link[1] != '/' {
return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
}
@ -324,14 +324,14 @@ func (repo *Repository) AvatarLink() string {
// UploadAvatar saves custom avatar for repository.
// FIXME: split uploads to different subdirs in case we have massive number of repositories.
func (repo *Repository) UploadAvatar(data []byte) error {
func (r *Repository) UploadAvatar(data []byte) error {
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return fmt.Errorf("decode image: %v", err)
}
_ = os.MkdirAll(conf.Picture.RepositoryAvatarUploadPath, os.ModePerm)
fw, err := os.Create(repo.CustomAvatarPath())
fw, err := os.Create(r.CustomAvatarPath())
if err != nil {
return fmt.Errorf("create custom avatar directory: %v", err)
}
@ -346,14 +346,14 @@ func (repo *Repository) UploadAvatar(data []byte) error {
}
// DeleteAvatar deletes the repository custom avatar.
func (repo *Repository) DeleteAvatar() error {
log.Trace("DeleteAvatar [%d]: %s", repo.ID, repo.CustomAvatarPath())
if err := os.Remove(repo.CustomAvatarPath()); err != nil {
func (r *Repository) DeleteAvatar() error {
log.Trace("DeleteAvatar [%d]: %s", r.ID, r.CustomAvatarPath())
if err := os.Remove(r.CustomAvatarPath()); err != nil {
return err
}
repo.UseCustomAvatar = false
return UpdateRepository(repo, false)
r.UseCustomAvatar = false
return UpdateRepository(r, false)
}
// This method assumes following fields have been assigned with valid values:
@ -361,133 +361,133 @@ func (repo *Repository) DeleteAvatar() error {
// Arguments that are allowed to be nil: permission
//
// Deprecated: Use APIFormat instead.
func (repo *Repository) APIFormatLegacy(permission *api.Permission, user ...*User) *api.Repository {
cloneLink := repo.CloneLink()
func (r *Repository) APIFormatLegacy(permission *api.Permission, user ...*User) *api.Repository {
cloneLink := r.CloneLink()
apiRepo := &api.Repository{
ID: repo.ID,
Owner: repo.Owner.APIFormat(),
Name: repo.Name,
FullName: repo.FullName(),
Description: repo.Description,
Private: repo.IsPrivate,
Fork: repo.IsFork,
Empty: repo.IsBare,
Mirror: repo.IsMirror,
Size: repo.Size,
HTMLURL: repo.HTMLURL(),
ID: r.ID,
Owner: r.Owner.APIFormat(),
Name: r.Name,
FullName: r.FullName(),
Description: r.Description,
Private: r.IsPrivate,
Fork: r.IsFork,
Empty: r.IsBare,
Mirror: r.IsMirror,
Size: r.Size,
HTMLURL: r.HTMLURL(),
SSHURL: cloneLink.SSH,
CloneURL: cloneLink.HTTPS,
Website: repo.Website,
Stars: repo.NumStars,
Forks: repo.NumForks,
Watchers: repo.NumWatches,
OpenIssues: repo.NumOpenIssues,
DefaultBranch: repo.DefaultBranch,
Created: repo.Created,
Updated: repo.Updated,
Website: r.Website,
Stars: r.NumStars,
Forks: r.NumForks,
Watchers: r.NumWatches,
OpenIssues: r.NumOpenIssues,
DefaultBranch: r.DefaultBranch,
Created: r.Created,
Updated: r.Updated,
Permissions: permission,
// Reserved for go-gogs-client change
// AvatarUrl: repo.AvatarLink(),
// AvatarUrl: r.AvatarLink(),
}
if repo.IsFork {
if r.IsFork {
p := &api.Permission{Pull: true}
if len(user) != 0 {
accessMode := Handle.Permissions().AccessMode(
context.TODO(),
user[0].ID,
repo.ID,
r.ID,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
)
p.Admin = accessMode >= AccessModeAdmin
p.Push = accessMode >= AccessModeWrite
}
apiRepo.Parent = repo.BaseRepo.APIFormatLegacy(p)
apiRepo.Parent = r.BaseRepo.APIFormatLegacy(p)
}
return apiRepo
}
func (repo *Repository) getOwner(e Engine) (err error) {
if repo.Owner != nil {
func (r *Repository) getOwner(e Engine) (err error) {
if r.Owner != nil {
return nil
}
repo.Owner, err = getUserByID(e, repo.OwnerID)
r.Owner, err = getUserByID(e, r.OwnerID)
return err
}
func (repo *Repository) GetOwner() error {
return repo.getOwner(x)
func (r *Repository) GetOwner() error {
return r.getOwner(x)
}
func (repo *Repository) mustOwner(e Engine) *User {
if err := repo.getOwner(e); err != nil {
func (r *Repository) mustOwner(e Engine) *User {
if err := r.getOwner(e); err != nil {
return &User{
Name: "error",
FullName: err.Error(),
}
}
return repo.Owner
return r.Owner
}
func (repo *Repository) UpdateSize() error {
countObject, err := git.CountObjects(repo.RepoPath())
func (r *Repository) UpdateSize() error {
countObject, err := git.CountObjects(r.RepoPath())
if err != nil {
return fmt.Errorf("count repository objects: %v", err)
}
repo.Size = countObject.Size + countObject.SizePack
if _, err = x.Id(repo.ID).Cols("size").Update(repo); err != nil {
r.Size = countObject.Size + countObject.SizePack
if _, err = x.Id(r.ID).Cols("size").Update(r); err != nil {
return fmt.Errorf("update size: %v", err)
}
return nil
}
// ComposeMetas composes a map of metas for rendering SHA1 URL and external issue tracker URL.
func (repo *Repository) ComposeMetas() map[string]string {
if repo.ExternalMetas != nil {
return repo.ExternalMetas
func (r *Repository) ComposeMetas() map[string]string {
if r.ExternalMetas != nil {
return r.ExternalMetas
}
repo.ExternalMetas = map[string]string{
"repoLink": repo.Link(),
r.ExternalMetas = map[string]string{
"repoLink": r.Link(),
}
if repo.EnableExternalTracker {
repo.ExternalMetas["user"] = repo.MustOwner().Name
repo.ExternalMetas["repo"] = repo.Name
repo.ExternalMetas["format"] = repo.ExternalTrackerFormat
if r.EnableExternalTracker {
r.ExternalMetas["user"] = r.MustOwner().Name
r.ExternalMetas["r"] = r.Name
r.ExternalMetas["format"] = r.ExternalTrackerFormat
switch repo.ExternalTrackerStyle {
switch r.ExternalTrackerStyle {
case markup.IssueNameStyleAlphanumeric:
repo.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
r.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
default:
repo.ExternalMetas["style"] = markup.IssueNameStyleNumeric
r.ExternalMetas["style"] = markup.IssueNameStyleNumeric
}
}
return repo.ExternalMetas
return r.ExternalMetas
}
// DeleteWiki removes the actual and local copy of repository wiki.
func (repo *Repository) DeleteWiki() {
wikiPaths := []string{repo.WikiPath(), repo.LocalWikiPath()}
func (r *Repository) DeleteWiki() {
wikiPaths := []string{r.WikiPath(), r.LocalWikiPath()}
for _, wikiPath := range wikiPaths {
RemoveAllWithNotice("Delete repository wiki", wikiPath)
}
}
// getUsersWithAccesMode returns users that have at least given access mode to the repository.
func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
if err = repo.getOwner(e); err != nil {
func (r *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
if err = r.getOwner(e); err != nil {
return nil, err
}
accesses := make([]*Access, 0, 10)
if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
if err = e.Where("repo_id = ? AND mode >= ?", r.ID, mode).Find(&accesses); err != nil {
return nil, err
}
@ -509,35 +509,35 @@ func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*U
u.FullName = markup.Sanitize(u.FullName)
}
}
if !repo.Owner.IsOrganization() {
users = append(users, repo.Owner)
if !r.Owner.IsOrganization() {
users = append(users, r.Owner)
}
return users, nil
}
// getAssignees returns a list of users who can be assigned to issues in this repository.
func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
return repo.getUsersWithAccesMode(e, AccessModeRead)
func (r *Repository) getAssignees(e Engine) (_ []*User, err error) {
return r.getUsersWithAccesMode(e, AccessModeRead)
}
// GetAssignees returns all users that have read access and can be assigned to issues
// of the repository,
func (repo *Repository) GetAssignees() (_ []*User, err error) {
return repo.getAssignees(x)
func (r *Repository) GetAssignees() (_ []*User, err error) {
return r.getAssignees(x)
}
// GetAssigneeByID returns the user that has write access of repository by given ID.
func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
func (r *Repository) GetAssigneeByID(userID int64) (*User, error) {
ctx := context.TODO()
if !Handle.Permissions().Authorize(
ctx,
userID,
repo.ID,
r.ID,
AccessModeRead,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
) {
return nil, ErrUserNotExist{args: errutil.Args{"userID": userID}}
@ -546,96 +546,96 @@ func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
}
// GetWriters returns all users that have write access to the repository.
func (repo *Repository) GetWriters() (_ []*User, err error) {
return repo.getUsersWithAccesMode(x, AccessModeWrite)
func (r *Repository) GetWriters() (_ []*User, err error) {
return r.getUsersWithAccesMode(x, AccessModeWrite)
}
// GetMilestoneByID returns the milestone belongs to repository by given ID.
func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
return GetMilestoneByRepoID(repo.ID, milestoneID)
func (r *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
return GetMilestoneByRepoID(r.ID, milestoneID)
}
// IssueStats returns number of open and closed repository issues by given filter mode.
func (repo *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
return GetRepoIssueStats(repo.ID, userID, filterMode, isPull)
func (r *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
return GetRepoIssueStats(r.ID, userID, filterMode, isPull)
}
func (repo *Repository) GetMirror() (err error) {
repo.Mirror, err = GetMirrorByRepoID(repo.ID)
func (r *Repository) GetMirror() (err error) {
r.Mirror, err = GetMirrorByRepoID(r.ID)
return err
}
func (repo *Repository) repoPath(e Engine) string {
return RepoPath(repo.mustOwner(e).Name, repo.Name)
func (r *Repository) repoPath(e Engine) string {
return RepoPath(r.mustOwner(e).Name, r.Name)
}
// Deprecated: Use repoutil.RepositoryPath instead.
func (repo *Repository) RepoPath() string {
return repo.repoPath(x)
func (r *Repository) RepoPath() string {
return r.repoPath(x)
}
func (repo *Repository) GitConfigPath() string {
return filepath.Join(repo.RepoPath(), "config")
func (r *Repository) GitConfigPath() string {
return filepath.Join(r.RepoPath(), "config")
}
func (repo *Repository) RelLink() string {
return "/" + repo.FullName()
func (r *Repository) RelLink() string {
return "/" + r.FullName()
}
func (repo *Repository) Link() string {
return conf.Server.Subpath + "/" + repo.FullName()
func (r *Repository) Link() string {
return conf.Server.Subpath + "/" + r.FullName()
}
// Deprecated: Use repoutil.ComparePath instead.
func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
func (r *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", r.MustOwner().Name, r.Name, oldCommitID, newCommitID)
}
func (repo *Repository) HasAccess(userID int64) bool {
return Handle.Permissions().Authorize(context.TODO(), userID, repo.ID, AccessModeRead,
func (r *Repository) HasAccess(userID int64) bool {
return Handle.Permissions().Authorize(context.TODO(), userID, r.ID, AccessModeRead,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
)
}
func (repo *Repository) IsOwnedBy(userID int64) bool {
return repo.OwnerID == userID
func (r *Repository) IsOwnedBy(userID int64) bool {
return r.OwnerID == userID
}
// CanBeForked returns true if repository meets the requirements of being forked.
func (repo *Repository) CanBeForked() bool {
return !repo.IsBare
func (r *Repository) CanBeForked() bool {
return !r.IsBare
}
// CanEnablePulls returns true if repository meets the requirements of accepting pulls.
func (repo *Repository) CanEnablePulls() bool {
return !repo.IsMirror && !repo.IsBare
func (r *Repository) CanEnablePulls() bool {
return !r.IsMirror && !r.IsBare
}
// AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
func (repo *Repository) AllowsPulls() bool {
return repo.CanEnablePulls() && repo.EnablePulls
func (r *Repository) AllowsPulls() bool {
return r.CanEnablePulls() && r.EnablePulls
}
func (repo *Repository) IsBranchRequirePullRequest(name string) bool {
return IsBranchOfRepoRequirePullRequest(repo.ID, name)
func (r *Repository) IsBranchRequirePullRequest(name string) bool {
return IsBranchOfRepoRequirePullRequest(r.ID, name)
}
// CanEnableEditor returns true if repository meets the requirements of web editor.
func (repo *Repository) CanEnableEditor() bool {
return !repo.IsMirror
func (r *Repository) CanEnableEditor() bool {
return !r.IsMirror
}
// FIXME: should have a mutex to prevent producing same index for two issues that are created
// closely enough.
func (repo *Repository) NextIssueIndex() int64 {
return int64(repo.NumIssues+repo.NumPulls) + 1
func (r *Repository) NextIssueIndex() int64 {
return int64(r.NumIssues+r.NumPulls) + 1
}
func (repo *Repository) LocalCopyPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-repo", com.ToStr(repo.ID))
func (r *Repository) LocalCopyPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-r", com.ToStr(r.ID))
}
// UpdateLocalCopy fetches latest changes of given branch from repoPath to localPath.
@ -685,22 +685,22 @@ func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err
}
// UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
func (repo *Repository) UpdateLocalCopyBranch(branch string) error {
return UpdateLocalCopyBranch(repo.RepoPath(), repo.LocalCopyPath(), branch, false)
func (r *Repository) UpdateLocalCopyBranch(branch string) error {
return UpdateLocalCopyBranch(r.RepoPath(), r.LocalCopyPath(), branch, false)
}
// PatchPath returns corresponding patch file path of repository by given issue ID.
func (repo *Repository) PatchPath(index int64) (string, error) {
if err := repo.GetOwner(); err != nil {
func (r *Repository) PatchPath(index int64) (string, error) {
if err := r.GetOwner(); err != nil {
return "", err
}
return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
return filepath.Join(RepoPath(r.Owner.Name, r.Name), "pulls", com.ToStr(index)+".patch"), nil
}
// SavePatch saves patch data to corresponding location by given issue ID.
func (repo *Repository) SavePatch(index int64, patch []byte) error {
patchPath, err := repo.PatchPath(index)
func (r *Repository) SavePatch(index int64, patch []byte) error {
patchPath, err := r.PatchPath(index)
if err != nil {
return fmt.Errorf("PatchPath: %v", err)
}
@ -729,28 +729,28 @@ func IsRepositoryExist(u *User, repoName string) (bool, error) {
}
// Deprecated: Use repoutil.NewCloneLink instead.
func (repo *Repository) cloneLink(isWiki bool) *repoutil.CloneLink {
repoName := repo.Name
func (r *Repository) cloneLink(isWiki bool) *repoutil.CloneLink {
repoName := r.Name
if isWiki {
repoName += ".wiki"
}
repo.Owner = repo.MustOwner()
r.Owner = r.MustOwner()
cl := new(repoutil.CloneLink)
if conf.SSH.Port != 22 {
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, repo.Owner.Name, repoName)
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, r.Owner.Name, repoName)
} else {
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, repo.Owner.Name, repoName)
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, r.Owner.Name, repoName)
}
cl.HTTPS = repoutil.HTTPSCloneURL(repo.Owner.Name, repoName)
cl.HTTPS = repoutil.HTTPSCloneURL(r.Owner.Name, repoName)
return cl
}
// CloneLink returns clone URLs of repository.
//
// Deprecated: Use repoutil.NewCloneLink instead.
func (repo *Repository) CloneLink() (cl *repoutil.CloneLink) {
return repo.cloneLink(false)
func (r *Repository) CloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(false)
}
type MigrateRepoOptions struct {
@ -2389,9 +2389,9 @@ func GetWatchers(repoID int64) ([]*Watch, error) {
}
// Repository.GetWatchers returns range of users watching given repository.
func (repo *Repository) GetWatchers(page int) ([]*User, error) {
func (r *Repository) GetWatchers(page int) ([]*User, error) {
users := make([]*User, 0, ItemsPerPage)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", repo.ID)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", r.ID)
if conf.UsePostgreSQL {
sess = sess.Join("LEFT", "watch", `"user".id=watch.user_id`)
} else {
@ -2489,9 +2489,9 @@ func IsStaring(userID, repoID int64) bool {
return has
}
func (repo *Repository) GetStargazers(page int) ([]*User, error) {
func (r *Repository) GetStargazers(page int) ([]*User, error) {
users := make([]*User, 0, ItemsPerPage)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", repo.ID)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", r.ID)
if conf.UsePostgreSQL {
sess = sess.Join("LEFT", "star", `"user".id=star.uid`)
} else {
@ -2595,14 +2595,14 @@ func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string)
return repo, nil
}
func (repo *Repository) GetForks() ([]*Repository, error) {
forks := make([]*Repository, 0, repo.NumForks)
if err := x.Find(&forks, &Repository{ForkID: repo.ID}); err != nil {
func (r *Repository) GetForks() ([]*Repository, error) {
forks := make([]*Repository, 0, r.NumForks)
if err := x.Find(&forks, &Repository{ForkID: r.ID}); err != nil {
return nil, err
}
for _, fork := range forks {
fork.BaseRepo = repo
fork.BaseRepo = r
}
return forks, nil
}
@ -2615,19 +2615,19 @@ func (repo *Repository) GetForks() ([]*Repository, error) {
// \/ \/ \/ \/ \/
//
func (repo *Repository) CreateNewBranch(oldBranch, newBranch string) (err error) {
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
func (r *Repository) CreateNewBranch(oldBranch, newBranch string) (err error) {
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
if err = discardLocalRepoBranchChanges(localPath, oldBranch); err != nil {
return fmt.Errorf("discard changes in local copy [path: %s, branch: %s]: %v", localPath, oldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(oldBranch); err != nil {
} else if err = r.UpdateLocalCopyBranch(oldBranch); err != nil {
return fmt.Errorf("update branch for local copy [path: %s, branch: %s]: %v", localPath, oldBranch, err)
}
if err = repo.CheckoutNewBranch(oldBranch, newBranch); err != nil {
if err = r.CheckoutNewBranch(oldBranch, newBranch); err != nil {
return fmt.Errorf("create new branch [base: %s, new: %s]: %v", oldBranch, newBranch, err)
}
@ -2639,18 +2639,18 @@ func (repo *Repository) CreateNewBranch(oldBranch, newBranch string) (err error)
}
// Deprecated: Use Perms.SetRepoPerms instead.
func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode) (err error) {
func (r *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode) (err error) {
newAccesses := make([]Access, 0, len(accessMap))
for userID, mode := range accessMap {
newAccesses = append(newAccesses, Access{
UserID: userID,
RepoID: repo.ID,
RepoID: r.ID,
Mode: mode,
})
}
// Delete old accesses and insert new ones for repository.
if _, err = e.Delete(&Access{RepoID: repo.ID}); err != nil {
if _, err = e.Delete(&Access{RepoID: r.ID}); err != nil {
return fmt.Errorf("delete old accesses: %v", err)
} else if _, err = e.Insert(newAccesses); err != nil {
return fmt.Errorf("insert new accesses: %v", err)
@ -2659,8 +2659,8 @@ func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode
}
// refreshCollaboratorAccesses retrieves repository collaborations with their access modes.
func (repo *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int64]AccessMode) error {
collaborations, err := repo.getCollaborations(e)
func (r *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int64]AccessMode) error {
collaborations, err := r.getCollaborations(e)
if err != nil {
return fmt.Errorf("getCollaborations: %v", err)
}
@ -2673,20 +2673,20 @@ func (repo *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int6
// recalculateTeamAccesses recalculates new accesses for teams of an organization
// except the team whose ID is given. It is used to assign a team ID when
// remove repository from that team.
func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err error) {
func (r *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err error) {
accessMap := make(map[int64]AccessMode, 20)
if err = repo.getOwner(e); err != nil {
if err = r.getOwner(e); err != nil {
return err
} else if !repo.Owner.IsOrganization() {
return fmt.Errorf("owner is not an organization: %d", repo.OwnerID)
} else if !r.Owner.IsOrganization() {
return fmt.Errorf("owner is not an organization: %d", r.OwnerID)
}
if err = repo.refreshCollaboratorAccesses(e, accessMap); err != nil {
if err = r.refreshCollaboratorAccesses(e, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
}
if err = repo.Owner.getTeams(e); err != nil {
if err = r.Owner.getTeams(e); err != nil {
return err
}
@ -2700,7 +2700,7 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
return max
}
for _, t := range repo.Owner.Teams {
for _, t := range r.Owner.Teams {
if t.ID == ignTeamID {
continue
}
@ -2709,7 +2709,7 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
// have relations with repository.
if t.IsOwnerTeam() {
t.Authorize = AccessModeOwner
} else if !t.hasRepository(e, repo.ID) {
} else if !t.hasRepository(e, r.ID) {
continue
}
@ -2721,22 +2721,22 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
}
}
return repo.refreshAccesses(e, accessMap)
return r.refreshAccesses(e, accessMap)
}
func (repo *Repository) recalculateAccesses(e Engine) error {
if repo.Owner.IsOrganization() {
return repo.recalculateTeamAccesses(e, 0)
func (r *Repository) recalculateAccesses(e Engine) error {
if r.Owner.IsOrganization() {
return r.recalculateTeamAccesses(e, 0)
}
accessMap := make(map[int64]AccessMode, 10)
if err := repo.refreshCollaboratorAccesses(e, accessMap); err != nil {
if err := r.refreshCollaboratorAccesses(e, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
}
return repo.refreshAccesses(e, accessMap)
return r.refreshAccesses(e, accessMap)
}
// RecalculateAccesses recalculates all accesses for repository.
func (repo *Repository) RecalculateAccesses() error {
return repo.recalculateAccesses(x)
func (r *Repository) RecalculateAccesses() error {
return r.recalculateAccesses(x)
}

View File

@ -64,18 +64,18 @@ func (ErrBranchNotExist) NotFound() bool {
return true
}
func (repo *Repository) GetBranch(name string) (*Branch, error) {
if !git.RepoHasBranch(repo.RepoPath(), name) {
func (r *Repository) GetBranch(name string) (*Branch, error) {
if !git.RepoHasBranch(r.RepoPath(), name) {
return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
}
return &Branch{
RepoPath: repo.RepoPath(),
RepoPath: r.RepoPath(),
Name: name,
}, nil
}
func (repo *Repository) GetBranches() ([]*Branch, error) {
return GetBranchesByPath(repo.RepoPath())
func (r *Repository) GetBranches() ([]*Branch, error) {
return GetBranchesByPath(r.RepoPath())
}
func (br *Branch) GetCommit() (*git.Commit, error) {

View File

@ -47,14 +47,14 @@ func IsCollaborator(repoID, userID int64) bool {
return has
}
func (repo *Repository) IsCollaborator(userID int64) bool {
return IsCollaborator(repo.ID, userID)
func (r *Repository) IsCollaborator(userID int64) bool {
return IsCollaborator(r.ID, userID)
}
// AddCollaborator adds new collaboration to a repository with default access mode.
func (repo *Repository) AddCollaborator(u *User) error {
func (r *Repository) AddCollaborator(u *User) error {
collaboration := &Collaboration{
RepoID: repo.ID,
RepoID: r.ID,
UserID: u.ID,
}
@ -74,16 +74,16 @@ func (repo *Repository) AddCollaborator(u *User) error {
if _, err = sess.Insert(collaboration); err != nil {
return err
} else if err = repo.recalculateAccesses(sess); err != nil {
return fmt.Errorf("recalculateAccesses [repo_id: %v]: %v", repo.ID, err)
} else if err = r.recalculateAccesses(sess); err != nil {
return fmt.Errorf("recalculateAccesses [repo_id: %v]: %v", r.ID, err)
}
return sess.Commit()
}
func (repo *Repository) getCollaborations(e Engine) ([]*Collaboration, error) {
func (r *Repository) getCollaborations(e Engine) ([]*Collaboration, error) {
collaborations := make([]*Collaboration, 0)
return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repo.ID})
return collaborations, e.Find(&collaborations, &Collaboration{RepoID: r.ID})
}
// Collaborator represents a user with collaboration details.
@ -103,8 +103,8 @@ func (c *Collaborator) APIFormat() *api.Collaborator {
}
}
func (repo *Repository) getCollaborators(e Engine) ([]*Collaborator, error) {
collaborations, err := repo.getCollaborations(e)
func (r *Repository) getCollaborators(e Engine) ([]*Collaborator, error) {
collaborations, err := r.getCollaborations(e)
if err != nil {
return nil, fmt.Errorf("getCollaborations: %v", err)
}
@ -124,19 +124,19 @@ func (repo *Repository) getCollaborators(e Engine) ([]*Collaborator, error) {
}
// GetCollaborators returns the collaborators for a repository
func (repo *Repository) GetCollaborators() ([]*Collaborator, error) {
return repo.getCollaborators(x)
func (r *Repository) GetCollaborators() ([]*Collaborator, error) {
return r.getCollaborators(x)
}
// ChangeCollaborationAccessMode sets new access mode for the collaboration.
func (repo *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessMode) error {
func (r *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessMode) error {
// Discard invalid input
if mode <= AccessModeNone || mode > AccessModeOwner {
return nil
}
collaboration := &Collaboration{
RepoID: repo.ID,
RepoID: r.ID,
UserID: userID,
}
has, err := x.Get(collaboration)
@ -152,10 +152,10 @@ func (repo *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessM
collaboration.Mode = mode
// If it's an organizational repository, merge with team access level for highest permission
if repo.Owner.IsOrganization() {
teams, err := GetUserTeams(repo.OwnerID, userID)
if r.Owner.IsOrganization() {
teams, err := GetUserTeams(r.OwnerID, userID)
if err != nil {
return fmt.Errorf("GetUserTeams: [org_id: %d, user_id: %d]: %v", repo.OwnerID, userID, err)
return fmt.Errorf("GetUserTeams: [org_id: %d, user_id: %d]: %v", r.OwnerID, userID, err)
}
for i := range teams {
if mode < teams[i].Authorize {
@ -176,14 +176,14 @@ func (repo *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessM
access := &Access{
UserID: userID,
RepoID: repo.ID,
RepoID: r.ID,
}
has, err = sess.Get(access)
if err != nil {
return fmt.Errorf("get access record: %v", err)
}
if has {
_, err = sess.Exec("UPDATE access SET mode = ? WHERE user_id = ? AND repo_id = ?", mode, userID, repo.ID)
_, err = sess.Exec("UPDATE access SET mode = ? WHERE user_id = ? AND repo_id = ?", mode, userID, r.ID)
} else {
access.Mode = mode
_, err = sess.Insert(access)
@ -221,6 +221,6 @@ func DeleteCollaboration(repo *Repository, userID int64) (err error) {
return sess.Commit()
}
func (repo *Repository) DeleteCollaboration(userID int64) error {
return DeleteCollaboration(repo, userID)
func (r *Repository) DeleteCollaboration(userID int64) error {
return DeleteCollaboration(r, userID)
}

View File

@ -92,13 +92,13 @@ func discardLocalRepoBranchChanges(localPath, branch string) error {
return nil
}
func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
func (r *Repository) DiscardLocalRepoBranchChanges(branch string) error {
return discardLocalRepoBranchChanges(r.LocalCopyPath(), branch)
}
// CheckoutNewBranch checks out to a new branch from the a branch name.
func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
if err := git.Checkout(repo.LocalCopyPath(), newBranch, git.CheckoutOptions{
func (r *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
if err := git.Checkout(r.LocalCopyPath(), newBranch, git.CheckoutOptions{
BaseBranch: oldBranch,
Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second,
}); err != nil {
@ -118,23 +118,23 @@ type UpdateRepoFileOptions struct {
}
// UpdateRepoFile adds or updates a file in repository.
func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
// 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.NewTreeName) {
return errors.Errorf("bad tree path %q", opts.NewTreeName)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
}
repoPath := repo.RepoPath()
localPath := repo.LocalCopyPath()
repoPath := r.RepoPath()
localPath := r.LocalCopyPath()
if opts.OldBranch != opts.NewBranch {
// Directly return error if new branch already exists in the server
@ -151,7 +151,7 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
}
}
if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
}
}
@ -203,11 +203,11 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer,
OwnerName: repo.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt,
RepoID: repo.ID,
RepoName: repo.Name,
RepoPath: repo.RepoPath(),
OwnerName: r.MustOwner().Name,
OwnerSalt: r.MustOwner().Salt,
RepoID: r.ID,
RepoName: r.Name,
RepoPath: r.RepoPath(),
}),
},
},
@ -219,22 +219,22 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
}
// GetDiffPreview produces and returns diff result of a file which is not yet committed.
func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) {
func (r *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) {
// 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(treePath) {
return nil, errors.Errorf("bad tree path %q", treePath)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
} else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(branch); err != nil {
return nil, fmt.Errorf("discard local r branch[%s] changes: %v", branch, err)
} else if err = r.UpdateLocalCopyBranch(branch); err != nil {
return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
}
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
filePath := path.Join(localPath, treePath)
if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return nil, err
@ -257,7 +257,7 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
return nil, fmt.Errorf("start: %v", err)
}
pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", r.RepoPath()), cmd)
defer process.Remove(pid)
diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
@ -288,28 +288,28 @@ type DeleteRepoFileOptions struct {
Message string
}
func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
func (r *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
// 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.TreePath) {
return errors.Errorf("bad tree path %q", opts.TreePath)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
}
if opts.OldBranch != opts.NewBranch {
if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
}
}
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
return fmt.Errorf("remove file %q: %v", opts.TreePath, err)
}
@ -336,11 +336,11 @@ func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (
CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer,
OwnerName: repo.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt,
RepoID: repo.ID,
RepoName: repo.Name,
RepoPath: repo.RepoPath(),
OwnerName: r.MustOwner().Name,
OwnerSalt: r.MustOwner().Salt,
RepoID: r.ID,
RepoName: r.Name,
RepoPath: r.RepoPath(),
}),
},
},
@ -509,7 +509,7 @@ func isRepositoryGitPath(path string) bool {
strings.Contains(path, `.git.\`)
}
func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error {
func (r *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error {
if len(opts.Files) == 0 {
return nil
}
@ -524,22 +524,22 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
}
if opts.OldBranch != opts.NewBranch {
if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
if err = r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
}
}
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
dirPath := path.Join(localPath, opts.TreePath)
if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
return err
@ -588,11 +588,11 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer,
OwnerName: repo.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt,
RepoID: repo.ID,
RepoName: repo.Name,
RepoPath: repo.RepoPath(),
OwnerName: r.MustOwner().Name,
OwnerSalt: r.MustOwner().Salt,
RepoID: r.ID,
RepoName: r.Name,
RepoPath: r.RepoPath(),
}),
},
},

View File

@ -47,6 +47,6 @@ func GetTagsByPath(path string) ([]*Tag, error) {
return tags, nil
}
func (repo *Repository) GetTags() ([]*Tag, error) {
return GetTagsByPath(repo.RepoPath())
func (r *Repository) GetTags() ([]*Tag, error) {
return GetTagsByPath(r.RepoPath())
}

View File

@ -792,13 +792,13 @@ func (s *UsersStore) GetMailableEmailsByUsernames(ctx context.Context, usernames
// IsUsernameUsed returns true if the given username has been used other than
// the excluded user (a non-positive ID effectively meaning check against all
// users).
func (s *UsersStore) IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool {
func (s *UsersStore) IsUsernameUsed(ctx context.Context, username string, excludeUserID int64) bool {
if username == "" {
return false
}
return s.db.WithContext(ctx).
Select("id").
Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserID).
First(&User{}).
Error != gorm.ErrRecordNotFound
}
@ -1425,8 +1425,8 @@ func (u *User) IsFollowing(followID int64) bool {
//
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`.
func (u *User) IsUserOrgOwner(orgId int64) bool {
return IsOrganizationOwner(orgId, u.ID)
func (u *User) IsUserOrgOwner(orgID int64) bool {
return IsOrganizationOwner(orgID, u.ID)
}
// IsPublicMember returns true if the user has public membership of the given
@ -1434,8 +1434,8 @@ func (u *User) IsUserOrgOwner(orgId int64) bool {
//
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`.
func (u *User) IsPublicMember(orgId int64) bool {
return IsPublicMembership(orgId, u.ID)
func (u *User) IsPublicMember(orgID int64) bool {
return IsPublicMembership(orgID, u.ID)
}
// GetOrganizationCount returns the count of organization membership that the

View File

@ -40,8 +40,8 @@ func ToWikiPageName(urlString string) string {
// WikiCloneLink returns clone URLs of repository wiki.
//
// Deprecated: Use repoutil.NewCloneLink instead.
func (repo *Repository) WikiCloneLink() (cl *repoutil.CloneLink) {
return repo.cloneLink(true)
func (r *Repository) WikiCloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(true)
}
// WikiPath returns wiki data path by given user and repository name.
@ -49,37 +49,37 @@ func WikiPath(userName, repoName string) string {
return filepath.Join(repoutil.UserPath(userName), strings.ToLower(repoName)+".wiki.git")
}
func (repo *Repository) WikiPath() string {
return WikiPath(repo.MustOwner().Name, repo.Name)
func (r *Repository) WikiPath() string {
return WikiPath(r.MustOwner().Name, r.Name)
}
// HasWiki returns true if repository has wiki.
func (repo *Repository) HasWiki() bool {
return com.IsDir(repo.WikiPath())
func (r *Repository) HasWiki() bool {
return com.IsDir(r.WikiPath())
}
// InitWiki initializes a wiki for repository,
// it does nothing when repository already has wiki.
func (repo *Repository) InitWiki() error {
if repo.HasWiki() {
func (r *Repository) InitWiki() error {
if r.HasWiki() {
return nil
}
if err := git.Init(repo.WikiPath(), git.InitOptions{Bare: true}); err != nil {
if err := git.Init(r.WikiPath(), git.InitOptions{Bare: true}); err != nil {
return fmt.Errorf("init repository: %v", err)
} else if err = createDelegateHooks(repo.WikiPath()); err != nil {
} else if err = createDelegateHooks(r.WikiPath()); err != nil {
return fmt.Errorf("createDelegateHooks: %v", err)
}
return nil
}
func (repo *Repository) LocalWikiPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-wiki", com.ToStr(repo.ID))
func (r *Repository) LocalWikiPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-wiki", com.ToStr(r.ID))
}
// UpdateLocalWiki makes sure the local copy of repository wiki is up-to-date.
func (repo *Repository) UpdateLocalWiki() error {
return UpdateLocalCopyBranch(repo.WikiPath(), repo.LocalWikiPath(), "master", true)
func (r *Repository) UpdateLocalWiki() error {
return UpdateLocalCopyBranch(r.WikiPath(), r.LocalWikiPath(), "master", true)
}
func discardLocalWikiChanges(localPath string) error {
@ -87,18 +87,18 @@ func discardLocalWikiChanges(localPath string) error {
}
// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
func (r *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(r.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.InitWiki(); err != nil {
if err = r.InitWiki(); err != nil {
return fmt.Errorf("InitWiki: %v", err)
}
localPath := repo.LocalWikiPath()
localPath := r.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = repo.UpdateLocalWiki(); err != nil {
} else if err = r.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}
@ -150,22 +150,22 @@ func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, mes
return nil
}
func (repo *Repository) AddWikiPage(doer *User, title, content, message string) error {
return repo.updateWikiPage(doer, "", title, content, message, true)
func (r *Repository) AddWikiPage(doer *User, title, content, message string) error {
return r.updateWikiPage(doer, "", title, content, message, true)
}
func (repo *Repository) EditWikiPage(doer *User, oldTitle, title, content, message string) error {
return repo.updateWikiPage(doer, oldTitle, title, content, message, false)
func (r *Repository) EditWikiPage(doer *User, oldTitle, title, content, message string) error {
return r.updateWikiPage(doer, oldTitle, title, content, message, false)
}
func (repo *Repository) DeleteWikiPage(doer *User, title string) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
func (r *Repository) DeleteWikiPage(doer *User, title string) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(r.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(r.ID))
localPath := repo.LocalWikiPath()
localPath := r.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = repo.UpdateLocalWiki(); err != nil {
} else if err = r.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}

View File

@ -21,15 +21,15 @@ import (
)
const (
MAIL_AUTH_ACTIVATE = "auth/activate"
MAIL_AUTH_ACTIVATE_EMAIL = "auth/activate_email"
MAIL_AUTH_RESET_PASSWORD = "auth/reset_passwd"
MAIL_AUTH_REGISTER_NOTIFY = "auth/register_notify"
tmplAuthActivate = "auth/activate"
tmplAuthActivateEmail = "auth/activate_email"
tmplAuthResetPassword = "auth/reset_passwd"
tmplAuthRegisterNotify = "auth/register_notify"
MAIL_ISSUE_COMMENT = "issue/comment"
MAIL_ISSUE_MENTION = "issue/mention"
tmplIssueComment = "issue/comment"
tmplIssueMention = "issue/mention"
MAIL_NOTIFY_COLLABORATOR = "notify/collaborator"
tmplNotifyCollaborator = "notify/collaborator"
)
var (
@ -122,11 +122,11 @@ func SendUserMail(_ *macaron.Context, u User, tpl, code, subject, info string) {
}
func SendActivateAccountMail(c *macaron.Context, u User) {
SendUserMail(c, u, MAIL_AUTH_ACTIVATE, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.activate_account"), "activate account")
SendUserMail(c, u, tmplAuthActivate, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.activate_account"), "activate account")
}
func SendResetPasswordMail(c *macaron.Context, u User) {
SendUserMail(c, u, MAIL_AUTH_RESET_PASSWORD, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.reset_password"), "reset password")
SendUserMail(c, u, tmplAuthResetPassword, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.reset_password"), "reset password")
}
// SendActivateAccountMail sends confirmation email.
@ -137,7 +137,7 @@ func SendActivateEmailMail(c *macaron.Context, u User, email string) {
"Code": u.GenerateEmailActivateCode(email),
"Email": email,
}
body, err := render(MAIL_AUTH_ACTIVATE_EMAIL, data)
body, err := render(tmplAuthActivateEmail, data)
if err != nil {
log.Error("HTMLString: %v", err)
return
@ -154,7 +154,7 @@ func SendRegisterNotifyMail(c *macaron.Context, u User) {
data := map[string]any{
"Username": u.DisplayName(),
}
body, err := render(MAIL_AUTH_REGISTER_NOTIFY, data)
body, err := render(tmplAuthRegisterNotify, data)
if err != nil {
log.Error("HTMLString: %v", err)
return
@ -175,7 +175,7 @@ func SendCollaboratorMail(u, doer User, repo Repository) {
"RepoName": repo.FullName(),
"Link": repo.HTMLURL(),
}
body, err := render(MAIL_NOTIFY_COLLABORATOR, data)
body, err := render(tmplNotifyCollaborator, data)
if err != nil {
log.Error("HTMLString: %v", err)
return
@ -216,7 +216,7 @@ func SendIssueCommentMail(issue Issue, repo Repository, doer User, tos []string)
return
}
Send(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_COMMENT, tos, "issue comment"))
Send(composeIssueMessage(issue, repo, doer, tmplIssueComment, tos, "issue comment"))
}
// SendIssueMentionMail composes and sends issue mention emails to target receivers.
@ -224,5 +224,5 @@ func SendIssueMentionMail(issue Issue, repo Repository, doer User, tos []string)
if len(tos) == 0 {
return
}
Send(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_MENTION, tos, "issue mention"))
Send(composeIssueMessage(issue, repo, doer, tmplIssueMention, tos, "issue mention"))
}

View File

@ -146,7 +146,7 @@ func (*Sender) Send(from string, to []string, msg io.WriterTo) error {
}
if err = client.Hello(hostname); err != nil {
return fmt.Errorf("Hello: %v", err)
return fmt.Errorf("hello: %v", err)
}
}
@ -173,28 +173,28 @@ func (*Sender) Send(from string, to []string, msg io.WriterTo) error {
if auth != nil {
if err = client.Auth(auth); err != nil {
return fmt.Errorf("Auth: %v", err)
return fmt.Errorf("auth: %v", err)
}
}
}
if err = client.Mail(from); err != nil {
return fmt.Errorf("Mail: %v", err)
return fmt.Errorf("mail: %v", err)
}
for _, rec := range to {
if err = client.Rcpt(rec); err != nil {
return fmt.Errorf("Rcpt: %v", err)
return fmt.Errorf("rcpt: %v", err)
}
}
w, err := client.Data()
if err != nil {
return fmt.Errorf("Data: %v", err)
return fmt.Errorf("data: %v", err)
} else if _, err = msg.WriteTo(w); err != nil {
return fmt.Errorf("WriteTo: %v", err)
return fmt.Errorf("write to: %v", err)
} else if err = w.Close(); err != nil {
return fmt.Errorf("Close: %v", err)
return fmt.Errorf("close: %v", err)
}
return client.Quit()

View File

@ -44,7 +44,7 @@ type MigrateRepo struct {
CloneAddr string `json:"clone_addr" binding:"Required"`
AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"`
Uid int64 `json:"uid" binding:"Required"`
UID int64 `json:"uid" binding:"Required"`
RepoName string `json:"repo_name" binding:"Required;AlphaDashDot;MaxSize(100)"`
Mirror bool `json:"mirror"`
Private bool `json:"private"`

View File

@ -9,7 +9,6 @@ import (
"bytes"
"context"
"crypto/tls"
"encoding/xml"
"io"
"log"
"mime/multipart"
@ -22,8 +21,6 @@ import (
"strings"
"sync"
"time"
jsoniter "github.com/json-iterator/go"
)
var (
@ -95,13 +92,13 @@ type Settings struct {
UserAgent string
ConnectTimeout time.Duration
ReadWriteTimeout time.Duration
TlsClientConfig *tls.Config
TLSClientConfig *tls.Config
Proxy func(*http.Request) (*url.URL, error)
Transport http.RoundTripper
EnableCookie bool
}
// HttpRequest provides more useful methods for requesting one url than http.Request.
// Request provides more useful methods for requesting a URL than http.Request.
type Request struct {
url string
req *http.Request
@ -112,7 +109,7 @@ type Request struct {
body []byte
}
// Change request settings
// Setting changes the request settings
func (r *Request) Setting(setting Settings) *Request {
r.setting = setting
return r
@ -151,7 +148,7 @@ func (r *Request) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *Re
// SetTLSClientConfig sets tls connection configurations if visiting https url.
func (r *Request) SetTLSClientConfig(config *tls.Config) *Request {
r.setting.TlsClientConfig = config
r.setting.TLSClientConfig = config
return r
}
@ -304,7 +301,7 @@ func (r *Request) getResponse() (*http.Response, error) {
if trans == nil {
// create default transport
trans = &http.Transport{
TLSClientConfig: r.setting.TlsClientConfig,
TLSClientConfig: r.setting.TLSClientConfig,
Proxy: r.setting.Proxy,
DialContext: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
}
@ -312,7 +309,7 @@ func (r *Request) getResponse() (*http.Response, error) {
// if r.transport is *http.Transport then set the settings.
if t, ok := trans.(*http.Transport); ok {
if t.TLSClientConfig == nil {
t.TLSClientConfig = r.setting.TlsClientConfig
t.TLSClientConfig = r.setting.TLSClientConfig
}
if t.Proxy == nil {
t.Proxy = r.setting.Proxy
@ -412,26 +409,6 @@ func (r *Request) ToFile(filename string) error {
return err
}
// ToJson returns the map that marshals from the body bytes as json in response .
// it calls Response inner.
func (r *Request) ToJson(v any) error {
data, err := r.Bytes()
if err != nil {
return err
}
return jsoniter.Unmarshal(data, v)
}
// ToXml returns the map that marshals from the body bytes as xml in response .
// it calls Response inner.
func (r *Request) ToXml(v any) error {
data, err := r.Bytes()
if err != nil {
return err
}
return xml.Unmarshal(data, v)
}
// Response executes request client gets response manually.
func (r *Request) Response() (*http.Response, error) {
return r.getResponse()

View File

@ -17,7 +17,7 @@ import (
var ErrExecTimeout = errors.New("process execution timeout")
const DEFAULT_TIMEOUT = 60 * time.Second
const defaultTimeout = 60 * time.Second
// Process represents a running process calls shell command.
type Process struct {
@ -77,7 +77,7 @@ func Remove(pid int64) bool {
// Exec starts executing a shell command in given path, it tracks corresponding process and timeout.
func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) (string, string, error) {
if timeout == -1 {
timeout = DEFAULT_TIMEOUT
timeout = defaultTimeout
}
bufOut := new(bytes.Buffer)

View File

@ -208,8 +208,8 @@ func Migrate(c *context.APIContext, f form.MigrateRepo) {
ctxUser := c.User
// Not equal means context user is an organization,
// or is another user/organization if current user is admin.
if f.Uid != ctxUser.ID {
org, err := database.Handle.Users().GetByID(c.Req.Context(), f.Uid)
if f.UID != ctxUser.ID {
org, err := database.Handle.Users().GetByID(c.Req.Context(), f.UID)
if err != nil {
if database.IsErrUserNotExist(err) {
c.ErrorStatus(http.StatusUnprocessableEntity, err)

View File

@ -11,7 +11,7 @@ import (
"gogs.io/gogs/internal/database"
)
func responseApiUsers(c *context.APIContext, users []*database.User) {
func responseAPIUsers(c *context.APIContext, users []*database.User) {
apiUsers := make([]*api.User, len(users))
for i := range users {
apiUsers[i] = users[i].APIFormat()
@ -25,7 +25,7 @@ func listUserFollowers(c *context.APIContext, u *database.User) {
c.Error(err, "list followers")
return
}
responseApiUsers(c, users)
responseAPIUsers(c, users)
}
func ListMyFollowers(c *context.APIContext) {
@ -46,7 +46,7 @@ func listUserFollowing(c *context.APIContext, u *database.User) {
c.Error(err, "list followings")
return
}
responseApiUsers(c, users)
responseAPIUsers(c, users)
}
func ListMyFollowing(c *context.APIContext) {

View File

@ -30,7 +30,7 @@ func Home(c *context.Context) {
if c.IsLogged {
if !c.User.IsActive && conf.Auth.RequireEmailConfirmation {
c.Data["Title"] = c.Tr("auth.active_your_account")
c.Success(user.ACTIVATE)
c.Success(user.TmplUserAuthActivate)
} else {
user.Dashboard(c)
}

View File

@ -282,7 +282,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) {
}); err != nil {
log.Error("Failed to update repo file: %v", err)
c.FormErr("TreePath")
c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, errors.InternalServerError), tmplEditorEdit, &f)
c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, errors.ErrInternalServerError), tmplEditorEdit, &f)
return
}
@ -390,7 +390,7 @@ func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) {
Message: message,
}); err != nil {
log.Error("Failed to delete repo file: %v", err)
c.RenderWithErr(c.Tr("repo.editor.fail_to_delete_file", c.Repo.TreePath, errors.InternalServerError), tmplEditorDelete, &f)
c.RenderWithErr(c.Tr("repo.editor.fail_to_delete_file", c.Repo.TreePath, errors.ErrInternalServerError), tmplEditorDelete, &f)
return
}
@ -512,7 +512,7 @@ func UploadFilePost(c *context.Context, f form.UploadRepoFile) {
}); err != nil {
log.Error("Failed to upload files: %v", err)
c.FormErr("TreePath")
c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, errors.InternalServerError), tmplEditorUpload, &f)
c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, errors.ErrInternalServerError), tmplEditorUpload, &f)
return
}

View File

@ -162,7 +162,7 @@ func Migrate(c *context.Context) {
func MigratePost(c *context.Context, f form.MigrateRepo) {
c.Data["Title"] = c.Tr("new_migrate")
ctxUser := checkContextUser(c, f.Uid)
ctxUser := checkContextUser(c, f.UID)
if c.Written() {
return
}

View File

@ -26,13 +26,13 @@ import (
)
const (
LOGIN = "user/auth/login"
TWO_FACTOR = "user/auth/two_factor"
TWO_FACTOR_RECOVERY_CODE = "user/auth/two_factor_recovery_code"
SIGNUP = "user/auth/signup"
ACTIVATE = "user/auth/activate"
FORGOT_PASSWORD = "user/auth/forgot_passwd"
RESET_PASSWORD = "user/auth/reset_passwd"
tmplUserAuthLogin = "user/auth/login"
tmplUserAuthTwoFactor = "user/auth/two_factor"
tmplUserAuthTwoFactorRecoveryCode = "user/auth/two_factor_recovery_code"
tmplUserAuthSignup = "user/auth/signup"
TmplUserAuthActivate = "user/auth/activate"
tmplUserAuthForgotPassword = "user/auth/forgot_passwd"
tmplUserAuthResetPassword = "user/auth/reset_passwd"
)
// AutoLogin reads cookie and try to auto-login.
@ -119,7 +119,7 @@ func Login(c *context.Context) {
break
}
}
c.Success(LOGIN)
c.Success(tmplUserAuthLogin)
}
func afterLogin(c *context.Context, u *database.User, remember bool) {
@ -161,7 +161,7 @@ func LoginPost(c *context.Context, f form.SignIn) {
c.Data["LoginSources"] = loginSources
if c.HasError() {
c.Success(LOGIN)
c.Success(tmplUserAuthLogin)
return
}
@ -170,10 +170,10 @@ func LoginPost(c *context.Context, f form.SignIn) {
switch {
case auth.IsErrBadCredentials(err):
c.FormErr("UserName", "Password")
c.RenderWithErr(c.Tr("form.username_password_incorrect"), LOGIN, &f)
c.RenderWithErr(c.Tr("form.username_password_incorrect"), tmplUserAuthLogin, &f)
case database.IsErrLoginSourceMismatch(err):
c.FormErr("LoginSource")
c.RenderWithErr(c.Tr("form.auth_source_mismatch"), LOGIN, &f)
c.RenderWithErr(c.Tr("form.auth_source_mismatch"), tmplUserAuthLogin, &f)
default:
c.Error(err, "authenticate user")
@ -204,7 +204,7 @@ func LoginTwoFactor(c *context.Context) {
return
}
c.Success(TWO_FACTOR)
c.Success(tmplUserAuthTwoFactor)
}
func LoginTwoFactorPost(c *context.Context) {
@ -257,7 +257,7 @@ func LoginTwoFactorRecoveryCode(c *context.Context) {
return
}
c.Success(TWO_FACTOR_RECOVERY_CODE)
c.Success(tmplUserAuthTwoFactorRecoveryCode)
}
func LoginTwoFactorRecoveryCodePost(c *context.Context) {
@ -301,11 +301,11 @@ func SignUp(c *context.Context) {
if conf.Auth.DisableRegistration {
c.Data["DisableRegistration"] = true
c.Success(SIGNUP)
c.Success(tmplUserAuthSignup)
return
}
c.Success(SIGNUP)
c.Success(tmplUserAuthSignup)
}
func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
@ -319,19 +319,19 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
}
if c.HasError() {
c.Success(SIGNUP)
c.Success(tmplUserAuthSignup)
return
}
if conf.Auth.EnableRegistrationCaptcha && !cpt.VerifyReq(c.Req) {
c.FormErr("Captcha")
c.RenderWithErr(c.Tr("form.captcha_incorrect"), SIGNUP, &f)
c.RenderWithErr(c.Tr("form.captcha_incorrect"), tmplUserAuthSignup, &f)
return
}
if f.Password != f.Retype {
c.FormErr("Password")
c.RenderWithErr(c.Tr("form.password_not_match"), SIGNUP, &f)
c.RenderWithErr(c.Tr("form.password_not_match"), tmplUserAuthSignup, &f)
return
}
@ -348,13 +348,13 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
switch {
case database.IsErrUserAlreadyExist(err):
c.FormErr("UserName")
c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f)
c.RenderWithErr(c.Tr("form.username_been_taken"), tmplUserAuthSignup, &f)
case database.IsErrEmailAlreadyUsed(err):
c.FormErr("Email")
c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f)
c.RenderWithErr(c.Tr("form.email_been_used"), tmplUserAuthSignup, &f)
case database.IsErrNameNotAllowed(err):
c.FormErr("UserName")
c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), SIGNUP, &f)
c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplUserAuthSignup, &f)
default:
c.Error(err, "create user")
}
@ -388,7 +388,7 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
c.Data["IsSendRegisterMail"] = true
c.Data["Email"] = user.Email
c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
c.Success(ACTIVATE)
c.Success(TmplUserAuthActivate)
if err := c.Cache.Put(userutil.MailResendCacheKey(user.ID), 1, 180); err != nil {
log.Error("Failed to put cache key 'mail resend': %v", err)
@ -402,12 +402,12 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
// parseUserFromCode returns user by username encoded in code.
// It returns nil if code or username is invalid.
func parseUserFromCode(code string) (user *database.User) {
if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
if len(code) <= tool.TimeLimitCodeLength {
return nil
}
// Use tail hex username to query user
hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
hexStr := code[tool.TimeLimitCodeLength:]
if b, err := hex.DecodeString(hexStr); err == nil {
if user, err = database.Handle.Users().GetByUsername(gocontext.TODO(), string(b)); user != nil {
return user
@ -425,7 +425,7 @@ func verifyUserActiveCode(code string) (user *database.User) {
if user = parseUserFromCode(code); user != nil {
// time limit code
prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
prefix := code[:tool.TimeLimitCodeLength]
data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
if tool.VerifyTimeLimitCode(data, minutes, prefix) {
@ -441,7 +441,7 @@ func verifyActiveEmailCode(code, email string) *database.EmailAddress {
if user := parseUserFromCode(code); user != nil {
// time limit code
prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
prefix := code[:tool.TimeLimitCodeLength]
data := com.ToStr(user.ID) + email + user.LowerName + user.Password + user.Rands
if tool.VerifyTimeLimitCode(data, minutes, prefix) {
@ -477,7 +477,7 @@ func Activate(c *context.Context) {
} else {
c.Data["ServiceNotEnabled"] = true
}
c.Success(ACTIVATE)
c.Success(TmplUserAuthActivate)
return
}
@ -506,7 +506,7 @@ func Activate(c *context.Context) {
}
c.Data["IsActivateFailed"] = true
c.Success(ACTIVATE)
c.Success(TmplUserAuthActivate)
}
func ActivateEmail(c *context.Context) {
@ -533,12 +533,12 @@ func ForgotPasswd(c *context.Context) {
if !conf.Email.Enabled {
c.Data["IsResetDisable"] = true
c.Success(FORGOT_PASSWORD)
c.Success(tmplUserAuthForgotPassword)
return
}
c.Data["IsResetRequest"] = true
c.Success(FORGOT_PASSWORD)
c.Success(tmplUserAuthForgotPassword)
}
func ForgotPasswdPost(c *context.Context) {
@ -558,7 +558,7 @@ func ForgotPasswdPost(c *context.Context) {
if database.IsErrUserNotExist(err) {
c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
c.Data["IsResetSent"] = true
c.Success(FORGOT_PASSWORD)
c.Success(tmplUserAuthForgotPassword)
return
}
@ -568,13 +568,13 @@ func ForgotPasswdPost(c *context.Context) {
if !u.IsLocal() {
c.FormErr("Email")
c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
c.RenderWithErr(c.Tr("auth.non_local_account"), tmplUserAuthForgotPassword, nil)
return
}
if c.Cache.IsExist(userutil.MailResendCacheKey(u.ID)) {
c.Data["ResendLimited"] = true
c.Success(FORGOT_PASSWORD)
c.Success(tmplUserAuthForgotPassword)
return
}
@ -585,7 +585,7 @@ func ForgotPasswdPost(c *context.Context) {
c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
c.Data["IsResetSent"] = true
c.Success(FORGOT_PASSWORD)
c.Success(tmplUserAuthForgotPassword)
}
func ResetPasswd(c *context.Context) {
@ -598,7 +598,7 @@ func ResetPasswd(c *context.Context) {
}
c.Data["Code"] = code
c.Data["IsResetForm"] = true
c.Success(RESET_PASSWORD)
c.Success(tmplUserAuthResetPassword)
}
func ResetPasswdPost(c *context.Context) {
@ -617,7 +617,7 @@ func ResetPasswdPost(c *context.Context) {
if len(password) < 6 {
c.Data["IsResetForm"] = true
c.Data["Err_Password"] = true
c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
c.RenderWithErr(c.Tr("auth.password_too_short"), tmplUserAuthResetPassword, nil)
return
}
@ -633,5 +633,5 @@ func ResetPasswdPost(c *context.Context) {
}
c.Data["IsResetFailed"] = true
c.Success(RESET_PASSWORD)
c.Success(tmplUserAuthResetPassword)
}

View File

@ -22,13 +22,8 @@ const (
)
func Profile(c *context.Context, puser *context.ParamsUser) {
isShowKeys := false
if strings.HasSuffix(c.Params(":username"), ".keys") {
isShowKeys = true
}
// Show SSH keys.
if isShowKeys {
if strings.HasSuffix(c.Params(":username"), ".keys") {
ShowSSHKeys(c, puser.ID)
return
}

View File

@ -164,11 +164,11 @@ func ToUTF8WithErr(content []byte) (error, string) {
encoding, _ := charset.Lookup(charsetLabel)
if encoding == nil {
return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
return fmt.Errorf("unknown encoding: %s", charsetLabel), string(content)
}
// If there is an error, we concatenate the nicely decoded part and the
// original left over. This way we won't loose data.
// original left over. This way we won't lose data.
result, n, err := transform.String(encoding.NewDecoder(), string(content))
if err != nil {
result = result + string(content[n:])

View File

@ -89,7 +89,7 @@ func VerifyTimeLimitCode(data string, minutes int, code string) bool {
return false
}
const TIME_LIMIT_CODE_LENGTH = 12 + 6 + 40
const TimeLimitCodeLength = 12 + 6 + 40
// CreateTimeLimitCode generates a time limit code based on given input data.
// Format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
@ -235,11 +235,7 @@ func TimeSincePro(then time.Time) string {
}
var timeStr, diffStr string
for {
if diff == 0 {
break
}
for diff != 0 {
diff, diffStr = computeTimeDiff(diff)
timeStr += ", " + diffStr
}

View File

@ -40,7 +40,7 @@ func TestGenerateActivateCode(t *testing.T) {
)
code := GenerateActivateCode(1, "alice@example.com", "Alice", "123456", "rands")
got := tool.VerifyTimeLimitCode("1alice@example.comalice123456rands", conf.Auth.ActivateCodeLives, code[:tool.TIME_LIMIT_CODE_LENGTH])
got := tool.VerifyTimeLimitCode("1alice@example.comalice123456rands", conf.Auth.ActivateCodeLives, code[:tool.TimeLimitCodeLength])
assert.True(t, got)
}