mod: bump modernc.org/sqlite from 1.36.0 to 1.37.0 (#7947)

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Joe Chen <jc@unknwon.io>
This commit is contained in:
dependabot[bot] 2025-04-14 18:00:07 -04:00 committed by GitHub
parent 4acaaac85a
commit 139ea3ce7d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
76 changed files with 1085 additions and 1097 deletions

View File

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

View File

@ -1,29 +1,42 @@
linters-settings: version: "2"
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
linters: linters:
enable: enable:
- unused
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- nakedret - nakedret
- gofmt
- rowserrcheck - rowserrcheck
- unconvert - unconvert
- goimports
- unparam - 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
- "-ST1016" # Some legit code uses this pattern
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 ### 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) - 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 ### Fixed

18
go.mod
View File

@ -1,6 +1,6 @@
module gogs.io/gogs module gogs.io/gogs
go 1.23.4 go 1.24
require ( require (
github.com/Masterminds/semver/v3 v3.3.1 github.com/Masterminds/semver/v3 v3.3.1
@ -55,7 +55,7 @@ require (
gorm.io/driver/sqlite v1.4.2 gorm.io/driver/sqlite v1.4.2
gorm.io/driver/sqlserver v1.4.1 gorm.io/driver/sqlserver v1.4.1
gorm.io/gorm v1.25.12 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 unknwon.dev/clog/v2 v2.2.0
xorm.io/builder v0.3.6 xorm.io/builder v0.3.6
xorm.io/core v0.7.2 xorm.io/core v0.7.2
@ -121,19 +121,19 @@ require (
go.bobheadxi.dev/streamline v1.2.1 // indirect go.bobheadxi.dev/streamline v1.2.1 // indirect
go.opentelemetry.io/otel v1.11.0 // indirect go.opentelemetry.io/otel v1.11.0 // indirect
go.opentelemetry.io/otel/trace 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/exp v0.0.0-20250305212735-054e65f0b394 // indirect
golang.org/x/mod v0.19.0 // indirect golang.org/x/mod v0.24.0 // indirect
golang.org/x/sync v0.11.0 // indirect golang.org/x/sync v0.12.0 // indirect
golang.org/x/sys v0.30.0 // indirect golang.org/x/sys v0.31.0 // indirect
google.golang.org/protobuf v1.36.1 // indirect google.golang.org/protobuf v1.36.1 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/bufio.v1 v1.0.0-20140618132640-567b2bfa514e // indirect gopkg.in/bufio.v1 v1.0.0-20140618132640-567b2bfa514e // indirect
gopkg.in/redis.v2 v2.3.2 // indirect gopkg.in/redis.v2 v2.3.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // 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/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 ./ // +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/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-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-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= 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.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.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 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 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= 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-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-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
golang.org/x/exp v0.0.0-20230315142452-642cacee5cc0/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= 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-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-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 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.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.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.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 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-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-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/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.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.9.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.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 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-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-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/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.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.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.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 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/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-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 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.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= 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.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.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= 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-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-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/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-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-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/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.25.2 h1:T2oH7sZdGvTaie0BRNFbIYsabzCxUQg8nLqCdQ2i0ic=
modernc.org/cc/v4 v4.24.4/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= modernc.org/cc/v4 v4.25.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.23.16 h1:Z2N+kk38b7SfySC1ZkpGLN2vthNJP1+ZzGZIlH7uBxo= modernc.org/ccgo/v4 v4.25.1 h1:TFSzPrAGmDsdnhT9X2UrcPMI3N/mJ9/X9ykKXwLhDsU=
modernc.org/ccgo/v4 v4.23.16/go.mod h1:nNma8goMTY7aQZQNTyN9AIoJfxav4nvTnvKThAeMDdo= 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 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= 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.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.3/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8= modernc.org/libc v1.62.1 h1:s0+fv5E3FymN8eJVmnk0llBe6rOxCu/DEU+XygRbS8s=
modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E= 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 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.8.2 h1:cL9L4bcoAObu4NkxOlKWBWtNHIsnnACGF/TbqQ6sbcI= modernc.org/memory v1.9.1 h1:V/Z1solwAVmMW1yttq3nDdZPJqV1rM05Ccq6KMSZ34g=
modernc.org/memory v1.8.2/go.mod h1:ZbjSvMO5NQ1A2i3bWeDiVMxIorXwdClKE/0SZ+BMotU= 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 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= 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 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.36.0 h1:EQXNRn4nIS+gfsKeUTymHIz1waxuv5BzU7558dHSfH8= modernc.org/sqlite v1.37.0 h1:s1TMe7T3Q3ovQiK2Ouz4Jwh7dw4ZDqbebSDTlSJdfjI=
modernc.org/sqlite v1.36.0/go.mod h1:7MPwH7Z6bREicF9ZVUR78P1IKuxfZ8mRIDHD0iD+8TU= 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 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=

View File

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

View File

@ -68,7 +68,7 @@ func runHookPreReceive(c *cli.Context) error {
} }
setup(c, "pre-receive.log", true) setup(c, "pre-receive.log", true)
isWiki := strings.Contains(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/") isWiki := strings.Contains(os.Getenv(database.EnvRepoCustomHooksPath), ".wiki.git/")
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
@ -89,7 +89,7 @@ func runHookPreReceive(c *cli.Context) error {
branchName := git.RefShortName(string(fields[2])) branchName := git.RefShortName(string(fields[2]))
// Branch protection // Branch protection
repoID := com.StrTo(os.Getenv(database.ENV_REPO_ID)).MustInt64() repoID := com.StrTo(os.Getenv(database.EnvRepoID)).MustInt64()
protectBranch, err := database.GetProtectBranchOfRepoByName(repoID, branchName) protectBranch, err := database.GetProtectBranchOfRepoByName(repoID, branchName)
if err != nil { if err != nil {
if database.IsErrBranchNotExist(err) { if database.IsErrBranchNotExist(err) {
@ -105,7 +105,7 @@ func runHookPreReceive(c *cli.Context) error {
bypassRequirePullRequest := false bypassRequirePullRequest := false
// Check if user is in whitelist when enabled // Check if user is in whitelist when enabled
userID := com.StrTo(os.Getenv(database.ENV_AUTH_USER_ID)).MustInt64() userID := com.StrTo(os.Getenv(database.EnvAuthUserID)).MustInt64()
if protectBranch.EnableWhitelist { if protectBranch.EnableWhitelist {
if !database.IsUserInProtectBranchWhitelist(repoID, userID, branchName) { if !database.IsUserInProtectBranchWhitelist(repoID, userID, branchName) {
fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "") fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "")
@ -126,7 +126,7 @@ func runHookPreReceive(c *cli.Context) error {
// Check force push // Check force push
output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID). output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).
RunInDir(database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME))) RunInDir(database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName)))
if err != nil { if err != nil {
fail("Internal error", "Failed to detect force push: %v", err) fail("Internal error", "Failed to detect force push: %v", err)
} else if len(output) > 0 { } else if len(output) > 0 {
@ -134,7 +134,7 @@ func runHookPreReceive(c *cli.Context) error {
} }
} }
customHooksPath := filepath.Join(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), "pre-receive") customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "pre-receive")
if !com.IsFile(customHooksPath) { if !com.IsFile(customHooksPath) {
return nil return nil
} }
@ -145,7 +145,7 @@ func runHookPreReceive(c *cli.Context) error {
} else { } else {
hookCmd = exec.Command(customHooksPath) hookCmd = exec.Command(customHooksPath)
} }
hookCmd.Dir = database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME)) hookCmd.Dir = database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName))
hookCmd.Stdout = os.Stdout hookCmd.Stdout = os.Stdout
hookCmd.Stdin = buf hookCmd.Stdin = buf
hookCmd.Stderr = os.Stderr hookCmd.Stderr = os.Stderr
@ -168,7 +168,7 @@ func runHookUpdate(c *cli.Context) error {
fail("First argument 'refName' is empty", "First argument 'refName' is empty") fail("First argument 'refName' is empty", "First argument 'refName' is empty")
} }
customHooksPath := filepath.Join(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), "update") customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "update")
if !com.IsFile(customHooksPath) { if !com.IsFile(customHooksPath) {
return nil return nil
} }
@ -179,7 +179,7 @@ func runHookUpdate(c *cli.Context) error {
} else { } else {
hookCmd = exec.Command(customHooksPath, args...) hookCmd = exec.Command(customHooksPath, args...)
} }
hookCmd.Dir = database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME)) hookCmd.Dir = database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName))
hookCmd.Stdout = os.Stdout hookCmd.Stdout = os.Stdout
hookCmd.Stdin = os.Stdin hookCmd.Stdin = os.Stdin
hookCmd.Stderr = os.Stderr hookCmd.Stderr = os.Stderr
@ -199,7 +199,7 @@ func runHookPostReceive(c *cli.Context) error {
// so we need to setup additional services for email notifications. // so we need to setup additional services for email notifications.
email.NewContext() email.NewContext()
isWiki := strings.Contains(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/") isWiki := strings.Contains(os.Getenv(database.EnvRepoCustomHooksPath), ".wiki.git/")
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
@ -221,10 +221,10 @@ func runHookPostReceive(c *cli.Context) error {
OldCommitID: string(fields[0]), OldCommitID: string(fields[0]),
NewCommitID: string(fields[1]), NewCommitID: string(fields[1]),
FullRefspec: string(fields[2]), FullRefspec: string(fields[2]),
PusherID: com.StrTo(os.Getenv(database.ENV_AUTH_USER_ID)).MustInt64(), PusherID: com.StrTo(os.Getenv(database.EnvAuthUserID)).MustInt64(),
PusherName: os.Getenv(database.ENV_AUTH_USER_NAME), PusherName: os.Getenv(database.EnvAuthUserName),
RepoUserName: os.Getenv(database.ENV_REPO_OWNER_NAME), RepoUserName: os.Getenv(database.EnvRepoOwnerName),
RepoName: os.Getenv(database.ENV_REPO_NAME), RepoName: os.Getenv(database.EnvRepoName),
} }
if err := database.PushUpdate(options); err != nil { if err := database.PushUpdate(options); err != nil {
log.Error("PushUpdate: %v", err) log.Error("PushUpdate: %v", err)
@ -233,8 +233,8 @@ func runHookPostReceive(c *cli.Context) error {
// Ask for running deliver hook and test pull request tasks // Ask for running deliver hook and test pull request tasks
q := make(url.Values) q := make(url.Values)
q.Add("branch", git.RefShortName(options.FullRefspec)) q.Add("branch", git.RefShortName(options.FullRefspec))
q.Add("secret", os.Getenv(database.ENV_REPO_OWNER_SALT_MD5)) q.Add("secret", os.Getenv(database.EnvRepoOwnerSaltMd5))
q.Add("pusher", os.Getenv(database.ENV_AUTH_USER_ID)) q.Add("pusher", os.Getenv(database.EnvAuthUserID))
reqURL := fmt.Sprintf("%s%s/%s/tasks/trigger?%s", conf.Server.LocalRootURL, options.RepoUserName, options.RepoName, q.Encode()) reqURL := fmt.Sprintf("%s%s/%s/tasks/trigger?%s", conf.Server.LocalRootURL, options.RepoUserName, options.RepoName, q.Encode())
log.Trace("Trigger task: %s", reqURL) log.Trace("Trigger task: %s", reqURL)
@ -252,7 +252,7 @@ func runHookPostReceive(c *cli.Context) error {
} }
} }
customHooksPath := filepath.Join(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), "post-receive") customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "post-receive")
if !com.IsFile(customHooksPath) { if !com.IsFile(customHooksPath) {
return nil return nil
} }
@ -263,7 +263,7 @@ func runHookPostReceive(c *cli.Context) error {
} else { } else {
hookCmd = exec.Command(customHooksPath) hookCmd = exec.Command(customHooksPath)
} }
hookCmd.Dir = database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME)) hookCmd.Dir = database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName))
hookCmd.Stdout = os.Stdout hookCmd.Stdout = os.Stdout
hookCmd.Stdin = buf hookCmd.Stdin = buf
hookCmd.Stderr = os.Stderr hookCmd.Stderr = os.Stderr

View File

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

View File

@ -22,7 +22,7 @@ import (
) )
const ( const (
_ACCESS_DENIED_MESSAGE = "Repository does not exist or you do not have access" accessDeniedMessage = "Repository does not exist or you do not have access"
) )
var Serv = cli.Command{ var Serv = cli.Command{
@ -173,7 +173,7 @@ func runServ(c *cli.Context) error {
repo, err := database.GetRepositoryByName(owner.ID, repoName) repo, err := database.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
if database.IsErrRepoNotExist(err) { if database.IsErrRepoNotExist(err) {
fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName) fail(accessDeniedMessage, "Repository does not exist: %s/%s", owner.Name, repoName)
} }
fail("Internal error", "Failed to get repository: %v", err) fail("Internal error", "Failed to get repository: %v", err)
} }
@ -217,7 +217,7 @@ func runServ(c *cli.Context) error {
}, },
) )
if mode < requestMode { if mode < requestMode {
clientMessage := _ACCESS_DENIED_MESSAGE clientMessage := accessDeniedMessage
if mode >= database.AccessModeRead { if mode >= database.AccessModeRead {
clientMessage = "You do not have sufficient authorization for this action" clientMessage = "You do not have sufficient authorization for this action"
} }

View File

@ -107,7 +107,7 @@ func newMacaron() *macaron.Macaron {
conf.Picture.RepositoryAvatarUploadPath, conf.Picture.RepositoryAvatarUploadPath,
macaron.StaticOptions{ macaron.StaticOptions{
ETag: true, ETag: true,
Prefix: database.REPO_AVATAR_URL_PREFIX, Prefix: database.RepoAvatarURLPrefix,
SkipLogging: conf.Server.DisableRouterLog, SkipLogging: conf.Server.DisableRouterLog,
}, },
)) ))

View File

@ -96,15 +96,6 @@ func (c *Context) UserID() int64 {
return c.User.ID 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 { func (c *Context) GetErrMsg() string {
return c.Data["ErrorMsg"].(string) return c.Data["ErrorMsg"].(string)
} }

View File

@ -233,7 +233,7 @@ func (s *ActionsStore) MirrorSyncPush(ctx context.Context, opts MirrorSyncPushOp
apiPusher := opts.Owner.APIFormat() apiPusher := opts.Owner.APIFormat()
err = PrepareWebhooks( err = PrepareWebhooks(
opts.Repo, opts.Repo,
HOOK_EVENT_PUSH, HookEventTypePush,
&api.PushPayload{ &api.PushPayload{
Ref: opts.RefName, Ref: opts.RefName,
Before: opts.OldCommitID, Before: opts.OldCommitID,
@ -499,7 +499,7 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
if isDelRef { if isDelRef {
err = PrepareWebhooks( err = PrepareWebhooks(
opts.Repo, opts.Repo,
HOOK_EVENT_DELETE, HookEventTypeDelete,
&api.DeletePayload{ &api.DeletePayload{
Ref: refName, Ref: refName,
RefType: "branch", RefType: "branch",
@ -543,7 +543,7 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
if isNewRef { if isNewRef {
err = PrepareWebhooks( err = PrepareWebhooks(
opts.Repo, opts.Repo,
HOOK_EVENT_CREATE, HookEventTypeCreate,
&api.CreatePayload{ &api.CreatePayload{
Ref: refName, Ref: refName,
RefType: "branch", RefType: "branch",
@ -576,7 +576,7 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
err = PrepareWebhooks( err = PrepareWebhooks(
opts.Repo, opts.Repo,
HOOK_EVENT_PUSH, HookEventTypePush,
&api.PushPayload{ &api.PushPayload{
Ref: opts.RefFullName, Ref: opts.RefFullName,
Before: opts.OldCommitID, Before: opts.OldCommitID,
@ -638,7 +638,7 @@ func (s *ActionsStore) PushTag(ctx context.Context, opts PushTagOptions) error {
if opts.NewCommitID == git.EmptyID { if opts.NewCommitID == git.EmptyID {
err = PrepareWebhooks( err = PrepareWebhooks(
opts.Repo, opts.Repo,
HOOK_EVENT_DELETE, HookEventTypeDelete,
&api.DeletePayload{ &api.DeletePayload{
Ref: refName, Ref: refName,
RefType: "tag", RefType: "tag",
@ -661,7 +661,7 @@ func (s *ActionsStore) PushTag(ctx context.Context, opts PushTagOptions) error {
err = PrepareWebhooks( err = PrepareWebhooks(
opts.Repo, opts.Repo,
HOOK_EVENT_CREATE, HookEventTypeCreate,
&api.CreatePayload{ &api.CreatePayload{
Ref: refName, Ref: refName,
RefType: "tag", RefType: "tag",

View File

@ -49,8 +49,8 @@ func AttachmentLocalPath(uuid string) string {
} }
// LocalPath returns where attachment is stored in local file system. // LocalPath returns where attachment is stored in local file system.
func (attach *Attachment) LocalPath() string { func (a *Attachment) LocalPath() string {
return AttachmentLocalPath(attach.UUID) return AttachmentLocalPath(a.UUID)
} }
// NewAttachment creates a new attachment object. // NewAttachment creates a new attachment object.
@ -72,9 +72,9 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment,
defer fw.Close() defer fw.Close()
if _, err = fw.Write(buf); err != nil { 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 { } 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 { 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. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) { func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueId) attachments, err := GetAttachmentsByIssueID(issueID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -193,8 +193,8 @@ func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
} }
// DeleteAttachmentsByComment deletes all attachments associated with the given comment. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) { func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentId) attachments, err := GetAttachmentsByCommentID(commentID)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View File

@ -25,27 +25,27 @@ type CommentType int
const ( const (
// Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0) // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
COMMENT_TYPE_COMMENT CommentType = iota CommentTypeComment CommentType = iota
COMMENT_TYPE_REOPEN CommentTypeReopen
COMMENT_TYPE_CLOSE CommentTypeClose
// References. // References.
COMMENT_TYPE_ISSUE_REF CommentTypeIssueRef
// Reference from a commit (not part of a pull request) // Reference from a commit (not part of a pull request)
COMMENT_TYPE_COMMIT_REF CommentTypeCommitRef
// Reference from a comment // Reference from a comment
COMMENT_TYPE_COMMENT_REF CommentTypeCommentRef
// Reference from a pull request // Reference from a pull request
COMMENT_TYPE_PULL_REF CommentTypePullRef
) )
type CommentTag int type CommentTag int
const ( const (
COMMENT_TAG_NONE CommentTag = iota CommentTagNone CommentTag = iota
COMMENT_TAG_POSTER CommentTagPoster
COMMENT_TAG_WRITER CommentTagWriter
COMMENT_TAG_OWNER CommentTagOwner
) )
// Comment represents a comment in commit and issue page. // Comment represents a comment in commit and issue page.
@ -166,21 +166,21 @@ func (c *Comment) EventTag() string {
// mailParticipants sends new comment emails to repository watchers // mailParticipants sends new comment emails to repository watchers
// and mentioned people. // and mentioned people.
func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) { func (c *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
mentions := markup.FindAllMentions(cmt.Content) mentions := markup.FindAllMentions(c.Content)
if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil { if err = updateIssueMentions(e, c.IssueID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err) return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
} }
switch opType { switch opType {
case ActionCommentIssue: case ActionCommentIssue:
issue.Content = cmt.Content issue.Content = c.Content
case ActionCloseIssue: case ActionCloseIssue:
issue.Content = fmt.Sprintf("Closed #%d", issue.Index) issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
case ActionReopenIssue: case ActionReopenIssue:
issue.Content = fmt.Sprintf("Reopened #%d", issue.Index) 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) log.Error("mailIssueCommentToParticipants: %v", err)
} }
@ -216,7 +216,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
// Check comment type. // Check comment type.
switch opts.Type { switch opts.Type {
case COMMENT_TYPE_COMMENT: case CommentTypeComment:
act.OpType = ActionCommentIssue act.OpType = ActionCommentIssue
if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil { if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
@ -245,7 +245,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
} }
} }
case COMMENT_TYPE_REOPEN: case CommentTypeReopen:
act.OpType = ActionReopenIssue act.OpType = ActionReopenIssue
if opts.Issue.IsPull { if opts.Issue.IsPull {
act.OpType = ActionReopenPullRequest act.OpType = ActionReopenPullRequest
@ -260,7 +260,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
return nil, err return nil, err
} }
case COMMENT_TYPE_CLOSE: case CommentTypeClose:
act.OpType = ActionCloseIssue act.OpType = ActionCloseIssue
if opts.Issue.IsPull { if opts.Issue.IsPull {
act.OpType = ActionClosePullRequest act.OpType = ActionClosePullRequest
@ -294,9 +294,9 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
} }
func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) { func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
cmtType := COMMENT_TYPE_CLOSE cmtType := CommentTypeClose
if !issue.IsClosed { if !issue.IsClosed {
cmtType = COMMENT_TYPE_REOPEN cmtType = CommentTypeReopen
} }
return createComment(e, &CreateCommentOptions{ return createComment(e, &CreateCommentOptions{
Type: cmtType, Type: cmtType,
@ -338,7 +338,7 @@ func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
// CreateIssueComment creates a plain issue comment. // CreateIssueComment creates a plain issue comment.
func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) { func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
comment, err := CreateComment(&CreateCommentOptions{ comment, err := CreateComment(&CreateCommentOptions{
Type: COMMENT_TYPE_COMMENT, Type: CommentTypeComment,
Doer: doer, Doer: doer,
Repo: repo, Repo: repo,
Issue: issue, Issue: issue,
@ -350,7 +350,7 @@ func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content stri
} }
comment.Issue = issue comment.Issue = issue
if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{ if err = PrepareWebhooks(repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_CREATED, Action: api.HOOK_ISSUE_COMMENT_CREATED,
Issue: issue.APIFormat(), Issue: issue.APIFormat(),
Comment: comment.APIFormat(), Comment: comment.APIFormat(),
@ -371,7 +371,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
// Check if same reference from same commit has already existed. // Check if same reference from same commit has already existed.
has, err := x.Get(&Comment{ has, err := x.Get(&Comment{
Type: COMMENT_TYPE_COMMIT_REF, Type: CommentTypeCommitRef,
IssueID: issue.ID, IssueID: issue.ID,
CommitSHA: commitSHA, CommitSHA: commitSHA,
}) })
@ -382,7 +382,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
} }
_, err = CreateComment(&CreateCommentOptions{ _, err = CreateComment(&CreateCommentOptions{
Type: COMMENT_TYPE_COMMIT_REF, Type: CommentTypeCommitRef,
Doer: doer, Doer: doer,
Repo: repo, Repo: repo,
Issue: issue, Issue: issue,
@ -486,7 +486,7 @@ func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
if err = c.Issue.LoadAttributes(); err != nil { if err = c.Issue.LoadAttributes(); err != nil {
log.Error("Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err) log.Error("Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
} else if err = PrepareWebhooks(c.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{ } else if err = PrepareWebhooks(c.Issue.Repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_EDITED, Action: api.HOOK_ISSUE_COMMENT_EDITED,
Issue: c.Issue.APIFormat(), Issue: c.Issue.APIFormat(),
Comment: c.APIFormat(), Comment: c.APIFormat(),
@ -524,7 +524,7 @@ func DeleteCommentByID(doer *User, id int64) error {
return err return err
} }
if comment.Type == COMMENT_TYPE_COMMENT { if comment.Type == CommentTypeComment {
if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil { if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
return err return err
} }
@ -541,7 +541,7 @@ func DeleteCommentByID(doer *User, id int64) error {
if err = comment.Issue.LoadAttributes(); err != nil { if err = comment.Issue.LoadAttributes(); err != nil {
log.Error("Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err) log.Error("Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
} else if err = PrepareWebhooks(comment.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{ } else if err = PrepareWebhooks(comment.Issue.Repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_DELETED, Action: api.HOOK_ISSUE_COMMENT_DELETED,
Issue: comment.Issue.APIFormat(), Issue: comment.Issue.APIFormat(),
Comment: comment.APIFormat(), Comment: comment.APIFormat(),

View File

@ -6,7 +6,7 @@ package errors
import "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. // New is a wrapper of real errors.New function.
func New(text string) error { func New(text string) error {

View File

@ -250,7 +250,7 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return return
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_UPDATED, Action: api.HOOK_ISSUE_LABEL_UPDATED,
Index: issue.Index, Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(), PullRequest: issue.PullRequest.APIFormat(),
@ -258,7 +258,7 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
}) })
} else { } else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_LABEL_UPDATED, Action: api.HOOK_ISSUE_LABEL_UPDATED,
Index: issue.Index, Index: issue.Index,
Issue: issue.APIFormat(), Issue: issue.APIFormat(),
@ -354,7 +354,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
if issue.IsPull { if issue.IsPull {
@ -363,7 +363,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return err return err
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_CLEARED, Action: api.HOOK_ISSUE_LABEL_CLEARED,
Index: issue.Index, Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(), PullRequest: issue.PullRequest.APIFormat(),
@ -371,7 +371,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
}) })
} else { } else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_LABEL_CLEARED, Action: api.HOOK_ISSUE_LABEL_CLEARED,
Index: issue.Index, Index: issue.Index,
Issue: issue.APIFormat(), Issue: issue.APIFormat(),
@ -485,7 +485,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
if issue.IsPull { if issue.IsPull {
@ -502,7 +502,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
} else { } else {
apiPullRequest.Action = api.HOOK_ISSUE_REOPENED apiPullRequest.Action = api.HOOK_ISSUE_REOPENED
} }
err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest) err = PrepareWebhooks(repo, HookEventTypePullRequest, apiPullRequest)
} else { } else {
apiIssues := &api.IssuesPayload{ apiIssues := &api.IssuesPayload{
Index: issue.Index, Index: issue.Index,
@ -515,7 +515,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
} else { } else {
apiIssues.Action = api.HOOK_ISSUE_REOPENED apiIssues.Action = api.HOOK_ISSUE_REOPENED
} }
err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, apiIssues) err = PrepareWebhooks(repo, HookEventTypeIssues, apiIssues)
} }
if err != nil { if err != nil {
log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err) log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
@ -533,7 +533,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
if issue.IsPull { if issue.IsPull {
issue.PullRequest.Issue = issue issue.PullRequest.Issue = issue
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_EDITED, Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index, Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(), PullRequest: issue.PullRequest.APIFormat(),
@ -546,7 +546,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
}) })
} else { } else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_EDITED, Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index, Index: issue.Index,
Issue: issue.APIFormat(), Issue: issue.APIFormat(),
@ -575,7 +575,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
if issue.IsPull { if issue.IsPull {
issue.PullRequest.Issue = issue issue.PullRequest.Issue = issue
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_EDITED, Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index, Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(), PullRequest: issue.PullRequest.APIFormat(),
@ -588,7 +588,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
}) })
} else { } else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_EDITED, Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index, Index: issue.Index,
Issue: issue.APIFormat(), Issue: issue.APIFormat(),
@ -635,7 +635,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
} else { } else {
apiPullRequest.Action = api.HOOK_ISSUE_ASSIGNED apiPullRequest.Action = api.HOOK_ISSUE_ASSIGNED
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest) err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, apiPullRequest)
} else { } else {
apiIssues := &api.IssuesPayload{ apiIssues := &api.IssuesPayload{
Index: issue.Index, Index: issue.Index,
@ -648,7 +648,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
} else { } else {
apiIssues.Action = api.HOOK_ISSUE_ASSIGNED apiIssues.Action = api.HOOK_ISSUE_ASSIGNED
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, apiIssues) err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, apiIssues)
} }
if err != nil { if err != nil {
log.Error("PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err) log.Error("PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
@ -770,11 +770,11 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
LableIDs: labelIDs, LableIDs: labelIDs,
Attachments: uuids, Attachments: uuids,
}); err != nil { }); err != nil {
return fmt.Errorf("newIssue: %v", err) return fmt.Errorf("new issue: %v", err)
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
if err = NotifyWatchers(&Action{ if err = NotifyWatchers(&Action{
@ -793,7 +793,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
log.Error("MailParticipants: %v", err) log.Error("MailParticipants: %v", err)
} }
if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{ if err = PrepareWebhooks(repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_OPENED, Action: api.HOOK_ISSUE_OPENED,
Index: issue.Index, Index: issue.Index,
Issue: issue.APIFormat(), Issue: issue.APIFormat(),
@ -1001,7 +1001,7 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) {
issues := make([]*Issue, 0, conf.UI.IssuePagingNum) issues := make([]*Issue, 0, conf.UI.IssuePagingNum)
if err := sess.Find(&issues); err != nil { if err := sess.Find(&issues); err != nil {
return nil, fmt.Errorf("Find: %v", err) return nil, fmt.Errorf("find: %v", err)
} }
// FIXME: use IssueList to improve performance. // FIXME: use IssueList to improve performance.
@ -1108,9 +1108,9 @@ func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
} }
// PairsContains returns true when pairs list contains given issue. // 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 { for i := range ius {
if ius[i].IssueID == issueId && if ius[i].IssueID == issueID &&
ius[i].UserID == uid { ius[i].UserID == uid {
return i return i
} }
@ -1146,9 +1146,9 @@ func GetIssueUserPairsByMode(userID, repoID int64, filterMode FilterMode, isClos
} }
switch filterMode { switch filterMode {
case FILTER_MODE_ASSIGN: case FilterModeAssign:
sess.And("is_assigned=?", true) sess.And("is_assigned=?", true)
case FILTER_MODE_CREATE: case FilterModeCreate:
sess.And("is_poster=?", true) sess.And("is_poster=?", true)
default: default:
return ius, nil return ius, nil
@ -1212,10 +1212,10 @@ type IssueStats struct {
type FilterMode string type FilterMode string
const ( const (
FILTER_MODE_YOUR_REPOS FilterMode = "your_repositories" FilterModeYourRepos FilterMode = "your_repositories"
FILTER_MODE_ASSIGN FilterMode = "assigned" FilterModeAssign FilterMode = "assigned"
FILTER_MODE_CREATE FilterMode = "created_by" FilterModeCreate FilterMode = "created_by"
FILTER_MODE_MENTION FilterMode = "mentioned" FilterModeMention FilterMode = "mentioned"
) )
func parseCountResult(results []map[string][]byte) int64 { func parseCountResult(results []map[string][]byte) int64 {
@ -1264,7 +1264,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
} }
switch opts.FilterMode { switch opts.FilterMode {
case FILTER_MODE_YOUR_REPOS, FILTER_MODE_ASSIGN: case FilterModeYourRepos, FilterModeAssign:
stats.OpenCount, _ = countSession(opts). stats.OpenCount, _ = countSession(opts).
And("is_closed = ?", false). And("is_closed = ?", false).
Count(new(Issue)) Count(new(Issue))
@ -1272,7 +1272,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
stats.ClosedCount, _ = countSession(opts). stats.ClosedCount, _ = countSession(opts).
And("is_closed = ?", true). And("is_closed = ?", true).
Count(new(Issue)) Count(new(Issue))
case FILTER_MODE_CREATE: case FilterModeCreate:
stats.OpenCount, _ = countSession(opts). stats.OpenCount, _ = countSession(opts).
And("poster_id = ?", opts.UserID). And("poster_id = ?", opts.UserID).
And("is_closed = ?", false). And("is_closed = ?", false).
@ -1282,7 +1282,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
And("poster_id = ?", opts.UserID). And("poster_id = ?", opts.UserID).
And("is_closed = ?", true). And("is_closed = ?", true).
Count(new(Issue)) Count(new(Issue))
case FILTER_MODE_MENTION: case FilterModeMention:
stats.OpenCount, _ = countSession(opts). stats.OpenCount, _ = countSession(opts).
Join("INNER", "issue_user", "issue.id = issue_user.issue_id"). Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
And("issue_user.uid = ?", opts.UserID). And("issue_user.uid = ?", opts.UserID).
@ -1330,7 +1330,7 @@ func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterM
} }
switch filterMode { switch filterMode {
case FILTER_MODE_YOUR_REPOS: case FilterModeYourRepos:
if !hasAnyRepo { if !hasAnyRepo {
break break
} }
@ -1339,14 +1339,14 @@ func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterM
Count(new(Issue)) Count(new(Issue))
stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs). stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
Count(new(Issue)) Count(new(Issue))
case FILTER_MODE_ASSIGN: case FilterModeAssign:
stats.OpenCount, _ = countSession(false, isPull, repoID, nil). stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
And("assignee_id = ?", userID). And("assignee_id = ?", userID).
Count(new(Issue)) Count(new(Issue))
stats.ClosedCount, _ = countSession(true, isPull, repoID, nil). stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
And("assignee_id = ?", userID). And("assignee_id = ?", userID).
Count(new(Issue)) Count(new(Issue))
case FILTER_MODE_CREATE: case FilterModeCreate:
stats.OpenCount, _ = countSession(false, isPull, repoID, nil). stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
And("poster_id = ?", userID). And("poster_id = ?", userID).
Count(new(Issue)) Count(new(Issue))
@ -1372,10 +1372,10 @@ func GetRepoIssueStats(repoID, userID int64, filterMode FilterMode, isPull bool)
closedCountSession := countSession(true, isPull, repoID) closedCountSession := countSession(true, isPull, repoID)
switch filterMode { switch filterMode {
case FILTER_MODE_ASSIGN: case FilterModeAssign:
openCountSession.And("assignee_id = ?", userID) openCountSession.And("assignee_id = ?", userID)
closedCountSession.And("assignee_id = ?", userID) closedCountSession.And("assignee_id = ?", userID)
case FILTER_MODE_CREATE: case FilterModeCreate:
openCountSession.And("poster_id = ?", userID) openCountSession.And("poster_id = ?", userID)
closedCountSession.And("poster_id = ?", userID) closedCountSession.And("poster_id = ?", userID)
} }

View File

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

View File

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

View File

@ -343,7 +343,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
var hookAction api.HookIssueAction var hookAction api.HookIssueAction
@ -359,7 +359,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return err return err
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: hookAction, Action: hookAction,
Index: issue.Index, Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(), PullRequest: issue.PullRequest.APIFormat(),
@ -367,7 +367,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
}) })
} else { } else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{ err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: hookAction, Action: hookAction,
Index: issue.Index, Index: issue.Index,
Issue: issue.APIFormat(), Issue: issue.APIFormat(),

View File

@ -229,9 +229,13 @@ func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath), timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
"git", gitArgs...) "git", gitArgs...)
if err != nil { if err != nil {
desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, stderr) const fmtStr = "Failed to update mirror repository %q: %s"
log.Error(desc) log.Error(fmtStr, repoPath, stderr)
if err = Handle.Notices().Create(context.TODO(), NoticeTypeRepository, desc); err != nil { if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, repoPath, stderr),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err) log.Error("CreateRepositoryNotice: %v", err)
} }
return nil, false return nil, false
@ -247,9 +251,13 @@ func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
if _, stderr, err := process.ExecDir( if _, stderr, err := process.ExecDir(
timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath), timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
"git", "remote", "update", "--prune"); err != nil { "git", "remote", "update", "--prune"); err != nil {
desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, stderr) const fmtStr = "Failed to update mirror wiki repository %q: %s"
log.Error(desc) log.Error(fmtStr, wikiPath, stderr)
if err = Handle.Notices().Create(context.TODO(), NoticeTypeRepository, desc); err != nil { if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, wikiPath, stderr),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err) log.Error("CreateRepositoryNotice: %v", err)
} }
} }
@ -290,11 +298,11 @@ func DeleteMirrorByRepoID(repoID int64) error {
// MirrorUpdate checks and updates mirror repositories. // MirrorUpdate checks and updates mirror repositories.
func MirrorUpdate() { func MirrorUpdate() {
if taskStatusTable.IsRunning(_MIRROR_UPDATE) { if taskStatusTable.IsRunning(taskNameMirrorUpdate) {
return return
} }
taskStatusTable.Start(_MIRROR_UPDATE) taskStatusTable.Start(taskNameMirrorUpdate)
defer taskStatusTable.Stop(_MIRROR_UPDATE) defer taskStatusTable.Stop(taskNameMirrorUpdate)
log.Trace("Doing: MirrorUpdate") log.Trace("Doing: MirrorUpdate")

View File

@ -41,7 +41,7 @@ func (org *User) GetTeam(name string) (*Team, error) {
} }
func (org *User) getOwnerTeam(e Engine) (*Team, error) { func (org *User) getOwnerTeam(e Engine) (*Team, error) {
return org.getTeam(e, OWNER_TEAM) return org.getTeam(e, ownerTeamName)
} }
// GetOwnerTeam returns owner team of organization. // GetOwnerTeam returns owner team of organization.
@ -73,7 +73,7 @@ func (org *User) GetMembers(limit int) error {
org.Members = make([]*User, len(ous)) org.Members = make([]*User, len(ous))
for i, ou := range ous { for i, ou := range ous {
org.Members[i], err = Handle.Users().GetByID(context.TODO(), ou.Uid) org.Members[i], err = Handle.Users().GetByID(context.TODO(), ou.UID)
if err != nil { if err != nil {
return err return err
} }
@ -139,7 +139,7 @@ func CreateOrganization(org, owner *User) (err error) {
// Add initial creator to organization and owner team. // Add initial creator to organization and owner team.
if _, err = sess.Insert(&OrgUser{ if _, err = sess.Insert(&OrgUser{
Uid: owner.ID, UID: owner.ID,
OrgID: org.ID, OrgID: org.ID,
IsOwner: true, IsOwner: true,
NumTeams: 1, NumTeams: 1,
@ -150,8 +150,8 @@ func CreateOrganization(org, owner *User) (err error) {
// Create default owner team. // Create default owner team.
t := &Team{ t := &Team{
OrgID: org.ID, OrgID: org.ID,
LowerName: strings.ToLower(OWNER_TEAM), LowerName: strings.ToLower(ownerTeamName),
Name: OWNER_TEAM, Name: ownerTeamName,
Authorize: AccessModeOwner, Authorize: AccessModeOwner,
NumMembers: 1, NumMembers: 1,
} }
@ -247,7 +247,7 @@ func DeleteOrganization(org *User) error {
// OrgUser represents relations of organizations and their members. // OrgUser represents relations of organizations and their members.
type OrgUser struct { type OrgUser struct {
ID int64 `gorm:"primaryKey"` ID int64 `gorm:"primaryKey"`
Uid int64 `xorm:"INDEX UNIQUE(s)" gorm:"uniqueIndex:org_user_user_org_unique;index;not null"` UID int64 `xorm:"uid INDEX UNIQUE(s)" gorm:"column:uid;uniqueIndex:org_user_user_org_unique;index;not null"`
OrgID int64 `xorm:"INDEX UNIQUE(s)" gorm:"uniqueIndex:org_user_user_org_unique;index;not null"` OrgID int64 `xorm:"INDEX UNIQUE(s)" gorm:"uniqueIndex:org_user_user_org_unique;index;not null"`
IsPublic bool `gorm:"not null;default:FALSE"` IsPublic bool `gorm:"not null;default:FALSE"`
IsOwner bool `gorm:"not null;default:FALSE"` IsOwner bool `gorm:"not null;default:FALSE"`
@ -261,14 +261,14 @@ func IsOrganizationOwner(orgID, userID int64) bool {
} }
// IsOrganizationMember returns true if given user is member of organization. // IsOrganizationMember returns true if given user is member of organization.
func IsOrganizationMember(orgId, uid int64) bool { func IsOrganizationMember(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser)) has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).Get(new(OrgUser))
return has return has
} }
// IsPublicMembership returns true if given user public his/her membership. // IsPublicMembership returns true if given user public his/her membership.
func IsPublicMembership(orgId, uid int64) bool { func IsPublicMembership(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser)) has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).And("is_public=?", true).Get(new(OrgUser))
return has return has
} }
@ -349,7 +349,7 @@ func AddOrgUser(orgID, uid int64) error {
} }
ou := &OrgUser{ ou := &OrgUser{
Uid: uid, UID: uid,
OrgID: orgID, OrgID: orgID,
} }

View File

@ -15,7 +15,7 @@ import (
"gogs.io/gogs/internal/errutil" "gogs.io/gogs/internal/errutil"
) )
const OWNER_TEAM = "Owners" const ownerTeamName = "Owners"
// Team represents a organization team. // Team represents a organization team.
type Team struct { type Team struct {
@ -43,7 +43,7 @@ func (t *Team) AfterSet(colName string, _ xorm.Cell) {
// IsOwnerTeam returns true if team is owner team. // IsOwnerTeam returns true if team is owner team.
func (t *Team) IsOwnerTeam() bool { func (t *Team) IsOwnerTeam() bool {
return t.Name == OWNER_TEAM return t.Name == ownerTeamName
} }
// HasWriteAccess returns true if team has at least write level access mode. // HasWriteAccess returns true if team has at least write level access mode.

View File

@ -30,16 +30,16 @@ var PullRequestQueue = sync.NewUniqueQueue(1000)
type PullRequestType int type PullRequestType int
const ( const (
PULL_REQUEST_GOGS PullRequestType = iota PullRequestTypeGogs PullRequestType = iota
PLLL_ERQUEST_GIT PullRequestTypeGit
) )
type PullRequestStatus int type PullRequestStatus int
const ( const (
PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota PullRequestStatusConflict PullRequestStatus = iota
PULL_REQUEST_STATUS_CHECKING PullRequestStatusChecking
PULL_REQUEST_STATUS_MERGEABLE PullRequestStatusMergeable
) )
// PullRequest represents relation between pull request and repositories. // PullRequest represents relation between pull request and repositories.
@ -161,8 +161,8 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
HasMerged: pr.HasMerged, HasMerged: pr.HasMerged,
} }
if pr.Status != PULL_REQUEST_STATUS_CHECKING { if pr.Status != PullRequestStatusChecking {
mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT mergeable := pr.Status != PullRequestStatusConflict
apiPullRequest.Mergeable = &mergeable apiPullRequest.Mergeable = &mergeable
} }
if pr.HasMerged { if pr.HasMerged {
@ -176,20 +176,20 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
// IsChecking returns true if this pull request is still checking conflict. // IsChecking returns true if this pull request is still checking conflict.
func (pr *PullRequest) IsChecking() bool { func (pr *PullRequest) IsChecking() bool {
return pr.Status == PULL_REQUEST_STATUS_CHECKING return pr.Status == PullRequestStatusChecking
} }
// CanAutoMerge returns true if this pull request can be merged automatically. // CanAutoMerge returns true if this pull request can be merged automatically.
func (pr *PullRequest) CanAutoMerge() bool { func (pr *PullRequest) CanAutoMerge() bool {
return pr.Status == PULL_REQUEST_STATUS_MERGEABLE return pr.Status == PullRequestStatusMergeable
} }
// MergeStyle represents the approach to merge commits into base branch. // MergeStyle represents the approach to merge commits into base branch.
type MergeStyle string type MergeStyle string
const ( const (
MERGE_STYLE_REGULAR MergeStyle = "create_merge_commit" MergeStyleRegular MergeStyle = "create_merge_commit"
MERGE_STYLE_REBASE MergeStyle = "rebase_before_merging" MergeStyleRebase MergeStyle = "rebase_before_merging"
) )
// Merge merges pull request to base repository. // Merge merges pull request to base repository.
@ -254,12 +254,12 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
remoteHeadBranch := "head_repo/" + pr.HeadBranch remoteHeadBranch := "head_repo/" + pr.HeadBranch
// Check if merge style is allowed, reset to default style if not // Check if merge style is allowed, reset to default style if not
if mergeStyle == MERGE_STYLE_REBASE && !pr.BaseRepo.PullsAllowRebase { if mergeStyle == MergeStyleRebase && !pr.BaseRepo.PullsAllowRebase {
mergeStyle = MERGE_STYLE_REGULAR mergeStyle = MergeStyleRegular
} }
switch mergeStyle { switch mergeStyle {
case MERGE_STYLE_REGULAR: // Create merge commit case MergeStyleRegular: // Create merge commit
// Merge changes from head branch. // Merge changes from head branch.
if _, stderr, err = process.ExecDir(-1, tmpBasePath, if _, stderr, err = process.ExecDir(-1, tmpBasePath,
@ -277,7 +277,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr) return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
} }
case MERGE_STYLE_REBASE: // Rebase before merging case MergeStyleRebase: // Rebase before merging
// Rebase head branch based on base branch, this creates a non-branch commit state. // Rebase head branch based on base branch, this creates a non-branch commit state.
if _, stderr, err = process.ExecDir(-1, tmpBasePath, if _, stderr, err = process.ExecDir(-1, tmpBasePath,
@ -332,7 +332,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
if err = Handle.Actions().MergePullRequest(ctx, doer, pr.Issue.Repo.Owner, pr.Issue.Repo, pr.Issue); err != nil { if err = Handle.Actions().MergePullRequest(ctx, doer, pr.Issue.Repo.Owner, pr.Issue.Repo, pr.Issue); err != nil {
@ -344,7 +344,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
log.Error("LoadAttributes: %v", err) log.Error("LoadAttributes: %v", err)
return nil return nil
} }
if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ if err = PrepareWebhooks(pr.Issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_CLOSED, Action: api.HOOK_ISSUE_CLOSED,
Index: pr.Index, Index: pr.Index,
PullRequest: pr.APIFormat(), PullRequest: pr.APIFormat(),
@ -369,7 +369,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
log.Error("Failed to get base branch %q commit: %v", pr.BaseBranch, err) log.Error("Failed to get base branch %q commit: %v", pr.BaseBranch, err)
return nil return nil
} }
if mergeStyle == MERGE_STYLE_REGULAR { if mergeStyle == MergeStyleRegular {
commits = append([]*git.Commit{mergeCommit}, commits...) commits = append([]*git.Commit{mergeCommit}, commits...)
} }
@ -389,7 +389,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
Pusher: pr.HeadRepo.MustOwner().APIFormat(), Pusher: pr.HeadRepo.MustOwner().APIFormat(),
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
} }
if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil { if err = PrepareWebhooks(pr.BaseRepo, HookEventTypePush, p); err != nil {
log.Error("Failed to prepare webhooks: %v", err) log.Error("Failed to prepare webhooks: %v", err)
return nil return nil
} }
@ -432,13 +432,13 @@ func (pr *PullRequest) testPatch() (err error) {
} }
args = append(args, patchPath) args = append(args, patchPath)
pr.Status = PULL_REQUEST_STATUS_CHECKING pr.Status = PullRequestStatusChecking
_, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(), _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID), fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
"git", args...) "git", args...)
if err != nil { if err != nil {
log.Trace("PullRequest[%d].testPatch (apply): has conflict\n%s", pr.ID, stderr) log.Trace("PullRequest[%d].testPatch (apply): has conflict\n%s", pr.ID, stderr)
pr.Status = PULL_REQUEST_STATUS_CONFLICT pr.Status = PullRequestStatusConflict
return nil return nil
} }
return nil return nil
@ -472,8 +472,8 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
return fmt.Errorf("testPatch: %v", err) return fmt.Errorf("testPatch: %v", err)
} }
// No conflict appears after test means mergeable. // No conflict appears after test means mergeable.
if pr.Status == PULL_REQUEST_STATUS_CHECKING { if pr.Status == PullRequestStatusChecking {
pr.Status = PULL_REQUEST_STATUS_MERGEABLE pr.Status = PullRequestStatusMergeable
} }
pr.IssueID = pull.ID pr.IssueID = pull.ID
@ -482,7 +482,7 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
if err = NotifyWatchers(&Action{ if err = NotifyWatchers(&Action{
@ -503,7 +503,7 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
pr.Issue = pull pr.Issue = pull
pull.PullRequest = pr pull.PullRequest = pr
if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ if err = PrepareWebhooks(repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_OPENED, Action: api.HOOK_ISSUE_OPENED,
Index: pull.Index, Index: pull.Index,
PullRequest: pr.APIFormat(), PullRequest: pr.APIFormat(),
@ -705,7 +705,7 @@ func (pr *PullRequest) PushToBaseRepo() (err error) {
// AddToTaskQueue adds itself to pull request test task queue. // AddToTaskQueue adds itself to pull request test task queue.
func (pr *PullRequest) AddToTaskQueue() { func (pr *PullRequest) AddToTaskQueue() {
go PullRequestQueue.AddFunc(pr.ID, func() { go PullRequestQueue.AddFunc(pr.ID, func() {
pr.Status = PULL_REQUEST_STATUS_CHECKING pr.Status = PullRequestStatusChecking
if err := pr.UpdateCols("status"); err != nil { if err := pr.UpdateCols("status"); err != nil {
log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err) log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
} }
@ -795,7 +795,7 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool
log.Error("LoadAttributes: %v", err) log.Error("LoadAttributes: %v", err)
continue continue
} }
if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ if err = PrepareWebhooks(pr.Issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_SYNCHRONIZED, Action: api.HOOK_ISSUE_SYNCHRONIZED,
Index: pr.Issue.Index, Index: pr.Issue.Index,
PullRequest: pr.Issue.PullRequest.APIFormat(), PullRequest: pr.Issue.PullRequest.APIFormat(),
@ -826,8 +826,8 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool
// and set to be either conflict or mergeable. // and set to be either conflict or mergeable.
func (pr *PullRequest) checkAndUpdateStatus() { func (pr *PullRequest) checkAndUpdateStatus() {
// Status is not changed to conflict means mergeable. // Status is not changed to conflict means mergeable.
if pr.Status == PULL_REQUEST_STATUS_CHECKING { if pr.Status == PullRequestStatusChecking {
pr.Status = PULL_REQUEST_STATUS_MERGEABLE pr.Status = PullRequestStatusMergeable
} }
// Make sure there is no waiting test to process before leaving the checking status. // Make sure there is no waiting test to process before leaving the checking status.
@ -843,7 +843,7 @@ func (pr *PullRequest) checkAndUpdateStatus() {
func TestPullRequests() { func TestPullRequests() {
prs := make([]*PullRequest, 0, 10) prs := make([]*PullRequest, 0, 10)
_ = x.Iterate(PullRequest{ _ = x.Iterate(PullRequest{
Status: PULL_REQUEST_STATUS_CHECKING, Status: PullRequestStatusChecking,
}, },
func(idx int, bean any) error { func(idx int, bean any) error {
pr := bean.(*PullRequest) pr := bean.(*PullRequest)

View File

@ -150,7 +150,7 @@ func createTag(gitRepo *git.Repository, r *Release) error {
} }
func (r *Release) preparePublishWebhooks() { func (r *Release) preparePublishWebhooks() {
if err := PrepareWebhooks(r.Repo, HOOK_EVENT_RELEASE, &api.ReleasePayload{ if err := PrepareWebhooks(r.Repo, HookEventTypeRelease, &api.ReleasePayload{
Action: api.HOOK_RELEASE_PUBLISHED, Action: api.HOOK_RELEASE_PUBLISHED,
Release: r.APIFormat(), Release: r.APIFormat(),
Repository: r.Repo.APIFormatLegacy(nil), Repository: r.Repo.APIFormatLegacy(nil),
@ -181,7 +181,7 @@ func NewRelease(gitRepo *git.Repository, r *Release, uuids []string) error {
} }
if _, err = sess.Insert(r); err != nil { if _, err = sess.Insert(r); err != nil {
return fmt.Errorf("Insert: %v", err) return fmt.Errorf("insert: %v", err)
} }
if len(uuids) > 0 { if len(uuids) > 0 {
@ -191,7 +191,7 @@ func NewRelease(gitRepo *git.Repository, r *Release, uuids []string) error {
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
// Only send webhook when actually published, skip drafts // Only send webhook when actually published, skip drafts
@ -236,7 +236,7 @@ func GetRelease(repoID int64, tagName string) (*Release, error) {
r := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)} r := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
if _, err = x.Get(r); err != nil { if _, err = x.Get(r); err != nil {
return nil, fmt.Errorf("Get: %v", err) return nil, fmt.Errorf("get: %v", err)
} }
return r, r.LoadAttributes() return r, r.LoadAttributes()
@ -334,7 +334,7 @@ func UpdateRelease(doer *User, gitRepo *git.Repository, r *Release, isPublish bo
} }
if err = sess.Commit(); err != nil { if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err) return fmt.Errorf("commit: %v", err)
} }
if !isPublish { if !isPublish {
@ -370,7 +370,7 @@ func DeleteReleaseOfRepoByID(repoID, id int64) error {
} }
if _, err = x.Id(rel.ID).Delete(new(Release)); err != nil { if _, err = x.Id(rel.ID).Delete(new(Release)); err != nil {
return fmt.Errorf("Delete: %v", err) return fmt.Errorf("delete: %v", err)
} }
return nil return nil

View File

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

View File

@ -64,18 +64,18 @@ func (ErrBranchNotExist) NotFound() bool {
return true return true
} }
func (repo *Repository) GetBranch(name string) (*Branch, error) { func (r *Repository) GetBranch(name string) (*Branch, error) {
if !git.RepoHasBranch(repo.RepoPath(), name) { if !git.RepoHasBranch(r.RepoPath(), name) {
return nil, ErrBranchNotExist{args: map[string]any{"name": name}} return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
} }
return &Branch{ return &Branch{
RepoPath: repo.RepoPath(), RepoPath: r.RepoPath(),
Name: name, Name: name,
}, nil }, nil
} }
func (repo *Repository) GetBranches() ([]*Branch, error) { func (r *Repository) GetBranches() ([]*Branch, error) {
return GetBranchesByPath(repo.RepoPath()) return GetBranchesByPath(r.RepoPath())
} }
func (br *Branch) GetCommit() (*git.Commit, error) { func (br *Branch) GetCommit() (*git.Commit, error) {
@ -147,12 +147,12 @@ func UpdateProtectBranch(protectBranch *ProtectBranch) (err error) {
if protectBranch.ID == 0 { if protectBranch.ID == 0 {
if _, err = sess.Insert(protectBranch); err != nil { if _, err = sess.Insert(protectBranch); err != nil {
return fmt.Errorf("Insert: %v", err) return fmt.Errorf("insert: %v", err)
} }
} }
if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil { if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
return fmt.Errorf("Update: %v", err) return fmt.Errorf("update: %v", err)
} }
return sess.Commit() return sess.Commit()
@ -213,7 +213,7 @@ func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whit
// Make sure protectBranch.ID is not 0 for whitelists // Make sure protectBranch.ID is not 0 for whitelists
if protectBranch.ID == 0 { if protectBranch.ID == 0 {
if _, err = x.Insert(protectBranch); err != nil { if _, err = x.Insert(protectBranch); err != nil {
return fmt.Errorf("Insert: %v", err) return fmt.Errorf("insert: %v", err)
} }
} }

View File

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

View File

@ -32,14 +32,14 @@ import (
) )
const ( const (
ENV_AUTH_USER_ID = "GOGS_AUTH_USER_ID" EnvAuthUserID = "GOGS_AUTH_USER_ID"
ENV_AUTH_USER_NAME = "GOGS_AUTH_USER_NAME" EnvAuthUserName = "GOGS_AUTH_USER_NAME"
ENV_AUTH_USER_EMAIL = "GOGS_AUTH_USER_EMAIL" EnvAuthUserEmail = "GOGS_AUTH_USER_EMAIL"
ENV_REPO_OWNER_NAME = "GOGS_REPO_OWNER_NAME" EnvRepoOwnerName = "GOGS_REPO_OWNER_NAME"
ENV_REPO_OWNER_SALT_MD5 = "GOGS_REPO_OWNER_SALT_MD5" EnvRepoOwnerSaltMd5 = "GOGS_REPO_OWNER_SALT_MD5"
ENV_REPO_ID = "GOGS_REPO_ID" EnvRepoID = "GOGS_REPO_ID"
ENV_REPO_NAME = "GOGS_REPO_NAME" EnvRepoName = "GOGS_REPO_NAME"
ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_REPO_CUSTOM_HOOKS_PATH" EnvRepoCustomHooksPath = "GOGS_REPO_CUSTOM_HOOKS_PATH"
) )
type ComposeHookEnvsOptions struct { type ComposeHookEnvsOptions struct {
@ -54,14 +54,14 @@ type ComposeHookEnvsOptions struct {
func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string { func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
envs := []string{ envs := []string{
"SSH_ORIGINAL_COMMAND=1", "SSH_ORIGINAL_COMMAND=1",
ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID), EnvAuthUserID + "=" + com.ToStr(opts.AuthUser.ID),
ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name, EnvAuthUserName + "=" + opts.AuthUser.Name,
ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email, EnvAuthUserEmail + "=" + opts.AuthUser.Email,
ENV_REPO_OWNER_NAME + "=" + opts.OwnerName, EnvRepoOwnerName + "=" + opts.OwnerName,
ENV_REPO_OWNER_SALT_MD5 + "=" + cryptoutil.MD5(opts.OwnerSalt), EnvRepoOwnerSaltMd5 + "=" + cryptoutil.MD5(opts.OwnerSalt),
ENV_REPO_ID + "=" + com.ToStr(opts.RepoID), EnvRepoID + "=" + com.ToStr(opts.RepoID),
ENV_REPO_NAME + "=" + opts.RepoName, EnvRepoName + "=" + opts.RepoName,
ENV_REPO_CUSTOM_HOOKS_PATH + "=" + filepath.Join(opts.RepoPath, "custom_hooks"), EnvRepoCustomHooksPath + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
} }
return envs return envs
} }
@ -92,13 +92,13 @@ func discardLocalRepoBranchChanges(localPath, branch string) error {
return nil return nil
} }
func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error { func (r *Repository) DiscardLocalRepoBranchChanges(branch string) error {
return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch) return discardLocalRepoBranchChanges(r.LocalCopyPath(), branch)
} }
// CheckoutNewBranch checks out to a new branch from the a branch name. // CheckoutNewBranch checks out to a new branch from the a branch name.
func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error { func (r *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
if err := git.Checkout(repo.LocalCopyPath(), newBranch, git.CheckoutOptions{ if err := git.Checkout(r.LocalCopyPath(), newBranch, git.CheckoutOptions{
BaseBranch: oldBranch, BaseBranch: oldBranch,
Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second, Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second,
}); err != nil { }); err != nil {
@ -118,23 +118,23 @@ type UpdateRepoFileOptions struct {
} }
// UpdateRepoFile adds or updates a file in repository. // 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. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.NewTreeName) { if isRepositoryGitPath(opts.NewTreeName) {
return errors.Errorf("bad tree path %q", opts.NewTreeName) return errors.Errorf("bad tree path %q", opts.NewTreeName)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err) return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil { } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
} }
repoPath := repo.RepoPath() repoPath := r.RepoPath()
localPath := repo.LocalCopyPath() localPath := r.LocalCopyPath()
if opts.OldBranch != opts.NewBranch { if opts.OldBranch != opts.NewBranch {
// Directly return error if new branch already exists in the server // 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) 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{ CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer, AuthUser: doer,
OwnerName: repo.MustOwner().Name, OwnerName: r.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt, OwnerSalt: r.MustOwner().Salt,
RepoID: repo.ID, RepoID: r.ID,
RepoName: repo.Name, RepoName: r.Name,
RepoPath: repo.RepoPath(), 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. // 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. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(treePath) { if isRepositoryGitPath(treePath) {
return nil, errors.Errorf("bad tree path %q", treePath) return nil, errors.Errorf("bad tree path %q", treePath)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil { if err = r.DiscardLocalRepoBranchChanges(branch); err != nil {
return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err) return nil, fmt.Errorf("discard local r branch[%s] changes: %v", branch, err)
} else if err = repo.UpdateLocalCopyBranch(branch); err != nil { } else if err = r.UpdateLocalCopyBranch(branch); err != nil {
return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err) return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
} }
localPath := repo.LocalCopyPath() localPath := r.LocalCopyPath()
filePath := path.Join(localPath, treePath) filePath := path.Join(localPath, treePath)
if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return nil, err return nil, err
@ -257,7 +257,7 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
return nil, fmt.Errorf("start: %v", err) 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) defer process.Remove(pid)
diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars) diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
@ -288,28 +288,28 @@ type DeleteRepoFileOptions struct {
Message string 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. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.TreePath) { if isRepositoryGitPath(opts.TreePath) {
return errors.Errorf("bad tree path %q", opts.TreePath) return errors.Errorf("bad tree path %q", opts.TreePath)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err) return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil { } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
} }
if opts.OldBranch != opts.NewBranch { 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) 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 { if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
return fmt.Errorf("remove file %q: %v", opts.TreePath, err) 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{ CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer, AuthUser: doer,
OwnerName: repo.MustOwner().Name, OwnerName: r.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt, OwnerSalt: r.MustOwner().Salt,
RepoID: repo.ID, RepoID: r.ID,
RepoName: repo.Name, RepoName: r.Name,
RepoPath: repo.RepoPath(), RepoPath: r.RepoPath(),
}), }),
}, },
}, },
@ -509,7 +509,7 @@ func isRepositoryGitPath(path string) bool {
strings.Contains(path, `.git.\`) 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 { if len(opts.Files) == 0 {
return nil 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) return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err) return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil { } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
} }
if opts.OldBranch != opts.NewBranch { 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) 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) dirPath := path.Join(localPath, opts.TreePath)
if err = os.MkdirAll(dirPath, os.ModePerm); err != nil { if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
return err return err
@ -588,11 +588,11 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
CommandOptions: git.CommandOptions{ CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer, AuthUser: doer,
OwnerName: repo.MustOwner().Name, OwnerName: r.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt, OwnerSalt: r.MustOwner().Salt,
RepoID: repo.ID, RepoID: r.ID,
RepoName: repo.Name, RepoName: r.Name,
RepoPath: repo.RepoPath(), RepoPath: r.RepoPath(),
}), }),
}, },
}, },

View File

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

View File

@ -23,7 +23,7 @@ func TestRepository_ComposeMetas(t *testing.T) {
metas := repo.ComposeMetas() metas := repo.ComposeMetas()
assert.Equal(t, metas["repoLink"], repo.Link()) assert.Equal(t, metas["repoLink"], repo.Link())
// Should no format and style if no external tracker is configured // Should not have format and style if no external tracker is configured
_, ok := metas["format"] _, ok := metas["format"]
assert.False(t, ok) assert.False(t, ok)
_, ok = metas["style"] _, ok = metas["style"]

View File

@ -82,12 +82,12 @@ func main() {
if len(ti.Indexes) > 0 { if len(ti.Indexes) > 0 {
_, _ = w.WriteString("Indexes: \n") _, _ = w.WriteString("Indexes: \n")
for _, index := range ti.Indexes { for _, index := range ti.Indexes {
_, _ = w.WriteString(fmt.Sprintf("\t%q", index.Name)) _, _ = fmt.Fprintf(w, "\t%q", index.Name)
if index.Class != "" { if index.Class != "" {
_, _ = w.WriteString(fmt.Sprintf(" %s", index.Class)) _, _ = fmt.Fprintf(w, " %s", index.Class)
} }
if index.Type != "" { if index.Type != "" {
_, _ = w.WriteString(fmt.Sprintf(", %s", index.Type)) _, _ = fmt.Fprintf(w, ", %s", index.Type)
} }
if len(index.Fields) > 0 { if len(index.Fields) > 0 {
@ -95,7 +95,7 @@ func main() {
for i := range index.Fields { for i := range index.Fields {
fields[i] = index.Fields[i].DBName fields[i] = index.Fields[i].DBName
} }
_, _ = w.WriteString(fmt.Sprintf(" (%s)", strings.Join(fields, ", "))) _, _ = fmt.Fprintf(w, " (%s)", strings.Join(fields, ", "))
} }
_, _ = w.WriteString("\n") _, _ = w.WriteString("\n")
} }

View File

@ -29,7 +29,7 @@ import (
) )
const ( const (
_TPL_PUBLICK_KEY = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n" tplPublicKey = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
) )
var sshOpLocker sync.Mutex var sshOpLocker sync.Mutex
@ -37,8 +37,8 @@ var sshOpLocker sync.Mutex
type KeyType int type KeyType int
const ( const (
KEY_TYPE_USER = iota + 1 KeyTypeUser = iota + 1
KEY_TYPE_DEPLOY KeyTypeDeploy
) )
// PublicKey represents a user or deploy SSH public key. // PublicKey represents a user or deploy SSH public key.
@ -85,12 +85,12 @@ func (k *PublicKey) OmitEmail() string {
// AuthorizedString returns formatted public key string for authorized_keys file. // AuthorizedString returns formatted public key string for authorized_keys file.
func (k *PublicKey) AuthorizedString() string { func (k *PublicKey) AuthorizedString() string {
return fmt.Sprintf(_TPL_PUBLICK_KEY, conf.AppPath(), k.ID, conf.CustomConf, k.Content) return fmt.Sprintf(tplPublicKey, conf.AppPath(), k.ID, conf.CustomConf, k.Content)
} }
// IsDeployKey returns true if the public key is used as deploy key. // IsDeployKey returns true if the public key is used as deploy key.
func (k *PublicKey) IsDeployKey() bool { func (k *PublicKey) IsDeployKey() bool {
return k.Type == KEY_TYPE_DEPLOY return k.Type == KeyTypeDeploy
} }
func extractTypeFromBase64Key(key string) (string, error) { func extractTypeFromBase64Key(key string) (string, error) {
@ -362,7 +362,7 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
func checkKeyContent(content string) error { func checkKeyContent(content string) error {
has, err := x.Get(&PublicKey{ has, err := x.Get(&PublicKey{
Content: content, Content: content,
Type: KEY_TYPE_USER, Type: KeyTypeUser,
}) })
if err != nil { if err != nil {
return err return err
@ -402,7 +402,7 @@ func addKey(e Engine, key *PublicKey) (err error) {
// AddPublicKey adds new public key to database and authorized_keys file. // AddPublicKey adds new public key to database and authorized_keys file.
func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) { func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
log.Trace(content) log.Trace("Add public key: %s", content)
if err := checkKeyContent(content); err != nil { if err := checkKeyContent(content); err != nil {
return nil, err return nil, err
} }
@ -426,7 +426,7 @@ func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
Name: name, Name: name,
Content: content, Content: content,
Mode: AccessModeWrite, Mode: AccessModeWrite,
Type: KEY_TYPE_USER, Type: KeyTypeUser,
} }
if err = addKey(sess, key); err != nil { if err = addKey(sess, key); err != nil {
return nil, fmt.Errorf("addKey: %v", err) return nil, fmt.Errorf("addKey: %v", err)
@ -659,7 +659,7 @@ func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
pkey := &PublicKey{ pkey := &PublicKey{
Content: content, Content: content,
Mode: AccessModeRead, Mode: AccessModeRead,
Type: KEY_TYPE_DEPLOY, Type: KeyTypeDeploy,
} }
has, err := x.Get(pkey) has, err := x.Get(pkey)
if err != nil { if err != nil {

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

View File

@ -88,9 +88,9 @@ type HookEvent struct {
type HookStatus int type HookStatus int
const ( const (
HOOK_STATUS_NONE = iota HookStatusNone = iota
HOOK_STATUS_SUCCEED HookStatusSucceed
HOOK_STATUS_FAILED HookStatusFailed
) )
// Webhook represents a web hook object. // Webhook represents a web hook object.
@ -162,49 +162,49 @@ func (w *Webhook) UpdateEvent() error {
// HasCreateEvent returns true if hook enabled create event. // HasCreateEvent returns true if hook enabled create event.
func (w *Webhook) HasCreateEvent() bool { func (w *Webhook) HasCreateEvent() bool {
return w.SendEverything || return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Create) (w.ChooseEvents && w.Create)
} }
// HasDeleteEvent returns true if hook enabled delete event. // HasDeleteEvent returns true if hook enabled delete event.
func (w *Webhook) HasDeleteEvent() bool { func (w *Webhook) HasDeleteEvent() bool {
return w.SendEverything || return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Delete) (w.ChooseEvents && w.Delete)
} }
// HasForkEvent returns true if hook enabled fork event. // HasForkEvent returns true if hook enabled fork event.
func (w *Webhook) HasForkEvent() bool { func (w *Webhook) HasForkEvent() bool {
return w.SendEverything || return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Fork) (w.ChooseEvents && w.Fork)
} }
// HasPushEvent returns true if hook enabled push event. // HasPushEvent returns true if hook enabled push event.
func (w *Webhook) HasPushEvent() bool { func (w *Webhook) HasPushEvent() bool {
return w.PushOnly || w.SendEverything || return w.PushOnly || w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Push) (w.ChooseEvents && w.Push)
} }
// HasIssuesEvent returns true if hook enabled issues event. // HasIssuesEvent returns true if hook enabled issues event.
func (w *Webhook) HasIssuesEvent() bool { func (w *Webhook) HasIssuesEvent() bool {
return w.SendEverything || return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Issues) (w.ChooseEvents && w.Issues)
} }
// HasPullRequestEvent returns true if hook enabled pull request event. // HasPullRequestEvent returns true if hook enabled pull request event.
func (w *Webhook) HasPullRequestEvent() bool { func (w *Webhook) HasPullRequestEvent() bool {
return w.SendEverything || return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.PullRequest) (w.ChooseEvents && w.PullRequest)
} }
// HasIssueCommentEvent returns true if hook enabled issue comment event. // HasIssueCommentEvent returns true if hook enabled issue comment event.
func (w *Webhook) HasIssueCommentEvent() bool { func (w *Webhook) HasIssueCommentEvent() bool {
return w.SendEverything || return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.IssueComment) (w.ChooseEvents && w.IssueComment)
} }
// HasReleaseEvent returns true if hook enabled release event. // HasReleaseEvent returns true if hook enabled release event.
func (w *Webhook) HasReleaseEvent() bool { func (w *Webhook) HasReleaseEvent() bool {
return w.SendEverything || return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Release) (w.ChooseEvents && w.Release)
} }
type eventChecker struct { type eventChecker struct {
@ -215,14 +215,14 @@ type eventChecker struct {
func (w *Webhook) EventsArray() []string { func (w *Webhook) EventsArray() []string {
events := make([]string, 0, 8) events := make([]string, 0, 8)
eventCheckers := []eventChecker{ eventCheckers := []eventChecker{
{w.HasCreateEvent, HOOK_EVENT_CREATE}, {w.HasCreateEvent, HookEventTypeCreate},
{w.HasDeleteEvent, HOOK_EVENT_DELETE}, {w.HasDeleteEvent, HookEventTypeDelete},
{w.HasForkEvent, HOOK_EVENT_FORK}, {w.HasForkEvent, HookEventTypeFork},
{w.HasPushEvent, HOOK_EVENT_PUSH}, {w.HasPushEvent, HookEventTypePush},
{w.HasIssuesEvent, HOOK_EVENT_ISSUES}, {w.HasIssuesEvent, HookEventTypeIssues},
{w.HasPullRequestEvent, HOOK_EVENT_PULL_REQUEST}, {w.HasPullRequestEvent, HookEventTypePullRequest},
{w.HasIssueCommentEvent, HOOK_EVENT_ISSUE_COMMENT}, {w.HasIssueCommentEvent, HookEventTypeIssueComment},
{w.HasReleaseEvent, HOOK_EVENT_RELEASE}, {w.HasReleaseEvent, HookEventTypeRelease},
} }
for _, c := range eventCheckers { for _, c := range eventCheckers {
if c.checker() { if c.checker() {
@ -409,14 +409,14 @@ func IsValidHookTaskType(name string) bool {
type HookEventType string type HookEventType string
const ( const (
HOOK_EVENT_CREATE HookEventType = "create" HookEventTypeCreate HookEventType = "create"
HOOK_EVENT_DELETE HookEventType = "delete" HookEventTypeDelete HookEventType = "delete"
HOOK_EVENT_FORK HookEventType = "fork" HookEventTypeFork HookEventType = "fork"
HOOK_EVENT_PUSH HookEventType = "push" HookEventTypePush HookEventType = "push"
HOOK_EVENT_ISSUES HookEventType = "issues" HookEventTypeIssues HookEventType = "issues"
HOOK_EVENT_PULL_REQUEST HookEventType = "pull_request" HookEventTypePullRequest HookEventType = "pull_request"
HOOK_EVENT_ISSUE_COMMENT HookEventType = "issue_comment" HookEventTypeIssueComment HookEventType = "issue_comment"
HOOK_EVENT_RELEASE HookEventType = "release" HookEventTypeRelease HookEventType = "release"
) )
// HookRequest represents hook task request information. // HookRequest represents hook task request information.
@ -511,7 +511,7 @@ func HookTasks(hookID int64, page int) ([]*HookTask, error) {
// createHookTask creates a new hook task, // createHookTask creates a new hook task,
// it handles conversion from Payload to PayloadContent. // it handles conversion from Payload to PayloadContent.
func createHookTask(e Engine, t *HookTask) error { func createHookTask(e Engine, t *HookTask) error {
data, err := t.Payloader.JSONPayload() data, err := t.JSONPayload()
if err != nil { if err != nil {
return err return err
} }
@ -570,35 +570,35 @@ func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Pay
var payloader api.Payloader var payloader api.Payloader
for _, w := range webhooks { for _, w := range webhooks {
switch event { switch event {
case HOOK_EVENT_CREATE: case HookEventTypeCreate:
if !w.HasCreateEvent() { if !w.HasCreateEvent() {
continue continue
} }
case HOOK_EVENT_DELETE: case HookEventTypeDelete:
if !w.HasDeleteEvent() { if !w.HasDeleteEvent() {
continue continue
} }
case HOOK_EVENT_FORK: case HookEventTypeFork:
if !w.HasForkEvent() { if !w.HasForkEvent() {
continue continue
} }
case HOOK_EVENT_PUSH: case HookEventTypePush:
if !w.HasPushEvent() { if !w.HasPushEvent() {
continue continue
} }
case HOOK_EVENT_ISSUES: case HookEventTypeIssues:
if !w.HasIssuesEvent() { if !w.HasIssuesEvent() {
continue continue
} }
case HOOK_EVENT_PULL_REQUEST: case HookEventTypePullRequest:
if !w.HasPullRequestEvent() { if !w.HasPullRequestEvent() {
continue continue
} }
case HOOK_EVENT_ISSUE_COMMENT: case HookEventTypeIssueComment:
if !w.HasIssueCommentEvent() { if !w.HasIssueCommentEvent() {
continue continue
} }
case HOOK_EVENT_RELEASE: case HookEventTypeRelease:
if !w.HasReleaseEvent() { if !w.HasReleaseEvent() {
continue continue
} }
@ -751,9 +751,9 @@ func (t *HookTask) deliver() {
return return
} }
if t.IsSucceed { if t.IsSucceed {
w.LastStatus = HOOK_STATUS_SUCCEED w.LastStatus = HookStatusSucceed
} else { } else {
w.LastStatus = HOOK_STATUS_FAILED w.LastStatus = HookStatusFailed
} }
if err = UpdateWebhook(w); err != nil { if err = UpdateWebhook(w); err != nil {
log.Error("UpdateWebhook: %v", err) log.Error("UpdateWebhook: %v", err)

View File

@ -61,21 +61,21 @@ func NewDingtalkActionCard(singleTitle, singleURL string) DingtalkActionCard {
// TODO: add content // TODO: add content
func GetDingtalkPayload(p api.Payloader, event HookEventType) (payload *DingtalkPayload, err error) { func GetDingtalkPayload(p api.Payloader, event HookEventType) (payload *DingtalkPayload, err error) {
switch event { switch event {
case HOOK_EVENT_CREATE: case HookEventTypeCreate:
payload = getDingtalkCreatePayload(p.(*api.CreatePayload)) payload = getDingtalkCreatePayload(p.(*api.CreatePayload))
case HOOK_EVENT_DELETE: case HookEventTypeDelete:
payload = getDingtalkDeletePayload(p.(*api.DeletePayload)) payload = getDingtalkDeletePayload(p.(*api.DeletePayload))
case HOOK_EVENT_FORK: case HookEventTypeFork:
payload = getDingtalkForkPayload(p.(*api.ForkPayload)) payload = getDingtalkForkPayload(p.(*api.ForkPayload))
case HOOK_EVENT_PUSH: case HookEventTypePush:
payload = getDingtalkPushPayload(p.(*api.PushPayload)) payload = getDingtalkPushPayload(p.(*api.PushPayload))
case HOOK_EVENT_ISSUES: case HookEventTypeIssues:
payload = getDingtalkIssuesPayload(p.(*api.IssuesPayload)) payload = getDingtalkIssuesPayload(p.(*api.IssuesPayload))
case HOOK_EVENT_ISSUE_COMMENT: case HookEventTypeIssueComment:
payload = getDingtalkIssueCommentPayload(p.(*api.IssueCommentPayload)) payload = getDingtalkIssueCommentPayload(p.(*api.IssueCommentPayload))
case HOOK_EVENT_PULL_REQUEST: case HookEventTypePullRequest:
payload = getDingtalkPullRequestPayload(p.(*api.PullRequestPayload)) payload = getDingtalkPullRequestPayload(p.(*api.PullRequestPayload))
case HOOK_EVENT_RELEASE: case HookEventTypeRelease:
payload = getDingtalkReleasePayload(p.(*api.ReleasePayload)) payload = getDingtalkReleasePayload(p.(*api.ReleasePayload))
default: default:
return nil, errors.Errorf("unexpected event %q", event) return nil, errors.Errorf("unexpected event %q", event)
@ -162,11 +162,12 @@ func getDingtalkIssuesPayload(p *api.IssuesPayload) *DingtalkPayload {
actionCard.Text += "# Issue Event " + strings.Title(string(p.Action)) actionCard.Text += "# Issue Event " + strings.Title(string(p.Action))
actionCard.Text += "\n- Issue: **" + MarkdownLinkFormatter(issueURL, issueName) + "**" actionCard.Text += "\n- Issue: **" + MarkdownLinkFormatter(issueURL, issueName) + "**"
if p.Action == api.HOOK_ISSUE_ASSIGNED { switch p.Action {
case api.HOOK_ISSUE_ASSIGNED:
actionCard.Text += "\n- New Assignee: **" + p.Issue.Assignee.UserName + "**" actionCard.Text += "\n- New Assignee: **" + p.Issue.Assignee.UserName + "**"
} else if p.Action == api.HOOK_ISSUE_MILESTONED { case api.HOOK_ISSUE_MILESTONED:
actionCard.Text += "\n- New Milestone: **" + p.Issue.Milestone.Title + "**" actionCard.Text += "\n- New Milestone: **" + p.Issue.Milestone.Title + "**"
} else if p.Action == api.HOOK_ISSUE_LABEL_UPDATED { case api.HOOK_ISSUE_LABEL_UPDATED:
if len(p.Issue.Labels) > 0 { if len(p.Issue.Labels) > 0 {
labels := make([]string, len(p.Issue.Labels)) labels := make([]string, len(p.Issue.Labels))
for i, label := range p.Issue.Labels { for i, label := range p.Issue.Labels {
@ -218,11 +219,12 @@ func getDingtalkPullRequestPayload(p *api.PullRequestPayload) *DingtalkPayload {
pullRequestURL := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index) pullRequestURL := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index)
content := "- PR: " + MarkdownLinkFormatter(pullRequestURL, fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title)) content := "- PR: " + MarkdownLinkFormatter(pullRequestURL, fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
if p.Action == api.HOOK_ISSUE_ASSIGNED { switch p.Action {
case api.HOOK_ISSUE_ASSIGNED:
content += "\n- New Assignee: **" + p.PullRequest.Assignee.UserName + "**" content += "\n- New Assignee: **" + p.PullRequest.Assignee.UserName + "**"
} else if p.Action == api.HOOK_ISSUE_MILESTONED { case api.HOOK_ISSUE_MILESTONED:
content += "\n- New Milestone: *" + p.PullRequest.Milestone.Title + "*" content += "\n- New Milestone: *" + p.PullRequest.Milestone.Title + "*"
} else if p.Action == api.HOOK_ISSUE_LABEL_UPDATED { case api.HOOK_ISSUE_LABEL_UPDATED:
labels := make([]string, len(p.PullRequest.Labels)) labels := make([]string, len(p.PullRequest.Labels))
for i, label := range p.PullRequest.Labels { for i, label := range p.PullRequest.Labels {
labels[i] = "**" + label.Name + "**" labels[i] = "**" + label.Name + "**"

View File

@ -378,21 +378,21 @@ func GetDiscordPayload(p api.Payloader, event HookEventType, meta string) (paylo
} }
switch event { switch event {
case HOOK_EVENT_CREATE: case HookEventTypeCreate:
payload = getDiscordCreatePayload(p.(*api.CreatePayload)) payload = getDiscordCreatePayload(p.(*api.CreatePayload))
case HOOK_EVENT_DELETE: case HookEventTypeDelete:
payload = getDiscordDeletePayload(p.(*api.DeletePayload)) payload = getDiscordDeletePayload(p.(*api.DeletePayload))
case HOOK_EVENT_FORK: case HookEventTypeFork:
payload = getDiscordForkPayload(p.(*api.ForkPayload)) payload = getDiscordForkPayload(p.(*api.ForkPayload))
case HOOK_EVENT_PUSH: case HookEventTypePush:
payload = getDiscordPushPayload(p.(*api.PushPayload), slack) payload = getDiscordPushPayload(p.(*api.PushPayload), slack)
case HOOK_EVENT_ISSUES: case HookEventTypeIssues:
payload = getDiscordIssuesPayload(p.(*api.IssuesPayload), slack) payload = getDiscordIssuesPayload(p.(*api.IssuesPayload), slack)
case HOOK_EVENT_ISSUE_COMMENT: case HookEventTypeIssueComment:
payload = getDiscordIssueCommentPayload(p.(*api.IssueCommentPayload), slack) payload = getDiscordIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
case HOOK_EVENT_PULL_REQUEST: case HookEventTypePullRequest:
payload = getDiscordPullRequestPayload(p.(*api.PullRequestPayload), slack) payload = getDiscordPullRequestPayload(p.(*api.PullRequestPayload), slack)
case HOOK_EVENT_RELEASE: case HookEventTypeRelease:
payload = getDiscordReleasePayload(p.(*api.ReleasePayload)) payload = getDiscordReleasePayload(p.(*api.ReleasePayload))
default: default:
return nil, errors.Errorf("unexpected event %q", event) return nil, errors.Errorf("unexpected event %q", event)

View File

@ -291,25 +291,25 @@ func getSlackReleasePayload(p *api.ReleasePayload) *SlackPayload {
func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (payload *SlackPayload, err error) { func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (payload *SlackPayload, err error) {
slack := &SlackMeta{} slack := &SlackMeta{}
if err := jsoniter.Unmarshal([]byte(meta), &slack); err != nil { if err := jsoniter.Unmarshal([]byte(meta), &slack); err != nil {
return nil, fmt.Errorf("Unmarshal: %v", err) return nil, fmt.Errorf("unmarshal: %v", err)
} }
switch event { switch event {
case HOOK_EVENT_CREATE: case HookEventTypeCreate:
payload = getSlackCreatePayload(p.(*api.CreatePayload)) payload = getSlackCreatePayload(p.(*api.CreatePayload))
case HOOK_EVENT_DELETE: case HookEventTypeDelete:
payload = getSlackDeletePayload(p.(*api.DeletePayload)) payload = getSlackDeletePayload(p.(*api.DeletePayload))
case HOOK_EVENT_FORK: case HookEventTypeFork:
payload = getSlackForkPayload(p.(*api.ForkPayload)) payload = getSlackForkPayload(p.(*api.ForkPayload))
case HOOK_EVENT_PUSH: case HookEventTypePush:
payload = getSlackPushPayload(p.(*api.PushPayload), slack) payload = getSlackPushPayload(p.(*api.PushPayload), slack)
case HOOK_EVENT_ISSUES: case HookEventTypeIssues:
payload = getSlackIssuesPayload(p.(*api.IssuesPayload), slack) payload = getSlackIssuesPayload(p.(*api.IssuesPayload), slack)
case HOOK_EVENT_ISSUE_COMMENT: case HookEventTypeIssueComment:
payload = getSlackIssueCommentPayload(p.(*api.IssueCommentPayload), slack) payload = getSlackIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
case HOOK_EVENT_PULL_REQUEST: case HookEventTypePullRequest:
payload = getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack) payload = getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
case HOOK_EVENT_RELEASE: case HookEventTypeRelease:
payload = getSlackReleasePayload(p.(*api.ReleasePayload)) payload = getSlackReleasePayload(p.(*api.ReleasePayload))
default: default:
return nil, errors.Errorf("unexpected event %q", event) return nil, errors.Errorf("unexpected event %q", event)

View File

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

View File

@ -21,15 +21,15 @@ import (
) )
const ( const (
MAIL_AUTH_ACTIVATE = "auth/activate" tmplAuthActivate = "auth/activate"
MAIL_AUTH_ACTIVATE_EMAIL = "auth/activate_email" tmplAuthActivateEmail = "auth/activate_email"
MAIL_AUTH_RESET_PASSWORD = "auth/reset_passwd" tmplAuthResetPassword = "auth/reset_passwd"
MAIL_AUTH_REGISTER_NOTIFY = "auth/register_notify" tmplAuthRegisterNotify = "auth/register_notify"
MAIL_ISSUE_COMMENT = "issue/comment" tmplIssueComment = "issue/comment"
MAIL_ISSUE_MENTION = "issue/mention" tmplIssueMention = "issue/mention"
MAIL_NOTIFY_COLLABORATOR = "notify/collaborator" tmplNotifyCollaborator = "notify/collaborator"
) )
var ( var (
@ -122,11 +122,11 @@ func SendUserMail(_ *macaron.Context, u User, tpl, code, subject, info string) {
} }
func SendActivateAccountMail(c *macaron.Context, u User) { 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) { 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. // SendActivateAccountMail sends confirmation email.
@ -137,7 +137,7 @@ func SendActivateEmailMail(c *macaron.Context, u User, email string) {
"Code": u.GenerateEmailActivateCode(email), "Code": u.GenerateEmailActivateCode(email),
"Email": email, "Email": email,
} }
body, err := render(MAIL_AUTH_ACTIVATE_EMAIL, data) body, err := render(tmplAuthActivateEmail, data)
if err != nil { if err != nil {
log.Error("HTMLString: %v", err) log.Error("HTMLString: %v", err)
return return
@ -154,7 +154,7 @@ func SendRegisterNotifyMail(c *macaron.Context, u User) {
data := map[string]any{ data := map[string]any{
"Username": u.DisplayName(), "Username": u.DisplayName(),
} }
body, err := render(MAIL_AUTH_REGISTER_NOTIFY, data) body, err := render(tmplAuthRegisterNotify, data)
if err != nil { if err != nil {
log.Error("HTMLString: %v", err) log.Error("HTMLString: %v", err)
return return
@ -175,7 +175,7 @@ func SendCollaboratorMail(u, doer User, repo Repository) {
"RepoName": repo.FullName(), "RepoName": repo.FullName(),
"Link": repo.HTMLURL(), "Link": repo.HTMLURL(),
} }
body, err := render(MAIL_NOTIFY_COLLABORATOR, data) body, err := render(tmplNotifyCollaborator, data)
if err != nil { if err != nil {
log.Error("HTMLString: %v", err) log.Error("HTMLString: %v", err)
return return
@ -216,7 +216,7 @@ func SendIssueCommentMail(issue Issue, repo Repository, doer User, tos []string)
return 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. // 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 { if len(tos) == 0 {
return 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 { 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 auth != nil {
if err = client.Auth(auth); err != 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 { if err = client.Mail(from); err != nil {
return fmt.Errorf("Mail: %v", err) return fmt.Errorf("mail: %v", err)
} }
for _, rec := range to { for _, rec := range to {
if err = client.Rcpt(rec); err != nil { if err = client.Rcpt(rec); err != nil {
return fmt.Errorf("Rcpt: %v", err) return fmt.Errorf("rcpt: %v", err)
} }
} }
w, err := client.Data() w, err := client.Data()
if err != nil { if err != nil {
return fmt.Errorf("Data: %v", err) return fmt.Errorf("data: %v", err)
} else if _, err = msg.WriteTo(w); err != nil { } 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 { } else if err = w.Close(); err != nil {
return fmt.Errorf("Close: %v", err) return fmt.Errorf("close: %v", err)
} }
return client.Quit() return client.Quit()

View File

@ -16,7 +16,7 @@ import (
"gogs.io/gogs/internal/lazyregexp" "gogs.io/gogs/internal/lazyregexp"
) )
const ERR_ALPHA_DASH_DOT_SLASH = "AlphaDashDotSlashError" const ErrAlphaDashDotSlash = "AlphaDashDotSlashError"
var AlphaDashDotSlashPattern = lazyregexp.New("[^\\d\\w-_\\./]") var AlphaDashDotSlashPattern = lazyregexp.New("[^\\d\\w-_\\./]")
@ -28,7 +28,7 @@ func init() {
}, },
IsValid: func(errs binding.Errors, name string, v any) (bool, binding.Errors) { IsValid: func(errs binding.Errors, name string, v any) (bool, binding.Errors) {
if AlphaDashDotSlashPattern.MatchString(fmt.Sprintf("%v", v)) { if AlphaDashDotSlashPattern.MatchString(fmt.Sprintf("%v", v)) {
errs.Add([]string{name}, ERR_ALPHA_DASH_DOT_SLASH, "AlphaDashDotSlash") errs.Add([]string{name}, ErrAlphaDashDotSlash, "AlphaDashDotSlash")
return false, errs return false, errs
} }
return true, errs return true, errs
@ -129,7 +129,7 @@ func validate(errs binding.Errors, data map[string]any, f Form, l macaron.Locale
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error") data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
case binding.ERR_ALPHA_DASH_DOT: case binding.ERR_ALPHA_DASH_DOT:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error") data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
case ERR_ALPHA_DASH_DOT_SLASH: case ErrAlphaDashDotSlash:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_slash_error") data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_slash_error")
case binding.ERR_SIZE: case binding.ERR_SIZE:
data["ErrorMsg"] = trName + l.Tr("form.size_error", getSize(field)) data["ErrorMsg"] = trName + l.Tr("form.size_error", getSize(field))

View File

@ -44,7 +44,7 @@ type MigrateRepo struct {
CloneAddr string `json:"clone_addr" binding:"Required"` CloneAddr string `json:"clone_addr" binding:"Required"`
AuthUsername string `json:"auth_username"` AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"` 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)"` RepoName string `json:"repo_name" binding:"Required;AlphaDashDot;MaxSize(100)"`
Mirror bool `json:"mirror"` Mirror bool `json:"mirror"`
Private bool `json:"private"` Private bool `json:"private"`

View File

@ -11,6 +11,7 @@ import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
//nolint:staticcheck // Reason: needed for legacy code
type Install struct { type Install struct {
DbType string `binding:"Required"` DbType string `binding:"Required"`
DbHost string DbHost string

View File

@ -9,7 +9,6 @@ import (
"bytes" "bytes"
"context" "context"
"crypto/tls" "crypto/tls"
"encoding/xml"
"io" "io"
"log" "log"
"mime/multipart" "mime/multipart"
@ -22,8 +21,6 @@ import (
"strings" "strings"
"sync" "sync"
"time" "time"
jsoniter "github.com/json-iterator/go"
) )
var ( var (
@ -95,13 +92,13 @@ type Settings struct {
UserAgent string UserAgent string
ConnectTimeout time.Duration ConnectTimeout time.Duration
ReadWriteTimeout time.Duration ReadWriteTimeout time.Duration
TlsClientConfig *tls.Config TLSClientConfig *tls.Config
Proxy func(*http.Request) (*url.URL, error) Proxy func(*http.Request) (*url.URL, error)
Transport http.RoundTripper Transport http.RoundTripper
EnableCookie bool 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 { type Request struct {
url string url string
req *http.Request req *http.Request
@ -112,7 +109,7 @@ type Request struct {
body []byte body []byte
} }
// Change request settings // Setting changes the request settings
func (r *Request) Setting(setting Settings) *Request { func (r *Request) Setting(setting Settings) *Request {
r.setting = setting r.setting = setting
return r return r
@ -151,7 +148,7 @@ func (r *Request) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *Re
// SetTLSClientConfig sets tls connection configurations if visiting https url. // SetTLSClientConfig sets tls connection configurations if visiting https url.
func (r *Request) SetTLSClientConfig(config *tls.Config) *Request { func (r *Request) SetTLSClientConfig(config *tls.Config) *Request {
r.setting.TlsClientConfig = config r.setting.TLSClientConfig = config
return r return r
} }
@ -304,7 +301,7 @@ func (r *Request) getResponse() (*http.Response, error) {
if trans == nil { if trans == nil {
// create default transport // create default transport
trans = &http.Transport{ trans = &http.Transport{
TLSClientConfig: r.setting.TlsClientConfig, TLSClientConfig: r.setting.TLSClientConfig,
Proxy: r.setting.Proxy, Proxy: r.setting.Proxy,
DialContext: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout), 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 r.transport is *http.Transport then set the settings.
if t, ok := trans.(*http.Transport); ok { if t, ok := trans.(*http.Transport); ok {
if t.TLSClientConfig == nil { if t.TLSClientConfig == nil {
t.TLSClientConfig = r.setting.TlsClientConfig t.TLSClientConfig = r.setting.TLSClientConfig
} }
if t.Proxy == nil { if t.Proxy == nil {
t.Proxy = r.setting.Proxy t.Proxy = r.setting.Proxy
@ -412,26 +409,6 @@ func (r *Request) ToFile(filename string) error {
return err 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. // Response executes request client gets response manually.
func (r *Request) Response() (*http.Response, error) { func (r *Request) Response() (*http.Response, error) {
return r.getResponse() return r.getResponse()

View File

@ -72,7 +72,7 @@ func (r *MarkdownRenderer) AutoLink(out *bytes.Buffer, link []byte, kind int) {
if j == -1 { if j == -1 {
j = len(m) j = len(m)
} }
out.WriteString(fmt.Sprintf(` <code><a href="%s">%s</a></code>`, m, tool.ShortSHA1(string(m[i+7:j])))) _, _ = fmt.Fprintf(out, ` <code><a href="%s">%s</a></code>`, m, tool.ShortSHA1(string(m[i+7:j])))
return return
} }

View File

@ -17,7 +17,7 @@ import (
var ErrExecTimeout = errors.New("process execution timeout") 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. // Process represents a running process calls shell command.
type Process struct { 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. // 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) { func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) (string, string, error) {
if timeout == -1 { if timeout == -1 {
timeout = DEFAULT_TIMEOUT timeout = defaultTimeout
} }
bufOut := new(bytes.Buffer) bufOut := new(bytes.Buffer)

View File

@ -24,9 +24,9 @@ import (
) )
const ( const (
AUTHS = "admin/auth/list" tmplAdminAuthList = "admin/auth/list"
AUTH_NEW = "admin/auth/new" tmplAdminAuthNew = "admin/auth/new"
AUTH_EDIT = "admin/auth/edit" tmplAdminAuthEdit = "admin/auth/edit"
) )
func Authentications(c *context.Context) { func Authentications(c *context.Context) {
@ -42,7 +42,7 @@ func Authentications(c *context.Context) {
} }
c.Data["Total"] = database.Handle.LoginSources().Count(c.Req.Context()) c.Data["Total"] = database.Handle.LoginSources().Count(c.Req.Context())
c.Success(AUTHS) c.Success(tmplAdminAuthList)
} }
type dropdownItem struct { type dropdownItem struct {
@ -79,7 +79,7 @@ func NewAuthSource(c *context.Context) {
c.Data["AuthSources"] = authSources c.Data["AuthSources"] = authSources
c.Data["SecurityProtocols"] = securityProtocols c.Data["SecurityProtocols"] = securityProtocols
c.Data["SMTPAuths"] = smtp.AuthTypes c.Data["SMTPAuths"] = smtp.AuthTypes
c.Success(AUTH_NEW) c.Success(tmplAdminAuthNew)
} }
func parseLDAPConfig(f form.Authentication) *ldap.Config { func parseLDAPConfig(f form.Authentication) *ldap.Config {
@ -155,7 +155,7 @@ func NewAuthSourcePost(c *context.Context, f form.Authentication) {
c.Data["HasTLS"] = hasTLS c.Data["HasTLS"] = hasTLS
if c.HasError() { if c.HasError() {
c.Success(AUTH_NEW) c.Success(tmplAdminAuthNew)
return return
} }
@ -171,7 +171,7 @@ func NewAuthSourcePost(c *context.Context, f form.Authentication) {
if err != nil { if err != nil {
if database.IsErrLoginSourceAlreadyExist(err) { if database.IsErrLoginSourceAlreadyExist(err) {
c.FormErr("Name") c.FormErr("Name")
c.RenderWithErr(c.Tr("admin.auths.login_source_exist", f.Name), AUTH_NEW, f) c.RenderWithErr(c.Tr("admin.auths.login_source_exist", f.Name), tmplAdminAuthNew, f)
} else { } else {
c.Error(err, "create login source") c.Error(err, "create login source")
} }
@ -208,7 +208,7 @@ func EditAuthSource(c *context.Context) {
c.Data["Source"] = source c.Data["Source"] = source
c.Data["HasTLS"] = source.Provider.HasTLS() c.Data["HasTLS"] = source.Provider.HasTLS()
c.Success(AUTH_EDIT) c.Success(tmplAdminAuthEdit)
} }
func EditAuthSourcePost(c *context.Context, f form.Authentication) { func EditAuthSourcePost(c *context.Context, f form.Authentication) {
@ -227,7 +227,7 @@ func EditAuthSourcePost(c *context.Context, f form.Authentication) {
c.Data["HasTLS"] = source.Provider.HasTLS() c.Data["HasTLS"] = source.Provider.HasTLS()
if c.HasError() { if c.HasError() {
c.Success(AUTH_EDIT) c.Success(tmplAdminAuthEdit)
return return
} }

View File

@ -19,9 +19,9 @@ import (
) )
const ( const (
USERS = "admin/user/list" tmplAdminUserList = "admin/user/list"
USER_NEW = "admin/user/new" tmplAdminUserNew = "admin/user/new"
USER_EDIT = "admin/user/edit" tmplAdminUserEdit = "admin/user/edit"
) )
func Users(c *context.Context) { func Users(c *context.Context) {
@ -35,7 +35,7 @@ func Users(c *context.Context) {
Ranger: database.Handle.Users().List, Ranger: database.Handle.Users().List,
PageSize: conf.UI.Admin.UserPagingNum, PageSize: conf.UI.Admin.UserPagingNum,
OrderBy: "id ASC", OrderBy: "id ASC",
TplName: USERS, TplName: tmplAdminUserList,
}) })
} }
@ -54,7 +54,7 @@ func NewUser(c *context.Context) {
c.Data["Sources"] = sources c.Data["Sources"] = sources
c.Data["CanSendEmail"] = conf.Email.Enabled c.Data["CanSendEmail"] = conf.Email.Enabled
c.Success(USER_NEW) c.Success(tmplAdminUserNew)
} }
func NewUserPost(c *context.Context, f form.AdminCrateUser) { func NewUserPost(c *context.Context, f form.AdminCrateUser) {
@ -72,7 +72,7 @@ func NewUserPost(c *context.Context, f form.AdminCrateUser) {
c.Data["CanSendEmail"] = conf.Email.Enabled c.Data["CanSendEmail"] = conf.Email.Enabled
if c.HasError() { if c.HasError() {
c.Success(USER_NEW) c.Success(tmplAdminUserNew)
return return
} }
@ -93,13 +93,13 @@ func NewUserPost(c *context.Context, f form.AdminCrateUser) {
switch { switch {
case database.IsErrUserAlreadyExist(err): case database.IsErrUserAlreadyExist(err):
c.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
c.RenderWithErr(c.Tr("form.username_been_taken"), USER_NEW, &f) c.RenderWithErr(c.Tr("form.username_been_taken"), tmplAdminUserNew, &f)
case database.IsErrEmailAlreadyUsed(err): case database.IsErrEmailAlreadyUsed(err):
c.Data["Err_Email"] = true c.Data["Err_Email"] = true
c.RenderWithErr(c.Tr("form.email_been_used"), USER_NEW, &f) c.RenderWithErr(c.Tr("form.email_been_used"), tmplAdminUserNew, &f)
case database.IsErrNameNotAllowed(err): case database.IsErrNameNotAllowed(err):
c.Data["Err_UserName"] = true c.Data["Err_UserName"] = true
c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), USER_NEW, &f) c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplAdminUserNew, &f)
default: default:
c.Error(err, "create user") c.Error(err, "create user")
} }
@ -155,7 +155,7 @@ func EditUser(c *context.Context) {
return return
} }
c.Success(USER_EDIT) c.Success(tmplAdminUserEdit)
} }
func EditUserPost(c *context.Context, f form.AdminEditUser) { func EditUserPost(c *context.Context, f form.AdminEditUser) {
@ -170,7 +170,7 @@ func EditUserPost(c *context.Context, f form.AdminEditUser) {
} }
if c.HasError() { if c.HasError() {
c.Success(USER_EDIT) c.Success(tmplAdminUserEdit)
return return
} }
@ -207,7 +207,7 @@ func EditUserPost(c *context.Context, f form.AdminEditUser) {
if err != nil { if err != nil {
if database.IsErrEmailAlreadyUsed(err) { if database.IsErrEmailAlreadyUsed(err) {
c.Data["Err_Email"] = true c.Data["Err_Email"] = true
c.RenderWithErr(c.Tr("form.email_been_used"), USER_EDIT, &f) c.RenderWithErr(c.Tr("form.email_been_used"), tmplAdminUserEdit, &f)
} else { } else {
c.Error(err, "update user") c.Error(err, "update user")
} }

View File

@ -104,9 +104,10 @@ func GetReferenceSHA(c *context.APIContext) {
} }
var sha string var sha string
if refType == 1 { switch refType {
case 1:
sha, err = gitRepo.BranchCommitID(ref) sha, err = gitRepo.BranchCommitID(ref)
} else if refType == 2 { case 2:
sha, err = gitRepo.TagCommitID(ref) sha, err = gitRepo.TagCommitID(ref)
} }
if err != nil { if err != nil {

View File

@ -61,14 +61,14 @@ func CreateHook(c *context.APIContext, form api.CreateHookOption) {
HookEvent: &database.HookEvent{ HookEvent: &database.HookEvent{
ChooseEvents: true, ChooseEvents: true,
HookEvents: database.HookEvents{ HookEvents: database.HookEvents{
Create: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_CREATE)), Create: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeCreate)),
Delete: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_DELETE)), Delete: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeDelete)),
Fork: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_FORK)), Fork: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeFork)),
Push: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_PUSH)), Push: com.IsSliceContainsStr(form.Events, string(database.HookEventTypePush)),
Issues: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_ISSUES)), Issues: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssues)),
IssueComment: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_ISSUE_COMMENT)), IssueComment: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssueComment)),
PullRequest: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_PULL_REQUEST)), PullRequest: com.IsSliceContainsStr(form.Events, string(database.HookEventTypePullRequest)),
Release: com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_RELEASE)), Release: com.IsSliceContainsStr(form.Events, string(database.HookEventTypeRelease)),
}, },
}, },
IsActive: form.Active, IsActive: form.Active,
@ -148,14 +148,14 @@ func EditHook(c *context.APIContext, form api.EditHookOption) {
w.PushOnly = false w.PushOnly = false
w.SendEverything = false w.SendEverything = false
w.ChooseEvents = true w.ChooseEvents = true
w.Create = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_CREATE)) w.Create = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeCreate))
w.Delete = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_DELETE)) w.Delete = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeDelete))
w.Fork = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_FORK)) w.Fork = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeFork))
w.Push = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_PUSH)) w.Push = com.IsSliceContainsStr(form.Events, string(database.HookEventTypePush))
w.Issues = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_ISSUES)) w.Issues = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssues))
w.IssueComment = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_ISSUE_COMMENT)) w.IssueComment = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeIssueComment))
w.PullRequest = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_PULL_REQUEST)) w.PullRequest = com.IsSliceContainsStr(form.Events, string(database.HookEventTypePullRequest))
w.Release = com.IsSliceContainsStr(form.Events, string(database.HOOK_EVENT_RELEASE)) w.Release = com.IsSliceContainsStr(form.Events, string(database.HookEventTypeRelease))
if err = w.UpdateEvent(); err != nil { if err = w.UpdateEvent(); err != nil {
c.Errorf(err, "update event") c.Errorf(err, "update event")
return return

View File

@ -94,7 +94,7 @@ func EditIssueComment(c *context.APIContext, form api.EditIssueCommentOption) {
if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() { if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() {
c.Status(http.StatusForbidden) c.Status(http.StatusForbidden)
return return
} else if comment.Type != database.COMMENT_TYPE_COMMENT { } else if comment.Type != database.CommentTypeComment {
c.NoContent() c.NoContent()
return return
} }
@ -118,7 +118,7 @@ func DeleteIssueComment(c *context.APIContext) {
if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() { if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() {
c.Status(http.StatusForbidden) c.Status(http.StatusForbidden)
return return
} else if comment.Type != database.COMMENT_TYPE_COMMENT { } else if comment.Type != database.CommentTypeComment {
c.NoContent() c.NoContent()
return return
} }

View File

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

View File

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

View File

@ -20,17 +20,17 @@ import (
) )
const ( const (
HOME = "home" tmplHome = "home"
EXPLORE_REPOS = "explore/repos" tmplExploreRepos = "explore/repos"
EXPLORE_USERS = "explore/users" tmplExploreUsers = "explore/users"
EXPLORE_ORGANIZATIONS = "explore/organizations" tmplExploreOrganizations = "explore/organizations"
) )
func Home(c *context.Context) { func Home(c *context.Context) {
if c.IsLogged { if c.IsLogged {
if !c.User.IsActive && conf.Auth.RequireEmailConfirmation { if !c.User.IsActive && conf.Auth.RequireEmailConfirmation {
c.Data["Title"] = c.Tr("auth.active_your_account") c.Data["Title"] = c.Tr("auth.active_your_account")
c.Success(user.ACTIVATE) c.Success(user.TmplUserAuthActivate)
} else { } else {
user.Dashboard(c) user.Dashboard(c)
} }
@ -45,7 +45,7 @@ func Home(c *context.Context) {
} }
c.Data["PageIsHome"] = true c.Data["PageIsHome"] = true
c.Success(HOME) c.Success(tmplHome)
} }
func ExploreRepos(c *context.Context) { func ExploreRepos(c *context.Context) {
@ -80,7 +80,7 @@ func ExploreRepos(c *context.Context) {
} }
c.Data["Repos"] = repos c.Data["Repos"] = repos
c.Success(EXPLORE_REPOS) c.Success(tmplExploreRepos)
} }
type UserSearchOptions struct { type UserSearchOptions struct {
@ -142,7 +142,7 @@ func ExploreUsers(c *context.Context) {
Ranger: database.Handle.Users().List, Ranger: database.Handle.Users().List,
PageSize: conf.UI.ExplorePagingNum, PageSize: conf.UI.ExplorePagingNum,
OrderBy: "updated_unix DESC", OrderBy: "updated_unix DESC",
TplName: EXPLORE_USERS, TplName: tmplExploreUsers,
}) })
} }
@ -161,7 +161,7 @@ func ExploreOrganizations(c *context.Context) {
}, },
PageSize: conf.UI.ExplorePagingNum, PageSize: conf.UI.ExplorePagingNum,
OrderBy: "updated_unix DESC", OrderBy: "updated_unix DESC",
TplName: EXPLORE_ORGANIZATIONS, TplName: tmplExploreOrganizations,
}) })
} }

View File

@ -14,8 +14,8 @@ import (
) )
const ( const (
MEMBERS = "org/member/members" tmplOrgMembers = "org/member/members"
MEMBER_INVITE = "org/member/invite" templOrgMemberInvite = "org/member/invite"
) )
func Members(c *context.Context) { func Members(c *context.Context) {
@ -29,7 +29,7 @@ func Members(c *context.Context) {
} }
c.Data["Members"] = org.Members c.Data["Members"] = org.Members
c.Success(MEMBERS) c.Success(tmplOrgMembers)
} }
func MembersAction(c *context.Context) { func MembersAction(c *context.Context) {
@ -118,5 +118,5 @@ func Invitation(c *context.Context) {
return return
} }
c.Success(MEMBER_INVITE) c.Success(templOrgMemberInvite)
} }

View File

@ -16,14 +16,14 @@ import (
) )
const ( const (
SETTINGS_OPTIONS = "org/settings/options" tmplOrgSettingsOptions = "org/settings/options"
SETTINGS_DELETE = "org/settings/delete" tmplOrgSettingsDelete = "org/settings/delete"
) )
func Settings(c *context.Context) { func Settings(c *context.Context) {
c.Title("org.settings") c.Title("org.settings")
c.Data["PageIsSettingsOptions"] = true c.Data["PageIsSettingsOptions"] = true
c.Success(SETTINGS_OPTIONS) c.Success(tmplOrgSettingsOptions)
} }
func SettingsPost(c *context.Context, f form.UpdateOrgSetting) { func SettingsPost(c *context.Context, f form.UpdateOrgSetting) {
@ -31,7 +31,7 @@ func SettingsPost(c *context.Context, f form.UpdateOrgSetting) {
c.Data["PageIsSettingsOptions"] = true c.Data["PageIsSettingsOptions"] = true
if c.HasError() { if c.HasError() {
c.Success(SETTINGS_OPTIONS) c.Success(tmplOrgSettingsOptions)
return return
} }
@ -53,7 +53,7 @@ func SettingsPost(c *context.Context, f form.UpdateOrgSetting) {
return return
} }
c.RenderWithErr(msg, SETTINGS_OPTIONS, &f) c.RenderWithErr(msg, tmplOrgSettingsOptions, &f)
return return
} }
@ -108,7 +108,7 @@ func SettingsDelete(c *context.Context) {
if c.Req.Method == "POST" { if c.Req.Method == "POST" {
if _, err := database.Handle.Users().Authenticate(c.Req.Context(), c.User.Name, c.Query("password"), c.User.LoginSource); err != nil { if _, err := database.Handle.Users().Authenticate(c.Req.Context(), c.User.Name, c.Query("password"), c.User.LoginSource); err != nil {
if auth.IsErrBadCredentials(err) { if auth.IsErrBadCredentials(err) {
c.RenderWithErr(c.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_password"), tmplOrgSettingsDelete, nil)
} else { } else {
c.Error(err, "authenticate user") c.Error(err, "authenticate user")
} }
@ -129,5 +129,5 @@ func SettingsDelete(c *context.Context) {
return return
} }
c.Success(SETTINGS_DELETE) c.Success(tmplOrgSettingsDelete)
} }

View File

@ -17,10 +17,10 @@ import (
) )
const ( const (
TEAMS = "org/team/teams" tmplOrgTeams = "org/team/teams"
TEAM_NEW = "org/team/new" tmplOrgTeamNew = "org/team/new"
TEAM_MEMBERS = "org/team/members" tmplOrgTeamMembers = "org/team/members"
TEAM_REPOSITORIES = "org/team/repositories" tmplOrgTeamRepositories = "org/team/repositories"
) )
func Teams(c *context.Context) { func Teams(c *context.Context) {
@ -36,7 +36,7 @@ func Teams(c *context.Context) {
} }
c.Data["Teams"] = org.Teams c.Data["Teams"] = org.Teams
c.Success(TEAMS) c.Success(tmplOrgTeams)
} }
func TeamsAction(c *context.Context) { func TeamsAction(c *context.Context) {
@ -146,7 +146,7 @@ func NewTeam(c *context.Context) {
c.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
c.Data["PageIsOrgTeamsNew"] = true c.Data["PageIsOrgTeamsNew"] = true
c.Data["Team"] = &database.Team{} c.Data["Team"] = &database.Team{}
c.Success(TEAM_NEW) c.Success(tmplOrgTeamNew)
} }
func NewTeamPost(c *context.Context, f form.CreateTeam) { func NewTeamPost(c *context.Context, f form.CreateTeam) {
@ -163,7 +163,7 @@ func NewTeamPost(c *context.Context, f form.CreateTeam) {
c.Data["Team"] = t c.Data["Team"] = t
if c.HasError() { if c.HasError() {
c.Success(TEAM_NEW) c.Success(tmplOrgTeamNew)
return return
} }
@ -171,9 +171,9 @@ func NewTeamPost(c *context.Context, f form.CreateTeam) {
c.Data["Err_TeamName"] = true c.Data["Err_TeamName"] = true
switch { switch {
case database.IsErrTeamAlreadyExist(err): case database.IsErrTeamAlreadyExist(err):
c.RenderWithErr(c.Tr("form.team_name_been_taken"), TEAM_NEW, &f) c.RenderWithErr(c.Tr("form.team_name_been_taken"), tmplOrgTeamNew, &f)
case database.IsErrNameNotAllowed(err): case database.IsErrNameNotAllowed(err):
c.RenderWithErr(c.Tr("org.form.team_name_not_allowed", err.(database.ErrNameNotAllowed).Value()), TEAM_NEW, &f) c.RenderWithErr(c.Tr("org.form.team_name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplOrgTeamNew, &f)
default: default:
c.Error(err, "new team") c.Error(err, "new team")
} }
@ -190,7 +190,7 @@ func TeamMembers(c *context.Context) {
c.Error(err, "get members") c.Error(err, "get members")
return return
} }
c.Success(TEAM_MEMBERS) c.Success(tmplOrgTeamMembers)
} }
func TeamRepositories(c *context.Context) { func TeamRepositories(c *context.Context) {
@ -200,7 +200,7 @@ func TeamRepositories(c *context.Context) {
c.Error(err, "get repositories") c.Error(err, "get repositories")
return return
} }
c.Success(TEAM_REPOSITORIES) c.Success(tmplOrgTeamRepositories)
} }
func EditTeam(c *context.Context) { func EditTeam(c *context.Context) {
@ -208,7 +208,7 @@ func EditTeam(c *context.Context) {
c.Data["PageIsOrgTeams"] = true c.Data["PageIsOrgTeams"] = true
c.Data["team_name"] = c.Org.Team.Name c.Data["team_name"] = c.Org.Team.Name
c.Data["desc"] = c.Org.Team.Description c.Data["desc"] = c.Org.Team.Description
c.Success(TEAM_NEW) c.Success(tmplOrgTeamNew)
} }
func EditTeamPost(c *context.Context, f form.CreateTeam) { func EditTeamPost(c *context.Context, f form.CreateTeam) {
@ -218,7 +218,7 @@ func EditTeamPost(c *context.Context, f form.CreateTeam) {
c.Data["Team"] = t c.Data["Team"] = t
if c.HasError() { if c.HasError() {
c.Success(TEAM_NEW) c.Success(tmplOrgTeamNew)
return return
} }
@ -249,7 +249,7 @@ func EditTeamPost(c *context.Context, f form.CreateTeam) {
c.Data["Err_TeamName"] = true c.Data["Err_TeamName"] = true
switch { switch {
case database.IsErrTeamAlreadyExist(err): case database.IsErrTeamAlreadyExist(err):
c.RenderWithErr(c.Tr("form.team_name_been_taken"), TEAM_NEW, &f) c.RenderWithErr(c.Tr("form.team_name_been_taken"), tmplOrgTeamNew, &f)
default: default:
c.Error(err, "update team") c.Error(err, "update team")
} }

View File

@ -18,8 +18,8 @@ import (
) )
const ( const (
BRANCHES_OVERVIEW = "repo/branches/overview" tmplRepoBranchesOverview = "repo/branches/overview"
BRANCHES_ALL = "repo/branches/all" tmplRepoBranchesAll = "repo/branches/all"
) )
type Branch struct { type Branch struct {
@ -91,7 +91,7 @@ func Branches(c *context.Context) {
c.Data["ActiveBranches"] = activeBranches c.Data["ActiveBranches"] = activeBranches
c.Data["StaleBranches"] = staleBranches c.Data["StaleBranches"] = staleBranches
c.Success(BRANCHES_OVERVIEW) c.Success(tmplRepoBranchesOverview)
} }
func AllBranches(c *context.Context) { func AllBranches(c *context.Context) {
@ -104,7 +104,7 @@ func AllBranches(c *context.Context) {
} }
c.Data["Branches"] = branches c.Data["Branches"] = branches
c.Success(BRANCHES_ALL) c.Success(tmplRepoBranchesAll)
} }
func DeleteBranchPost(c *context.Context) { func DeleteBranchPost(c *context.Context) {
@ -142,14 +142,14 @@ func DeleteBranchPost(c *context.Context) {
return return
} }
if err := database.PrepareWebhooks(c.Repo.Repository, database.HOOK_EVENT_DELETE, &api.DeletePayload{ if err := database.PrepareWebhooks(c.Repo.Repository, database.HookEventTypeDelete, &api.DeletePayload{
Ref: branchName, Ref: branchName,
RefType: "branch", RefType: "branch",
PusherType: api.PUSHER_TYPE_USER, PusherType: api.PUSHER_TYPE_USER,
Repo: c.Repo.Repository.APIFormatLegacy(nil), Repo: c.Repo.Repository.APIFormatLegacy(nil),
Sender: c.User.APIFormat(), Sender: c.User.APIFormat(),
}); err != nil { }); err != nil {
log.Error("Failed to prepare webhooks for %q: %v", database.HOOK_EVENT_DELETE, err) log.Error("Failed to prepare webhooks for %q: %v", database.HookEventTypeDelete, err)
return return
} }
} }

View File

@ -25,10 +25,10 @@ const (
func RefCommits(c *context.Context) { func RefCommits(c *context.Context) {
c.Data["PageIsViewFiles"] = true c.Data["PageIsViewFiles"] = true
switch { switch c.Repo.TreePath {
case c.Repo.TreePath == "": case "":
Commits(c) Commits(c)
case c.Repo.TreePath == "search": case "search":
SearchCommits(c) SearchCommits(c)
default: default:
FileHistory(c) FileHistory(c)

View File

@ -82,7 +82,7 @@ func editFile(c *context.Context, isNewFile bool) {
return return
} }
if err, content := template.ToUTF8WithErr(p); err != nil { if content, err := template.ToUTF8WithErr(p); err != nil {
if err != nil { if err != nil {
log.Error("Failed to convert encoding to UTF-8: %v", err) log.Error("Failed to convert encoding to UTF-8: %v", err)
} }
@ -282,7 +282,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) {
}); err != nil { }); err != nil {
log.Error("Failed to update repo file: %v", err) log.Error("Failed to update repo file: %v", err)
c.FormErr("TreePath") 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 return
} }
@ -390,7 +390,7 @@ func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) {
Message: message, Message: message,
}); err != nil { }); err != nil {
log.Error("Failed to delete repo file: %v", err) 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 return
} }
@ -512,7 +512,7 @@ func UploadFilePost(c *context.Context, f form.UploadRepoFile) {
}); err != nil { }); err != nil {
log.Error("Failed to upload files: %v", err) log.Error("Failed to upload files: %v", err)
c.FormErr("TreePath") 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 return
} }

View File

@ -300,7 +300,7 @@ func gitCommand(dir string, args ...string) []byte {
cmd.Dir = dir cmd.Dir = dir
out, err := cmd.Output() out, err := cmd.Output()
if err != nil { if err != nil {
log.Error(fmt.Sprintf("Git: %v - %s", err, out)) log.Error("Git: %v - %s", err, out)
} }
return out return out
} }

View File

@ -25,17 +25,15 @@ import (
) )
const ( const (
ISSUES = "repo/issue/list" tmplRepoIssueList = "repo/issue/list"
ISSUE_NEW = "repo/issue/new" tmplRepoIssueNew = "repo/issue/new"
ISSUE_VIEW = "repo/issue/view" tmplRepoIssueView = "repo/issue/view"
tmplRepoIssueLabels = "repo/issue/labels"
tmplRepoIssueMilestones = "repo/issue/milestones"
tmplRepoIssueMilestoneNew = "repo/issue/milestone_new"
tmplRepoIssueMilestoneEdit = "repo/issue/milestone_edit"
LABELS = "repo/issue/labels" IssueTemplateKey = "IssueTemplate"
MILESTONE = "repo/issue/milestones"
MILESTONE_NEW = "repo/issue/milestone_new"
MILESTONE_EDIT = "repo/issue/milestone_edit"
ISSUE_TEMPLATE_KEY = "IssueTemplate"
) )
var ( var (
@ -123,16 +121,16 @@ func issues(c *context.Context, isPullList bool) {
assigneeID = c.QueryInt64("assignee") assigneeID = c.QueryInt64("assignee")
posterID int64 posterID int64
) )
filterMode := database.FILTER_MODE_YOUR_REPOS filterMode := database.FilterModeYourRepos
switch viewType { switch viewType {
case "assigned": case "assigned":
filterMode = database.FILTER_MODE_ASSIGN filterMode = database.FilterModeAssign
assigneeID = c.User.ID assigneeID = c.User.ID
case "created_by": case "created_by":
filterMode = database.FILTER_MODE_CREATE filterMode = database.FilterModeCreate
posterID = c.User.ID posterID = c.User.ID
case "mentioned": case "mentioned":
filterMode = database.FILTER_MODE_MENTION filterMode = database.FilterModeMention
} }
var uid int64 = -1 var uid int64 = -1
@ -176,7 +174,7 @@ func issues(c *context.Context, isPullList bool) {
MilestoneID: milestoneID, MilestoneID: milestoneID,
Page: pager.Current(), Page: pager.Current(),
IsClosed: isShowClosed, IsClosed: isShowClosed,
IsMention: filterMode == database.FILTER_MODE_MENTION, IsMention: filterMode == database.FilterModeMention,
IsPull: isPullList, IsPull: isPullList,
Labels: selectLabels, Labels: selectLabels,
SortType: sortType, SortType: sortType,
@ -241,7 +239,7 @@ func issues(c *context.Context, isPullList bool) {
c.Data["State"] = "open" c.Data["State"] = "open"
} }
c.Success(ISSUES) c.Success(tmplRepoIssueList)
} }
func Issues(c *context.Context) { func Issues(c *context.Context) {
@ -337,7 +335,7 @@ func NewIssue(c *context.Context) {
c.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
c.Data["title"] = c.Query("title") c.Data["title"] = c.Query("title")
c.Data["content"] = c.Query("content") c.Data["content"] = c.Query("content")
setTemplateIfExists(c, ISSUE_TEMPLATE_KEY, IssueTemplateCandidates) setTemplateIfExists(c, IssueTemplateKey, IssueTemplateCandidates)
renderAttachmentSettings(c) renderAttachmentSettings(c)
RetrieveRepoMetas(c, c.Repo.Repository) RetrieveRepoMetas(c, c.Repo.Repository)
@ -345,7 +343,7 @@ func NewIssue(c *context.Context) {
return return
} }
c.Success(ISSUE_NEW) c.Success(tmplRepoIssueNew)
} }
func ValidateRepoMetas(c *context.Context, f form.NewIssue) ([]int64, int64, int64) { func ValidateRepoMetas(c *context.Context, f form.NewIssue) ([]int64, int64, int64) {
@ -415,7 +413,7 @@ func NewIssuePost(c *context.Context, f form.NewIssue) {
} }
if c.HasError() { if c.HasError() {
c.Success(ISSUE_NEW) c.Success(tmplRepoIssueNew)
return return
} }
@ -599,7 +597,7 @@ func viewIssue(c *context.Context, isPullList bool) {
// Render comments and fetch participants. // Render comments and fetch participants.
participants[0] = issue.Poster participants[0] = issue.Poster
for _, comment = range issue.Comments { for _, comment = range issue.Comments {
if comment.Type == database.COMMENT_TYPE_COMMENT { if comment.Type == database.CommentTypeComment {
comment.RenderedContent = string(markup.Markdown(comment.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) comment.RenderedContent = string(markup.Markdown(comment.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
// Check tag. // Check tag.
@ -611,7 +609,7 @@ func viewIssue(c *context.Context, isPullList bool) {
if repo.IsOwnedBy(comment.PosterID) || if repo.IsOwnedBy(comment.PosterID) ||
(repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) { (repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) {
comment.ShowTag = database.COMMENT_TAG_OWNER comment.ShowTag = database.CommentTagOwner
} else if database.Handle.Permissions().Authorize( } else if database.Handle.Permissions().Authorize(
c.Req.Context(), c.Req.Context(),
comment.PosterID, comment.PosterID,
@ -622,9 +620,9 @@ func viewIssue(c *context.Context, isPullList bool) {
Private: repo.IsPrivate, Private: repo.IsPrivate,
}, },
) { ) {
comment.ShowTag = database.COMMENT_TAG_WRITER comment.ShowTag = database.CommentTagWriter
} else if comment.PosterID == issue.PosterID { } else if comment.PosterID == issue.PosterID {
comment.ShowTag = database.COMMENT_TAG_POSTER comment.ShowTag = database.CommentTagPoster
} }
marked[comment.PosterID] = comment.ShowTag marked[comment.PosterID] = comment.ShowTag
@ -670,7 +668,7 @@ func viewIssue(c *context.Context, isPullList bool) {
c.Data["Issue"] = issue c.Data["Issue"] = issue
c.Data["IsIssueOwner"] = c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID)) c.Data["IsIssueOwner"] = c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID))
c.Data["SignInLink"] = conf.Server.Subpath + "/user/login?redirect_to=" + c.Data["Link"].(string) c.Data["SignInLink"] = conf.Server.Subpath + "/user/login?redirect_to=" + c.Data["Link"].(string)
c.Success(ISSUE_VIEW) c.Success(tmplRepoIssueView)
} }
func ViewIssue(c *context.Context) { func ViewIssue(c *context.Context) {
@ -935,7 +933,7 @@ func UpdateCommentContent(c *context.Context) {
if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() { if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
c.NotFound() c.NotFound()
return return
} else if comment.Type != database.COMMENT_TYPE_COMMENT { } else if comment.Type != database.CommentTypeComment {
c.Status(http.StatusNoContent) c.Status(http.StatusNoContent)
return return
} }
@ -968,7 +966,7 @@ func DeleteComment(c *context.Context) {
if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() { if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
c.NotFound() c.NotFound()
return return
} else if comment.Type != database.COMMENT_TYPE_COMMENT { } else if comment.Type != database.CommentTypeComment {
c.Status(http.StatusNoContent) c.Status(http.StatusNoContent)
return return
} }
@ -987,7 +985,7 @@ func Labels(c *context.Context) {
c.Data["PageIsLabels"] = true c.Data["PageIsLabels"] = true
c.Data["RequireMinicolors"] = true c.Data["RequireMinicolors"] = true
c.Data["LabelTemplates"] = database.LabelTemplates c.Data["LabelTemplates"] = database.LabelTemplates
c.Success(LABELS) c.Success(tmplRepoIssueLabels)
} }
func InitializeLabels(c *context.Context, f form.InitializeLabels) { func InitializeLabels(c *context.Context, f form.InitializeLabels) {
@ -1112,7 +1110,7 @@ func Milestones(c *context.Context) {
} }
c.Data["IsShowClosed"] = isShowClosed c.Data["IsShowClosed"] = isShowClosed
c.Success(MILESTONE) c.Success(tmplRepoIssueMilestones)
} }
func NewMilestone(c *context.Context) { func NewMilestone(c *context.Context) {
@ -1120,8 +1118,8 @@ func NewMilestone(c *context.Context) {
c.Data["PageIsIssueList"] = true c.Data["PageIsIssueList"] = true
c.Data["PageIsMilestones"] = true c.Data["PageIsMilestones"] = true
c.Data["RequireDatetimepicker"] = true c.Data["RequireDatetimepicker"] = true
c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language()) c.Data["DateLang"] = conf.I18n.DateLang(c.Language())
c.Success(MILESTONE_NEW) c.Success(tmplRepoIssueMilestoneNew)
} }
func NewMilestonePost(c *context.Context, f form.CreateMilestone) { func NewMilestonePost(c *context.Context, f form.CreateMilestone) {
@ -1129,10 +1127,10 @@ func NewMilestonePost(c *context.Context, f form.CreateMilestone) {
c.Data["PageIsIssueList"] = true c.Data["PageIsIssueList"] = true
c.Data["PageIsMilestones"] = true c.Data["PageIsMilestones"] = true
c.Data["RequireDatetimepicker"] = true c.Data["RequireDatetimepicker"] = true
c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language()) c.Data["DateLang"] = conf.I18n.DateLang(c.Language())
if c.HasError() { if c.HasError() {
c.Success(MILESTONE_NEW) c.Success(tmplRepoIssueMilestoneNew)
return return
} }
@ -1142,7 +1140,7 @@ func NewMilestonePost(c *context.Context, f form.CreateMilestone) {
deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local) deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
if err != nil { if err != nil {
c.Data["Err_Deadline"] = true c.Data["Err_Deadline"] = true
c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f) c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), tmplRepoIssueMilestoneNew, &f)
return return
} }
@ -1165,7 +1163,7 @@ func EditMilestone(c *context.Context) {
c.Data["PageIsMilestones"] = true c.Data["PageIsMilestones"] = true
c.Data["PageIsEditMilestone"] = true c.Data["PageIsEditMilestone"] = true
c.Data["RequireDatetimepicker"] = true c.Data["RequireDatetimepicker"] = true
c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language()) c.Data["DateLang"] = conf.I18n.DateLang(c.Language())
m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id")) m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
if err != nil { if err != nil {
@ -1177,7 +1175,7 @@ func EditMilestone(c *context.Context) {
if len(m.DeadlineString) > 0 { if len(m.DeadlineString) > 0 {
c.Data["deadline"] = m.DeadlineString c.Data["deadline"] = m.DeadlineString
} }
c.Success(MILESTONE_NEW) c.Success(tmplRepoIssueMilestoneNew)
} }
func EditMilestonePost(c *context.Context, f form.CreateMilestone) { func EditMilestonePost(c *context.Context, f form.CreateMilestone) {
@ -1185,10 +1183,10 @@ func EditMilestonePost(c *context.Context, f form.CreateMilestone) {
c.Data["PageIsMilestones"] = true c.Data["PageIsMilestones"] = true
c.Data["PageIsEditMilestone"] = true c.Data["PageIsEditMilestone"] = true
c.Data["RequireDatetimepicker"] = true c.Data["RequireDatetimepicker"] = true
c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language()) c.Data["DateLang"] = conf.I18n.DateLang(c.Language())
if c.HasError() { if c.HasError() {
c.Success(MILESTONE_NEW) c.Success(tmplRepoIssueMilestoneNew)
return return
} }
@ -1198,7 +1196,7 @@ func EditMilestonePost(c *context.Context, f form.CreateMilestone) {
deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local) deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
if err != nil { if err != nil {
c.Data["Err_Deadline"] = true c.Data["Err_Deadline"] = true
c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f) c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), tmplRepoIssueMilestoneNew, &f)
return return
} }

View File

@ -23,13 +23,13 @@ import (
) )
const ( const (
FORK = "repo/pulls/fork" tmplRepoPullsFork = "repo/pulls/fork"
COMPARE_PULL = "repo/pulls/compare" tmplRepoPullsCompare = "repo/pulls/compare"
PULL_COMMITS = "repo/pulls/commits" tmplRepoPullsCommits = "repo/pulls/commits"
PULL_FILES = "repo/pulls/files" tmplRepoPullsFiles = "repo/pulls/files"
PULL_REQUEST_TEMPLATE_KEY = "PullRequestTemplate" PullRequestTemplateKey = "PullRequestTemplate"
PULL_REQUEST_TITLE_TEMPLATE_KEY = "PullRequestTitleTemplate" PullRequestTitleTemplateKey = "PullRequestTitleTemplate"
) )
var ( var (
@ -94,7 +94,7 @@ func Fork(c *context.Context) {
} }
c.Data["ContextUser"] = c.User c.Data["ContextUser"] = c.User
c.Success(FORK) c.Success(tmplRepoPullsFork)
} }
func ForkPost(c *context.Context, f form.CreateRepo) { func ForkPost(c *context.Context, f form.CreateRepo) {
@ -112,7 +112,7 @@ func ForkPost(c *context.Context, f form.CreateRepo) {
c.Data["ContextUser"] = ctxUser c.Data["ContextUser"] = ctxUser
if c.HasError() { if c.HasError() {
c.Success(FORK) c.Success(tmplRepoPullsFork)
return return
} }
@ -133,7 +133,7 @@ func ForkPost(c *context.Context, f form.CreateRepo) {
// Cannot fork to same owner // Cannot fork to same owner
if ctxUser.ID == baseRepo.OwnerID { if ctxUser.ID == baseRepo.OwnerID {
c.RenderWithErr(c.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f) c.RenderWithErr(c.Tr("repo.settings.cannot_fork_to_same_owner"), tmplRepoPullsFork, &f)
return return
} }
@ -142,11 +142,11 @@ func ForkPost(c *context.Context, f form.CreateRepo) {
c.Data["Err_RepoName"] = true c.Data["Err_RepoName"] = true
switch { switch {
case database.IsErrReachLimitOfRepo(err): case database.IsErrReachLimitOfRepo(err):
c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", err.(database.ErrReachLimitOfRepo).Limit), FORK, &f) c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", err.(database.ErrReachLimitOfRepo).Limit), tmplRepoPullsFork, &f)
case database.IsErrRepoAlreadyExist(err): case database.IsErrRepoAlreadyExist(err):
c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f) c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), tmplRepoPullsFork, &f)
case database.IsErrNameNotAllowed(err): case database.IsErrNameNotAllowed(err):
c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), FORK, &f) c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplRepoPullsFork, &f)
default: default:
c.Error(err, "fork repository") c.Error(err, "fork repository")
} }
@ -301,7 +301,7 @@ func ViewPullCommits(c *context.Context) {
c.Data["Commits"] = matchUsersWithCommitEmails(c.Req.Context(), commits) c.Data["Commits"] = matchUsersWithCommitEmails(c.Req.Context(), commits)
c.Data["CommitsCount"] = len(commits) c.Data["CommitsCount"] = len(commits)
c.Success(PULL_COMMITS) c.Success(tmplRepoPullsCommits)
} }
func ViewPullFiles(c *context.Context) { func ViewPullFiles(c *context.Context) {
@ -399,7 +399,7 @@ func ViewPullFiles(c *context.Context) {
} }
c.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
c.Success(PULL_FILES) c.Success(tmplRepoPullsFiles)
} }
func MergePullRequest(c *context.Context) { func MergePullRequest(c *context.Context) {
@ -550,7 +550,7 @@ func ParseCompareInfo(c *context.Context) (*database.User, *database.Repository,
if err != nil { if err != nil {
if gitutil.IsErrNoMergeBase(err) { if gitutil.IsErrNoMergeBase(err) {
c.Data["IsNoMergeBase"] = true c.Data["IsNoMergeBase"] = true
c.Success(COMPARE_PULL) c.Success(tmplRepoPullsCompare)
} else { } else {
c.Error(err, "get pull request meta") c.Error(err, "get pull request meta")
} }
@ -626,7 +626,7 @@ func CompareAndPullRequest(c *context.Context) {
c.Data["PageIsComparePull"] = true c.Data["PageIsComparePull"] = true
c.Data["IsDiffCompare"] = true c.Data["IsDiffCompare"] = true
c.Data["RequireHighlightJS"] = true c.Data["RequireHighlightJS"] = true
setTemplateIfExists(c, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates) setTemplateIfExists(c, PullRequestTemplateKey, PullRequestTemplateCandidates)
renderAttachmentSettings(c) renderAttachmentSettings(c)
headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c) headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
@ -643,7 +643,7 @@ func CompareAndPullRequest(c *context.Context) {
} else { } else {
c.Data["HasPullRequest"] = true c.Data["HasPullRequest"] = true
c.Data["PullRequest"] = pr c.Data["PullRequest"] = pr
c.Success(COMPARE_PULL) c.Success(tmplRepoPullsCompare)
return return
} }
@ -666,15 +666,15 @@ func CompareAndPullRequest(c *context.Context) {
} }
c.Data["IsSplitStyle"] = c.Query("style") == "split" c.Data["IsSplitStyle"] = c.Query("style") == "split"
setTemplateIfExists(c, PULL_REQUEST_TITLE_TEMPLATE_KEY, PullRequestTitleTemplateCandidates) setTemplateIfExists(c, PullRequestTitleTemplateKey, PullRequestTitleTemplateCandidates)
if c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY] != nil { if c.Data[PullRequestTitleTemplateKey] != nil {
customTitle := c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY].(string) customTitle := c.Data[PullRequestTitleTemplateKey].(string)
r := strings.NewReplacer("{{headBranch}}", headBranch, "{{baseBranch}}", baseBranch) r := strings.NewReplacer("{{headBranch}}", headBranch, "{{baseBranch}}", baseBranch)
c.Data["title"] = r.Replace(customTitle) c.Data["title"] = r.Replace(customTitle)
} }
c.Success(COMPARE_PULL) c.Success(tmplRepoPullsCompare)
} }
func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) { func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
@ -713,7 +713,7 @@ func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
return return
} }
c.Success(COMPARE_PULL) c.Success(tmplRepoPullsCompare)
return return
} }
@ -743,7 +743,7 @@ func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
HeadRepo: headRepo, HeadRepo: headRepo,
BaseRepo: repo, BaseRepo: repo,
MergeBase: meta.MergeBase, MergeBase: meta.MergeBase,
Type: database.PULL_REQUEST_GOGS, Type: database.PullRequestTypeGogs,
} }
// FIXME: check error in the case two people send pull request at almost same time, give nice error prompt // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
// instead of 500. // instead of 500.

View File

@ -20,8 +20,8 @@ import (
) )
const ( const (
RELEASES = "repo/release/list" tmplRepoReleaseList = "repo/release/list"
RELEASE_NEW = "repo/release/new" tmplRepoReleaseNew = "repo/release/new"
) )
// calReleaseNumCommitsBehind calculates given release has how many commits behind release target. // calReleaseNumCommitsBehind calculates given release has how many commits behind release target.
@ -148,7 +148,7 @@ func Releases(c *context.Context) {
if len(results) > 0 { if len(results) > 0 {
c.Data["NextAfter"] = results[len(results)-1].TagName c.Data["NextAfter"] = results[len(results)-1].TagName
} }
c.Success(RELEASES) c.Success(tmplRepoReleaseList)
} }
func renderReleaseAttachmentSettings(c *context.Context) { func renderReleaseAttachmentSettings(c *context.Context) {
@ -164,7 +164,7 @@ func NewRelease(c *context.Context) {
c.Data["PageIsReleaseList"] = true c.Data["PageIsReleaseList"] = true
c.Data["tag_target"] = c.Repo.Repository.DefaultBranch c.Data["tag_target"] = c.Repo.Repository.DefaultBranch
renderReleaseAttachmentSettings(c) renderReleaseAttachmentSettings(c)
c.Success(RELEASE_NEW) c.Success(tmplRepoReleaseNew)
} }
func NewReleasePost(c *context.Context, f form.NewRelease) { func NewReleasePost(c *context.Context, f form.NewRelease) {
@ -173,12 +173,12 @@ func NewReleasePost(c *context.Context, f form.NewRelease) {
renderReleaseAttachmentSettings(c) renderReleaseAttachmentSettings(c)
if c.HasError() { if c.HasError() {
c.Success(RELEASE_NEW) c.Success(tmplRepoReleaseNew)
return return
} }
if !c.Repo.GitRepo.HasBranch(f.Target) { if !c.Repo.GitRepo.HasBranch(f.Target) {
c.RenderWithErr(c.Tr("form.target_branch_not_exist"), RELEASE_NEW, &f) c.RenderWithErr(c.Tr("form.target_branch_not_exist"), tmplRepoReleaseNew, &f)
return return
} }
@ -226,9 +226,9 @@ func NewReleasePost(c *context.Context, f form.NewRelease) {
c.Data["Err_TagName"] = true c.Data["Err_TagName"] = true
switch { switch {
case database.IsErrReleaseAlreadyExist(err): case database.IsErrReleaseAlreadyExist(err):
c.RenderWithErr(c.Tr("repo.release.tag_name_already_exist"), RELEASE_NEW, &f) c.RenderWithErr(c.Tr("repo.release.tag_name_already_exist"), tmplRepoReleaseNew, &f)
case database.IsErrInvalidTagName(err): case database.IsErrInvalidTagName(err):
c.RenderWithErr(c.Tr("repo.release.tag_name_invalid"), RELEASE_NEW, &f) c.RenderWithErr(c.Tr("repo.release.tag_name_invalid"), tmplRepoReleaseNew, &f)
default: default:
c.Error(err, "new release") c.Error(err, "new release")
} }
@ -260,7 +260,7 @@ func EditRelease(c *context.Context) {
c.Data["prerelease"] = rel.IsPrerelease c.Data["prerelease"] = rel.IsPrerelease
c.Data["IsDraft"] = rel.IsDraft c.Data["IsDraft"] = rel.IsDraft
c.Success(RELEASE_NEW) c.Success(tmplRepoReleaseNew)
} }
func EditReleasePost(c *context.Context, f form.EditRelease) { func EditReleasePost(c *context.Context, f form.EditRelease) {
@ -284,7 +284,7 @@ func EditReleasePost(c *context.Context, f form.EditRelease) {
c.Data["IsDraft"] = rel.IsDraft c.Data["IsDraft"] = rel.IsDraft
if c.HasError() { if c.HasError() {
c.Success(RELEASE_NEW) c.Success(tmplRepoReleaseNew)
return return
} }

View File

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

View File

@ -26,21 +26,21 @@ import (
) )
const ( const (
SETTINGS_OPTIONS = "repo/settings/options" tmplRepoSettingsOptions = "repo/settings/options"
SETTINGS_REPO_AVATAR = "repo/settings/avatar" tmplRepoSettingsAvatar = "repo/settings/avatar"
SETTINGS_COLLABORATION = "repo/settings/collaboration" tmplRepoSettingsCollaboration = "repo/settings/collaboration"
SETTINGS_BRANCHES = "repo/settings/branches" tmplRepoSettingsBranches = "repo/settings/branches"
SETTINGS_PROTECTED_BRANCH = "repo/settings/protected_branch" tmplRepoSettingsProtectedBranch = "repo/settings/protected_branch"
SETTINGS_GITHOOKS = "repo/settings/githooks" tmplRepoSettingsGithooks = "repo/settings/githooks"
SETTINGS_GITHOOK_EDIT = "repo/settings/githook_edit" tmplRepoSettingsGithookEdit = "repo/settings/githook_edit"
SETTINGS_DEPLOY_KEYS = "repo/settings/deploy_keys" tmplRepoSettingsDeployKeys = "repo/settings/deploy_keys"
) )
func Settings(c *context.Context) { func Settings(c *context.Context) {
c.Title("repo.settings") c.Title("repo.settings")
c.PageIs("SettingsOptions") c.PageIs("SettingsOptions")
c.RequireAutosize() c.RequireAutosize()
c.Success(SETTINGS_OPTIONS) c.Success(tmplRepoSettingsOptions)
} }
func SettingsPost(c *context.Context, f form.RepoSetting) { func SettingsPost(c *context.Context, f form.RepoSetting) {
@ -53,7 +53,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
switch c.Query("action") { switch c.Query("action") {
case "update": case "update":
if c.HasError() { if c.HasError() {
c.Success(SETTINGS_OPTIONS) c.Success(tmplRepoSettingsOptions)
return return
} }
@ -67,9 +67,9 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
c.FormErr("RepoName") c.FormErr("RepoName")
switch { switch {
case database.IsErrRepoAlreadyExist(err): case database.IsErrRepoAlreadyExist(err):
c.RenderWithErr(c.Tr("form.repo_name_been_taken"), SETTINGS_OPTIONS, &f) c.RenderWithErr(c.Tr("form.repo_name_been_taken"), tmplRepoSettingsOptions, &f)
case database.IsErrNameNotAllowed(err): case database.IsErrNameNotAllowed(err):
c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), SETTINGS_OPTIONS, &f) c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplRepoSettingsOptions, &f)
default: default:
c.Error(err, "change repository name") c.Error(err, "change repository name")
} }
@ -179,7 +179,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil)
return return
} }
@ -213,7 +213,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil)
return return
} }
@ -226,13 +226,13 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
newOwner := c.Query("new_owner_name") newOwner := c.Query("new_owner_name")
if !database.Handle.Users().IsUsernameUsed(c.Req.Context(), newOwner, c.Repo.Owner.ID) { if !database.Handle.Users().IsUsernameUsed(c.Req.Context(), newOwner, c.Repo.Owner.ID) {
c.RenderWithErr(c.Tr("form.enterred_invalid_owner_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_owner_name"), tmplRepoSettingsOptions, nil)
return return
} }
if err := database.TransferOwnership(c.User, newOwner, repo); err != nil { if err := database.TransferOwnership(c.User, newOwner, repo); err != nil {
if database.IsErrRepoAlreadyExist(err) { if database.IsErrRepoAlreadyExist(err) {
c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), tmplRepoSettingsOptions, nil)
} else { } else {
c.Error(err, "transfer ownership") c.Error(err, "transfer ownership")
} }
@ -248,7 +248,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil)
return return
} }
@ -274,7 +274,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
return return
} }
if repo.Name != f.RepoName { if repo.Name != f.RepoName {
c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), SETTINGS_OPTIONS, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_repo_name"), tmplRepoSettingsOptions, nil)
return return
} }
@ -305,7 +305,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
func SettingsAvatar(c *context.Context) { func SettingsAvatar(c *context.Context) {
c.Title("settings.avatar") c.Title("settings.avatar")
c.PageIs("SettingsAvatar") c.PageIs("SettingsAvatar")
c.Success(SETTINGS_REPO_AVATAR) c.Success(tmplRepoSettingsAvatar)
} }
func SettingsAvatarPost(c *context.Context, f form.Avatar) { func SettingsAvatarPost(c *context.Context, f form.Avatar) {
@ -370,7 +370,7 @@ func SettingsCollaboration(c *context.Context) {
} }
c.Data["Collaborators"] = users c.Data["Collaborators"] = users
c.Success(SETTINGS_COLLABORATION) c.Success(tmplRepoSettingsCollaboration)
} }
func SettingsCollaborationPost(c *context.Context) { func SettingsCollaborationPost(c *context.Context) {
@ -440,7 +440,7 @@ func SettingsBranches(c *context.Context) {
if c.Repo.Repository.IsBare { if c.Repo.Repository.IsBare {
c.Flash.Info(c.Tr("repo.settings.branches_bare"), true) c.Flash.Info(c.Tr("repo.settings.branches_bare"), true)
c.Success(SETTINGS_BRANCHES) c.Success(tmplRepoSettingsBranches)
return return
} }
@ -459,7 +459,7 @@ func SettingsBranches(c *context.Context) {
} }
c.Data["ProtectBranches"] = branches c.Data["ProtectBranches"] = branches
c.Success(SETTINGS_BRANCHES) c.Success(tmplRepoSettingsBranches)
} }
func UpdateDefaultBranch(c *context.Context) { func UpdateDefaultBranch(c *context.Context) {
@ -527,7 +527,7 @@ func SettingsProtectedBranch(c *context.Context) {
} }
c.Data["Branch"] = protectBranch c.Data["Branch"] = protectBranch
c.Success(SETTINGS_PROTECTED_BRANCH) c.Success(tmplRepoSettingsProtectedBranch)
} }
func SettingsProtectedBranchPost(c *context.Context, f form.ProtectBranch) { func SettingsProtectedBranchPost(c *context.Context, f form.ProtectBranch) {
@ -579,7 +579,7 @@ func SettingsGitHooks(c *context.Context) {
} }
c.Data["Hooks"] = hooks c.Data["Hooks"] = hooks
c.Success(SETTINGS_GITHOOKS) c.Success(tmplRepoSettingsGithooks)
} }
func SettingsGitHooksEdit(c *context.Context) { func SettingsGitHooksEdit(c *context.Context) {
@ -594,7 +594,7 @@ func SettingsGitHooksEdit(c *context.Context) {
return return
} }
c.Data["Hook"] = hook c.Data["Hook"] = hook
c.Success(SETTINGS_GITHOOK_EDIT) c.Success(tmplRepoSettingsGithookEdit)
} }
func SettingsGitHooksEditPost(c *context.Context) { func SettingsGitHooksEditPost(c *context.Context) {
@ -622,7 +622,7 @@ func SettingsDeployKeys(c *context.Context) {
} }
c.Data["Deploykeys"] = keys c.Data["Deploykeys"] = keys
c.Success(SETTINGS_DEPLOY_KEYS) c.Success(tmplRepoSettingsDeployKeys)
} }
func SettingsDeployKeysPost(c *context.Context, f form.AddSSHKey) { func SettingsDeployKeysPost(c *context.Context, f form.AddSSHKey) {
@ -637,7 +637,7 @@ func SettingsDeployKeysPost(c *context.Context, f form.AddSSHKey) {
c.Data["Deploykeys"] = keys c.Data["Deploykeys"] = keys
if c.HasError() { if c.HasError() {
c.Success(SETTINGS_DEPLOY_KEYS) c.Success(tmplRepoSettingsDeployKeys)
return return
} }
@ -660,10 +660,10 @@ func SettingsDeployKeysPost(c *context.Context, f form.AddSSHKey) {
switch { switch {
case database.IsErrKeyAlreadyExist(err): case database.IsErrKeyAlreadyExist(err):
c.Data["Err_Content"] = true c.Data["Err_Content"] = true
c.RenderWithErr(c.Tr("repo.settings.key_been_used"), SETTINGS_DEPLOY_KEYS, &f) c.RenderWithErr(c.Tr("repo.settings.key_been_used"), tmplRepoSettingsDeployKeys, &f)
case database.IsErrKeyNameAlreadyUsed(err): case database.IsErrKeyNameAlreadyUsed(err):
c.Data["Err_Title"] = true c.Data["Err_Title"] = true
c.RenderWithErr(c.Tr("repo.settings.key_name_used"), SETTINGS_DEPLOY_KEYS, &f) c.RenderWithErr(c.Tr("repo.settings.key_name_used"), tmplRepoSettingsDeployKeys, &f)
default: default:
c.Error(err, "add deploy key") c.Error(err, "add deploy key")
} }

View File

@ -164,10 +164,8 @@ func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink stri
default: default:
// Building code view blocks with line number on server side. // Building code view blocks with line number on server side.
var fileContent string var fileContent string
if err, content := template.ToUTF8WithErr(p); err != nil { if content, err := template.ToUTF8WithErr(p); err != nil {
if err != nil { log.Error("ToUTF8WithErr: %s", err)
log.Error("ToUTF8WithErr: %s", err)
}
fileContent = string(p) fileContent = string(p)
} else { } else {
fileContent = content fileContent = content

View File

@ -545,7 +545,7 @@ func TestWebhook(c *context.Context) {
Pusher: apiUser, Pusher: apiUser,
Sender: apiUser, Sender: apiUser,
} }
if err := database.TestWebhook(c.Repo.Repository, database.HOOK_EVENT_PUSH, p, c.ParamsInt64("id")); err != nil { if err := database.TestWebhook(c.Repo.Repository, database.HookEventTypePush, p, c.ParamsInt64("id")); err != nil {
c.Error(err, "test webhook") c.Error(err, "test webhook")
return return
} }

View File

@ -18,10 +18,10 @@ import (
) )
const ( const (
WIKI_START = "repo/wiki/start" tmplRepoWikiStart = "repo/wiki/start"
WIKI_VIEW = "repo/wiki/view" tmplRepoWikiView = "repo/wiki/view"
WIKI_NEW = "repo/wiki/new" tmplRepoWikiNew = "repo/wiki/new"
WIKI_PAGES = "repo/wiki/pages" tmplRepoWikiPages = "repo/wiki/pages"
) )
func MustEnableWiki(c *context.Context) { func MustEnableWiki(c *context.Context) {
@ -114,7 +114,7 @@ func Wiki(c *context.Context) {
if !c.Repo.Repository.HasWiki() { if !c.Repo.Repository.HasWiki() {
c.Data["Title"] = c.Tr("repo.wiki") c.Data["Title"] = c.Tr("repo.wiki")
c.Success(WIKI_START) c.Success(tmplRepoWikiStart)
return return
} }
@ -131,7 +131,7 @@ func Wiki(c *context.Context) {
} }
c.Data["Author"] = commits[0].Author c.Data["Author"] = commits[0].Author
c.Success(WIKI_VIEW) c.Success(tmplRepoWikiView)
} }
func WikiPages(c *context.Context) { func WikiPages(c *context.Context) {
@ -177,7 +177,7 @@ func WikiPages(c *context.Context) {
} }
c.Data["Pages"] = pages c.Data["Pages"] = pages
c.Success(WIKI_PAGES) c.Success(tmplRepoWikiPages)
} }
func NewWiki(c *context.Context) { func NewWiki(c *context.Context) {
@ -189,7 +189,7 @@ func NewWiki(c *context.Context) {
c.Data["title"] = "Home" c.Data["title"] = "Home"
} }
c.Success(WIKI_NEW) c.Success(tmplRepoWikiNew)
} }
func NewWikiPost(c *context.Context, f form.NewWiki) { func NewWikiPost(c *context.Context, f form.NewWiki) {
@ -198,14 +198,14 @@ func NewWikiPost(c *context.Context, f form.NewWiki) {
c.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
if c.HasError() { if c.HasError() {
c.Success(WIKI_NEW) c.Success(tmplRepoWikiNew)
return return
} }
if err := c.Repo.Repository.AddWikiPage(c.User, f.Title, f.Content, f.Message); err != nil { if err := c.Repo.Repository.AddWikiPage(c.User, f.Title, f.Content, f.Message); err != nil {
if database.IsErrWikiAlreadyExist(err) { if database.IsErrWikiAlreadyExist(err) {
c.Data["Err_Title"] = true c.Data["Err_Title"] = true
c.RenderWithErr(c.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &f) c.RenderWithErr(c.Tr("repo.wiki.page_already_exists"), tmplRepoWikiNew, &f)
} else { } else {
c.Error(err, "add wiki page") c.Error(err, "add wiki page")
} }
@ -230,7 +230,7 @@ func EditWiki(c *context.Context) {
return return
} }
c.Success(WIKI_NEW) c.Success(tmplRepoWikiNew)
} }
func EditWikiPost(c *context.Context, f form.NewWiki) { func EditWikiPost(c *context.Context, f form.NewWiki) {
@ -239,7 +239,7 @@ func EditWikiPost(c *context.Context, f form.NewWiki) {
c.Data["RequireSimpleMDE"] = true c.Data["RequireSimpleMDE"] = true
if c.HasError() { if c.HasError() {
c.Success(WIKI_NEW) c.Success(tmplRepoWikiNew)
return return
} }

View File

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

View File

@ -18,11 +18,11 @@ import (
) )
const ( const (
DASHBOARD = "user/dashboard/dashboard" tmplUserDashboard = "user/dashboard/dashboard"
NEWS_FEED = "user/dashboard/feeds" tmplUserDashboardFeeds = "user/dashboard/feeds"
ISSUES = "user/dashboard/issues" tmplUserDashboardIssues = "user/dashboard/issues"
PROFILE = "user/profile" tmplUserProfile = "user/profile"
ORG_HOME = "org/home" tmplOrgHome = "org/home"
) )
// getDashboardContextUser finds out dashboard is viewing as which context user. // getDashboardContextUser finds out dashboard is viewing as which context user.
@ -115,7 +115,7 @@ func Dashboard(c *context.Context) {
} }
if c.Req.Header.Get("X-AJAX") == "true" { if c.Req.Header.Get("X-AJAX") == "true" {
c.Success(NEWS_FEED) c.Success(tmplUserDashboardFeeds)
return return
} }
@ -183,7 +183,7 @@ func Dashboard(c *context.Context) {
c.Data["MirrorCount"] = len(mirrors) c.Data["MirrorCount"] = len(mirrors)
c.Data["Mirrors"] = mirrors c.Data["Mirrors"] = mirrors
c.Success(DASHBOARD) c.Success(tmplUserDashboard)
} }
func Issues(c *context.Context) { func Issues(c *context.Context) {
@ -203,19 +203,19 @@ func Issues(c *context.Context) {
var ( var (
sortType = c.Query("sort") sortType = c.Query("sort")
filterMode = database.FILTER_MODE_YOUR_REPOS filterMode = database.FilterModeYourRepos
) )
// Note: Organization does not have view type and filter mode. // Note: Organization does not have view type and filter mode.
if !ctxUser.IsOrganization() { if !ctxUser.IsOrganization() {
viewType := c.Query("type") viewType := c.Query("type")
types := []string{ types := []string{
string(database.FILTER_MODE_YOUR_REPOS), string(database.FilterModeYourRepos),
string(database.FILTER_MODE_ASSIGN), string(database.FilterModeAssign),
string(database.FILTER_MODE_CREATE), string(database.FilterModeCreate),
} }
if !com.IsSliceContainsStr(types, viewType) { if !com.IsSliceContainsStr(types, viewType) {
viewType = string(database.FILTER_MODE_YOUR_REPOS) viewType = string(database.FilterModeYourRepos)
} }
filterMode = database.FilterMode(viewType) filterMode = database.FilterMode(viewType)
} }
@ -260,7 +260,7 @@ func Issues(c *context.Context) {
for _, repo := range repos { for _, repo := range repos {
userRepoIDs = append(userRepoIDs, repo.ID) userRepoIDs = append(userRepoIDs, repo.ID)
if filterMode != database.FILTER_MODE_YOUR_REPOS { if filterMode != database.FilterModeYourRepos {
continue continue
} }
@ -297,7 +297,7 @@ func Issues(c *context.Context) {
SortType: sortType, SortType: sortType,
} }
switch filterMode { switch filterMode {
case database.FILTER_MODE_YOUR_REPOS: case database.FilterModeYourRepos:
// Get all issues from repositories from this user. // Get all issues from repositories from this user.
if userRepoIDs == nil { if userRepoIDs == nil {
issueOptions.RepoIDs = []int64{-1} issueOptions.RepoIDs = []int64{-1}
@ -305,11 +305,11 @@ func Issues(c *context.Context) {
issueOptions.RepoIDs = userRepoIDs issueOptions.RepoIDs = userRepoIDs
} }
case database.FILTER_MODE_ASSIGN: case database.FilterModeAssign:
// Get all issues assigned to this user. // Get all issues assigned to this user.
issueOptions.AssigneeID = ctxUser.ID issueOptions.AssigneeID = ctxUser.ID
case database.FILTER_MODE_CREATE: case database.FilterModeCreate:
// Get all issues created by this user. // Get all issues created by this user.
issueOptions.PosterID = ctxUser.ID issueOptions.PosterID = ctxUser.ID
} }
@ -370,7 +370,7 @@ func Issues(c *context.Context) {
c.Data["State"] = "open" c.Data["State"] = "open"
} }
c.Success(ISSUES) c.Success(tmplUserDashboardIssues)
} }
func ShowSSHKeys(c *context.Context, uid int64) { func ShowSSHKeys(c *context.Context, uid int64) {
@ -440,7 +440,7 @@ func showOrgProfile(c *context.Context) {
c.Data["Teams"] = org.Teams c.Data["Teams"] = org.Teams
c.Success(ORG_HOME) c.Success(tmplOrgHome)
} }
func Email2User(c *context.Context) { func Email2User(c *context.Context) {

View File

@ -22,13 +22,8 @@ const (
) )
func Profile(c *context.Context, puser *context.ParamsUser) { func Profile(c *context.Context, puser *context.ParamsUser) {
isShowKeys := false
if strings.HasSuffix(c.Params(":username"), ".keys") {
isShowKeys = true
}
// Show SSH keys. // Show SSH keys.
if isShowKeys { if strings.HasSuffix(c.Params(":username"), ".keys") {
ShowSSHKeys(c, puser.ID) ShowSSHKeys(c, puser.ID)
return return
} }
@ -80,7 +75,7 @@ func Profile(c *context.Context, puser *context.ParamsUser) {
c.Data["Page"] = paginater.New(int(count), conf.UI.User.RepoPagingNum, page, 5) c.Data["Page"] = paginater.New(int(count), conf.UI.User.RepoPagingNum, page, 5)
} }
c.Success(PROFILE) c.Success(tmplUserProfile)
} }
func Followers(c *context.Context, puser *context.ParamsUser) { func Followers(c *context.Context, puser *context.ParamsUser) {

View File

@ -43,19 +43,19 @@ func NewSettingsHandler(s SettingsStore) *SettingsHandler {
} }
const ( const (
SETTINGS_PROFILE = "user/settings/profile" tmplUserSettingsProfile = "user/settings/profile"
SETTINGS_AVATAR = "user/settings/avatar" tmplUserSettingsAvatar = "user/settings/avatar"
SETTINGS_PASSWORD = "user/settings/password" tmplUserSettingsPassword = "user/settings/password"
SETTINGS_EMAILS = "user/settings/email" tmplUserSettingsEmail = "user/settings/email"
SETTINGS_SSH_KEYS = "user/settings/sshkeys" tmplUserSettingsSSHKeys = "user/settings/sshkeys"
SETTINGS_SECURITY = "user/settings/security" tmplUserSettingsSecurity = "user/settings/security"
SETTINGS_TWO_FACTOR_ENABLE = "user/settings/two_factor_enable" tmplUserSettingsTwoFactorEnable = "user/settings/two_factor_enable"
SETTINGS_TWO_FACTOR_RECOVERY_CODES = "user/settings/two_factor_recovery_codes" tmplUserSettingsTwoFactorRecoveryCodes = "user/settings/two_factor_recovery_codes"
SETTINGS_REPOSITORIES = "user/settings/repositories" tmplUserSettingsRepositories = "user/settings/repositories"
SETTINGS_ORGANIZATIONS = "user/settings/organizations" tmplUserSettingsOrganizations = "user/settings/organizations"
SETTINGS_APPLICATIONS = "user/settings/applications" tmplUserSettingsApplications = "user/settings/applications"
SETTINGS_DELETE = "user/settings/delete" tmplUserSettingsDelete = "user/settings/delete"
NOTIFICATION = "user/notification" tmplUserNotification = "user/notification"
) )
func Settings(c *context.Context) { func Settings(c *context.Context) {
@ -67,7 +67,7 @@ func Settings(c *context.Context) {
c.Data["email"] = c.User.Email c.Data["email"] = c.User.Email
c.Data["website"] = c.User.Website c.Data["website"] = c.User.Website
c.Data["location"] = c.User.Location c.Data["location"] = c.User.Location
c.Success(SETTINGS_PROFILE) c.Success(tmplUserSettingsProfile)
} }
func SettingsPost(c *context.Context, f form.UpdateProfile) { func SettingsPost(c *context.Context, f form.UpdateProfile) {
@ -76,7 +76,7 @@ func SettingsPost(c *context.Context, f form.UpdateProfile) {
c.Data["origin_name"] = c.User.Name c.Data["origin_name"] = c.User.Name
if c.HasError() { if c.HasError() {
c.Success(SETTINGS_PROFILE) c.Success(tmplUserSettingsProfile)
return return
} }
@ -98,7 +98,7 @@ func SettingsPost(c *context.Context, f form.UpdateProfile) {
return return
} }
c.RenderWithErr(msg, SETTINGS_PROFILE, &f) c.RenderWithErr(msg, tmplUserSettingsProfile, &f)
return return
} }
@ -174,7 +174,7 @@ func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxUser *database.Us
func SettingsAvatar(c *context.Context) { func SettingsAvatar(c *context.Context) {
c.Title("settings.avatar") c.Title("settings.avatar")
c.PageIs("SettingsAvatar") c.PageIs("SettingsAvatar")
c.Success(SETTINGS_AVATAR) c.Success(tmplUserSettingsAvatar)
} }
func SettingsAvatarPost(c *context.Context, f form.Avatar) { func SettingsAvatarPost(c *context.Context, f form.Avatar) {
@ -199,7 +199,7 @@ func SettingsDeleteAvatar(c *context.Context) {
func SettingsPassword(c *context.Context) { func SettingsPassword(c *context.Context) {
c.Title("settings.password") c.Title("settings.password")
c.PageIs("SettingsPassword") c.PageIs("SettingsPassword")
c.Success(SETTINGS_PASSWORD) c.Success(tmplUserSettingsPassword)
} }
func SettingsPasswordPost(c *context.Context, f form.ChangePassword) { func SettingsPasswordPost(c *context.Context, f form.ChangePassword) {
@ -207,7 +207,7 @@ func SettingsPasswordPost(c *context.Context, f form.ChangePassword) {
c.PageIs("SettingsPassword") c.PageIs("SettingsPassword")
if c.HasError() { if c.HasError() {
c.Success(SETTINGS_PASSWORD) c.Success(tmplUserSettingsPassword)
return return
} }
@ -244,7 +244,7 @@ func SettingsEmails(c *context.Context) {
} }
c.Data["Emails"] = emails c.Data["Emails"] = emails
c.Success(SETTINGS_EMAILS) c.Success(tmplUserSettingsEmail)
} }
func SettingsEmailPost(c *context.Context, f form.AddEmail) { func SettingsEmailPost(c *context.Context, f form.AddEmail) {
@ -271,14 +271,14 @@ func SettingsEmailPost(c *context.Context, f form.AddEmail) {
c.Data["Emails"] = emails c.Data["Emails"] = emails
if c.HasError() { if c.HasError() {
c.Success(SETTINGS_EMAILS) c.Success(tmplUserSettingsEmail)
return return
} }
err = database.Handle.Users().AddEmail(c.Req.Context(), c.User.ID, f.Email, !conf.Auth.RequireEmailConfirmation) err = database.Handle.Users().AddEmail(c.Req.Context(), c.User.ID, f.Email, !conf.Auth.RequireEmailConfirmation)
if err != nil { if err != nil {
if database.IsErrEmailAlreadyUsed(err) { if database.IsErrEmailAlreadyUsed(err) {
c.RenderWithErr(c.Tr("form.email_been_used"), SETTINGS_EMAILS, &f) c.RenderWithErr(c.Tr("form.email_been_used"), tmplUserSettingsEmail, &f)
} else { } else {
c.Errorf(err, "add email address") c.Errorf(err, "add email address")
} }
@ -333,7 +333,7 @@ func SettingsSSHKeys(c *context.Context) {
} }
c.Data["Keys"] = keys c.Data["Keys"] = keys
c.Success(SETTINGS_SSH_KEYS) c.Success(tmplUserSettingsSSHKeys)
} }
func SettingsSSHKeysPost(c *context.Context, f form.AddSSHKey) { func SettingsSSHKeysPost(c *context.Context, f form.AddSSHKey) {
@ -348,7 +348,7 @@ func SettingsSSHKeysPost(c *context.Context, f form.AddSSHKey) {
c.Data["Keys"] = keys c.Data["Keys"] = keys
if c.HasError() { if c.HasError() {
c.Success(SETTINGS_SSH_KEYS) c.Success(tmplUserSettingsSSHKeys)
return return
} }
@ -368,10 +368,10 @@ func SettingsSSHKeysPost(c *context.Context, f form.AddSSHKey) {
switch { switch {
case database.IsErrKeyAlreadyExist(err): case database.IsErrKeyAlreadyExist(err):
c.FormErr("Content") c.FormErr("Content")
c.RenderWithErr(c.Tr("settings.ssh_key_been_used"), SETTINGS_SSH_KEYS, &f) c.RenderWithErr(c.Tr("settings.ssh_key_been_used"), tmplUserSettingsSSHKeys, &f)
case database.IsErrKeyNameAlreadyUsed(err): case database.IsErrKeyNameAlreadyUsed(err):
c.FormErr("Title") c.FormErr("Title")
c.RenderWithErr(c.Tr("settings.ssh_key_name_used"), SETTINGS_SSH_KEYS, &f) c.RenderWithErr(c.Tr("settings.ssh_key_name_used"), tmplUserSettingsSSHKeys, &f)
default: default:
c.Errorf(err, "add public key") c.Errorf(err, "add public key")
} }
@ -405,7 +405,7 @@ func SettingsSecurity(c *context.Context) {
} }
c.Data["TwoFactor"] = t c.Data["TwoFactor"] = t
c.Success(SETTINGS_SECURITY) c.Success(tmplUserSettingsSecurity)
} }
func SettingsTwoFactorEnable(c *context.Context) { func SettingsTwoFactorEnable(c *context.Context) {
@ -450,7 +450,7 @@ func SettingsTwoFactorEnable(c *context.Context) {
_ = c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"]) _ = c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"])
_ = c.Session.Set("twoFactorURL", key.String()) _ = c.Session.Set("twoFactorURL", key.String())
c.Success(SETTINGS_TWO_FACTOR_ENABLE) c.Success(tmplUserSettingsTwoFactorEnable)
} }
func SettingsTwoFactorEnablePost(c *context.Context) { func SettingsTwoFactorEnablePost(c *context.Context) {
@ -494,7 +494,7 @@ func SettingsTwoFactorRecoveryCodes(c *context.Context) {
} }
c.Data["RecoveryCodes"] = recoveryCodes c.Data["RecoveryCodes"] = recoveryCodes
c.Success(SETTINGS_TWO_FACTOR_RECOVERY_CODES) c.Success(tmplUserSettingsTwoFactorRecoveryCodes)
} }
func SettingsTwoFactorRecoveryCodesPost(c *context.Context) { func SettingsTwoFactorRecoveryCodesPost(c *context.Context) {
@ -544,7 +544,7 @@ func SettingsRepos(c *context.Context) {
} }
c.Data["Repos"] = repos c.Data["Repos"] = repos
c.Success(SETTINGS_REPOSITORIES) c.Success(tmplUserSettingsRepositories)
} }
func SettingsLeaveRepo(c *context.Context) { func SettingsLeaveRepo(c *context.Context) {
@ -576,7 +576,7 @@ func SettingsOrganizations(c *context.Context) {
} }
c.Data["Orgs"] = orgs c.Data["Orgs"] = orgs
c.Success(SETTINGS_ORGANIZATIONS) c.Success(tmplUserSettingsOrganizations)
} }
func SettingsLeaveOrganization(c *context.Context) { func SettingsLeaveOrganization(c *context.Context) {
@ -606,7 +606,7 @@ func (h *SettingsHandler) Applications() macaron.Handler {
} }
c.Data["Tokens"] = tokens c.Data["Tokens"] = tokens
c.Success(SETTINGS_APPLICATIONS) c.Success(tmplUserSettingsApplications)
} }
} }
@ -623,7 +623,7 @@ func (h *SettingsHandler) ApplicationsPost() macaron.Handler {
} }
c.Data["Tokens"] = tokens c.Data["Tokens"] = tokens
c.Success(SETTINGS_APPLICATIONS) c.Success(tmplUserSettingsApplications)
return return
} }
@ -665,7 +665,7 @@ func SettingsDelete(c *context.Context) {
if c.Req.Method == "POST" { if c.Req.Method == "POST" {
if _, err := database.Handle.Users().Authenticate(c.Req.Context(), c.User.Name, c.Query("password"), c.User.LoginSource); err != nil { if _, err := database.Handle.Users().Authenticate(c.Req.Context(), c.User.Name, c.Query("password"), c.User.LoginSource); err != nil {
if auth.IsErrBadCredentials(err) { if auth.IsErrBadCredentials(err) {
c.RenderWithErr(c.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil) c.RenderWithErr(c.Tr("form.enterred_invalid_password"), tmplUserSettingsDelete, nil)
} else { } else {
c.Errorf(err, "authenticate user") c.Errorf(err, "authenticate user")
} }
@ -690,7 +690,7 @@ func SettingsDelete(c *context.Context) {
return return
} }
c.Success(SETTINGS_DELETE) c.Success(tmplUserSettingsDelete)
} }
// SettingsStore is the data layer carrier for user settings endpoints. This // SettingsStore is the data layer carrier for user settings endpoints. This

View File

@ -154,27 +154,27 @@ func Sha1(str string) string {
return cryptoutil.SHA1(str) return cryptoutil.SHA1(str)
} }
func ToUTF8WithErr(content []byte) (error, string) { func ToUTF8WithErr(content []byte) (string, error) {
charsetLabel, err := tool.DetectEncoding(content) charsetLabel, err := tool.DetectEncoding(content)
if err != nil { if err != nil {
return err, "" return "", err
} else if charsetLabel == "UTF-8" { } else if charsetLabel == "UTF-8" {
return nil, string(content) return string(content), nil
} }
encoding, _ := charset.Lookup(charsetLabel) encoding, _ := charset.Lookup(charsetLabel)
if encoding == nil { if encoding == nil {
return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content) return string(content), fmt.Errorf("unknown encoding: %s", charsetLabel)
} }
// If there is an error, we concatenate the nicely decoded part and the // 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)) result, n, err := transform.String(encoding.NewDecoder(), string(content))
if err != nil { if err != nil {
result = result + string(content[n:]) result = result + string(content[n:])
} }
return err, result return result, err
} }
// RenderCommitMessage renders commit message with special links. // RenderCommitMessage renders commit message with special links.

View File

@ -89,7 +89,7 @@ func VerifyTimeLimitCode(data string, minutes int, code string) bool {
return false 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. // CreateTimeLimitCode generates a time limit code based on given input data.
// Format: 12 length date time string + 6 minutes string + 40 sha1 encoded string // 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 var timeStr, diffStr string
for { for diff != 0 {
if diff == 0 {
break
}
diff, diffStr = computeTimeDiff(diff) diff, diffStr = computeTimeDiff(diff)
timeStr += ", " + diffStr timeStr += ", " + diffStr
} }

View File

@ -40,7 +40,7 @@ func TestGenerateActivateCode(t *testing.T) {
) )
code := GenerateActivateCode(1, "alice@example.com", "Alice", "123456", "rands") 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) assert.True(t, got)
} }