Compare commits

..

No commits in common. "d020343269eaa136abd0c4893f1373560c6cf433" and "50166d1f7c6df41c79561b094e29c9698c0000d5" have entirely different histories.

178 changed files with 993 additions and 1172 deletions

428
.drone.yml Normal file
View File

@ -0,0 +1,428 @@
---
kind: pipeline
name: release-version
platform:
os: linux
arch: amd64
workspace:
base: /source
path: /
trigger:
event:
- tag
volumes:
- name: deps
temp: {}
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git fetch --tags --force
- name: deps-frontend
image: node:20
pull: always
commands:
- make deps-frontend
- name: deps-backend
image: gitea/test_env:linux-1.20-amd64
pull: always
commands:
- make deps-backend
volumes:
- name: deps
path: /go
- name: static
image: techknowlogick/xgo:go-1.21.x
pull: always
commands:
- apt-get update && apt-get -qqy install ca-certificates curl gnupg
- mkdir -p /etc/apt/keyrings && curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
- echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" > /etc/apt/sources.list.d/nodesource.list
- apt-get update && apt-get -qqy install nodejs
- export PATH=$PATH:$GOPATH/bin
- make release
environment:
GOPROXY: https://goproxy.io # proxy.golang.org is blocked in China, this proxy is not
TAGS: bindata sqlite sqlite_unlock_notify
DEBIAN_FRONTEND: noninteractive
depends_on: [fetch-tags]
volumes:
- name: deps
path: /go
- name: gpg-sign
image: plugins/gpgsign:1
pull: always
settings:
detach_sign: true
excludes:
- "dist/release/*.sha256"
files:
- "dist/release/*"
environment:
GPGSIGN_KEY:
from_secret: gpgsign_key
GPGSIGN_PASSPHRASE:
from_secret: gpgsign_passphrase
depends_on: [static]
- name: release-tag
image: woodpeckerci/plugin-s3:latest
pull: always
settings:
acl:
from_secret: aws_s3_acl
region:
from_secret: aws_s3_region
bucket:
from_secret: aws_s3_bucket
endpoint:
from_secret: aws_s3_endpoint
path_style:
from_secret: aws_s3_path_style
source: "dist/release/*"
strip_prefix: dist/release/
target: "/gitea/${DRONE_TAG##v}"
environment:
AWS_ACCESS_KEY_ID:
from_secret: aws_access_key_id
AWS_SECRET_ACCESS_KEY:
from_secret: aws_secret_access_key
depends_on: [gpg-sign]
- name: github
image: plugins/github-release:latest
pull: always
settings:
files:
- "dist/release/*"
file_exists: overwrite
environment:
GITHUB_TOKEN:
from_secret: github_token
depends_on: [gpg-sign]
---
kind: pipeline
type: docker
name: docker-linux-amd64-release-version
platform:
os: linux
arch: amd64
trigger:
ref:
include:
- "refs/tags/**"
exclude:
- "refs/tags/**-rc*"
paths:
exclude:
- "docs/**"
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
pull: always
settings:
auto_tag: true
auto_tag_suffix: linux-amd64
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
- name: publish-rootless
image: plugins/docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: true
auto_tag_suffix: linux-amd64-rootless
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
---
kind: pipeline
type: docker
name: docker-linux-amd64-release-candidate-version
platform:
os: linux
arch: amd64
trigger:
ref:
- "refs/tags/**-rc*"
paths:
exclude:
- "docs/**"
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
pull: always
settings:
tags: ${DRONE_TAG##v}-linux-amd64
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
- name: publish-rootless
image: plugins/docker:latest
settings:
dockerfile: Dockerfile.rootless
tags: ${DRONE_TAG##v}-linux-amd64-rootless
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
---
kind: pipeline
type: docker
name: docker-linux-arm64-release-version
platform:
os: linux
arch: arm64
trigger:
ref:
include:
- "refs/tags/**"
exclude:
- "refs/tags/**-rc*"
paths:
exclude:
- "docs/**"
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
pull: always
settings:
auto_tag: true
auto_tag_suffix: linux-arm64
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
- name: publish-rootless
image: plugins/docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: true
auto_tag_suffix: linux-arm64-rootless
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
---
kind: pipeline
type: docker
name: docker-linux-arm64-release-candidate-version
platform:
os: linux
arch: arm64
trigger:
ref:
- "refs/tags/**-rc*"
paths:
exclude:
- "docs/**"
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
pull: always
settings:
tags: ${DRONE_TAG##v}-linux-arm64
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
- name: publish-rootless
image: plugins/docker:latest
settings:
dockerfile: Dockerfile.rootless
tags: ${DRONE_TAG##v}-linux-arm64-rootless
repo: gitea/gitea
build_args:
- GOPROXY=https://goproxy.io
password:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
- pull_request
---
kind: pipeline
type: docker
name: docker-manifest-version
platform:
os: linux
arch: amd64
steps:
- name: manifest-rootless
image: plugins/manifest
pull: always
settings:
auto_tag: true
ignore_missing: true
spec: docker/manifest.rootless.tmpl
password:
from_secret: docker_password
username:
from_secret: docker_username
- name: manifest
image: plugins/manifest
settings:
auto_tag: true
ignore_missing: true
spec: docker/manifest.tmpl
password:
from_secret: docker_password
username:
from_secret: docker_username
trigger:
ref:
- "refs/tags/**"
paths:
exclude:
- "docs/**"
depends_on:
- docker-linux-amd64-release-version
- docker-linux-amd64-release-candidate-version
- docker-linux-arm64-release-version
- docker-linux-arm64-release-candidate-version

View File

@ -1,6 +1,6 @@
name: Bug Report name: Bug Report
description: Found something you weren't expecting? Report it here! description: Found something you weren't expecting? Report it here!
labels: ["type/bug"] labels: ["kind/bug"]
body: body:
- type: markdown - type: markdown
attributes: attributes:

View File

@ -1,6 +1,6 @@
name: Feature Request name: Feature Request
description: Got an idea for a feature that Gitea doesn't have currently? Submit your idea here! description: Got an idea for a feature that Gitea doesn't have currently? Submit your idea here!
labels: ["type/proposal"] labels: ["kind/proposal"]
body: body:
- type: markdown - type: markdown
attributes: attributes:

View File

@ -1,6 +1,6 @@
name: Web Interface Bug Report name: Web Interface Bug Report
description: Something doesn't look quite as it should? Report it here! description: Something doesn't look quite as it should? Report it here!
labels: ["type/bug", "topic/ui"] labels: ["kind/bug", "kind/ui"]
body: body:
- type: markdown - type: markdown
attributes: attributes:

View File

@ -1,4 +1,4 @@
name: release-nightly name: release-nightly-assets
on: on:
push: push:

View File

@ -1,125 +0,0 @@
name: release-tag-rc
on:
push:
tags:
- 'v1*-rc*'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
jobs:
binary:
runs-on: nscloud
steps:
- uses: actions/checkout@v4
# fetch all commits instead of only the last as some branches are long lived and could have many between versions
# fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567
- run: git fetch --unshallow --quiet --tags --force
- uses: actions/setup-go@v4
with:
go-version: "~1.21"
check-latest: true
- uses: actions/setup-node@v3
with:
node-version: 20
- run: make deps-frontend deps-backend
# xgo build
- run: make release
env:
TAGS: bindata sqlite sqlite_unlock_notify
- name: import gpg key
id: import_gpg
uses: crazy-max/ghaction-import-gpg@v5
with:
gpg_private_key: ${{ secrets.GPGSIGN_KEY }}
passphrase: ${{ secrets.GPGSIGN_PASSPHRASE }}
- name: sign binaries
run: |
for f in dist/release/*; do
echo '${{ secrets.GPGSIGN_PASSPHRASE }}' | gpg --pinentry-mode loopback --passphrase-fd 0 --batch --yes --detach-sign -u ${{ steps.import_gpg.outputs.fingerprint }} --output "$f.asc" "$f"
done
# clean branch name to get the folder name in S3
- name: Get cleaned branch name
id: clean_name
run: |
REF_NAME=$(echo "${{ github.ref }}" | sed -e 's/refs\/heads\///' -e 's/refs\/tags\///' -e 's/release\/v//')
echo "Cleaned name is ${REF_NAME}"
echo "branch=${REF_NAME}" >> "$GITHUB_OUTPUT"
- name: configure aws
uses: aws-actions/configure-aws-credentials@v4
with:
aws-region: ${{ secrets.AWS_REGION }}
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
- name: upload binaries to s3
run: |
aws s3 sync dist/release s3://${{ secrets.AWS_S3_BUCKET }}/gitea/${{ steps.clean_name.outputs.branch }} --no-progress
- name: create github release
run: |
gh release create ${{ github.ref_name }} --title ${{ github.ref_name }} --draft --notes-from-tag dist/release/*
env:
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
docker-rootful:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# fetch all commits instead of only the last as some branches are long lived and could have many between versions
# fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567
- run: git fetch --unshallow --quiet --tags --force
- uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v2
- uses: docker/metadata-action@v5
id: meta
with:
images: gitea/gitea
# 1.2.3-rc0
tags: |
type=semver,pattern={{version}}
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: build rootful docker image
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
docker-rootless:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# fetch all commits instead of only the last as some branches are long lived and could have many between versions
# fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567
- run: git fetch --unshallow --quiet --tags --force
- uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v2
- uses: docker/metadata-action@v5
id: meta
with:
images: gitea/gitea
# each tag below will have the suffix of -rootless
flavor: |
suffix=-rootless
# 1.2.3-rc0
tags: |
type=semver,pattern={{version}}
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: build rootless docker image
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
file: Dockerfile.rootless
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

View File

@ -1,141 +0,0 @@
name: release-tag-version
on:
push:
tags:
- 'v1.*'
- '!v1*-rc*'
- '!v1*-dev'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
jobs:
binary:
runs-on: nscloud
steps:
- uses: actions/checkout@v4
# fetch all commits instead of only the last as some branches are long lived and could have many between versions
# fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567
- run: git fetch --unshallow --quiet --tags --force
- uses: actions/setup-go@v4
with:
go-version: "~1.21"
check-latest: true
- uses: actions/setup-node@v3
with:
node-version: 20
- run: make deps-frontend deps-backend
# xgo build
- run: make release
env:
TAGS: bindata sqlite sqlite_unlock_notify
- name: import gpg key
id: import_gpg
uses: crazy-max/ghaction-import-gpg@v5
with:
gpg_private_key: ${{ secrets.GPGSIGN_KEY }}
passphrase: ${{ secrets.GPGSIGN_PASSPHRASE }}
- name: sign binaries
run: |
for f in dist/release/*; do
echo '${{ secrets.GPGSIGN_PASSPHRASE }}' | gpg --pinentry-mode loopback --passphrase-fd 0 --batch --yes --detach-sign -u ${{ steps.import_gpg.outputs.fingerprint }} --output "$f.asc" "$f"
done
# clean branch name to get the folder name in S3
- name: Get cleaned branch name
id: clean_name
run: |
REF_NAME=$(echo "${{ github.ref }}" | sed -e 's/refs\/heads\///' -e 's/refs\/tags\///' -e 's/release\/v//')
echo "Cleaned name is ${REF_NAME}"
echo "branch=${REF_NAME}" >> "$GITHUB_OUTPUT"
- name: configure aws
uses: aws-actions/configure-aws-credentials@v4
with:
aws-region: ${{ secrets.AWS_REGION }}
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
- name: upload binaries to s3
run: |
aws s3 sync dist/release s3://${{ secrets.AWS_S3_BUCKET }}/gitea/${{ steps.clean_name.outputs.branch }} --no-progress
- name: create github release
run: |
gh release create ${{ github.ref_name }} --title ${{ github.ref_name }} --draft --notes-from-tag dist/release/*
env:
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
docker-rootful:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# fetch all commits instead of only the last as some branches are long lived and could have many between versions
# fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567
- run: git fetch --unshallow --quiet --tags --force
- uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v2
- uses: docker/metadata-action@v5
id: meta
with:
images: gitea/gitea
# this will generate tags in the following format:
# latest
# 1
# 1.2
# 1.2.3
tags: |
type=raw,value=latest
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{version}}
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: build rootful docker image
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
docker-rootless:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# fetch all commits instead of only the last as some branches are long lived and could have many between versions
# fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567
- run: git fetch --unshallow --quiet --tags --force
- uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v2
- uses: docker/metadata-action@v5
id: meta
with:
images: gitea/gitea
# each tag below will have the suffix of -rootless
flavor: |
suffix=-rootless
# this will generate tags in the following format (with -rootless suffix added):
# latest
# 1
# 1.2
# 1.2.3
tags: |
type=raw,value=latest
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{version}}
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: build rootless docker image
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
file: Dockerfile.rootless
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

View File

@ -24,6 +24,8 @@ rules:
document-start: document-start:
level: error level: error
present: false present: false
ignore: |
/.drone.yml
document-end: document-end:
present: false present: false

View File

@ -62,7 +62,7 @@ func runListAuth(c *cli.Context) error {
return err return err
} }
authSources, err := auth_model.Sources(ctx) authSources, err := auth_model.Sources()
if err != nil { if err != nil {
return err return err
} }
@ -100,7 +100,7 @@ func runDeleteAuth(c *cli.Context) error {
return err return err
} }
source, err := auth_model.GetSourceByID(ctx, c.Int64("id")) source, err := auth_model.GetSourceByID(c.Int64("id"))
if err != nil { if err != nil {
return err return err
} }

View File

@ -17,9 +17,9 @@ import (
type ( type (
authService struct { authService struct {
initDB func(ctx context.Context) error initDB func(ctx context.Context) error
createAuthSource func(context.Context, *auth.Source) error createAuthSource func(*auth.Source) error
updateAuthSource func(context.Context, *auth.Source) error updateAuthSource func(*auth.Source) error
getAuthSourceByID func(ctx context.Context, id int64) (*auth.Source, error) getAuthSourceByID func(id int64) (*auth.Source, error)
} }
) )
@ -289,12 +289,12 @@ func findLdapSecurityProtocolByName(name string) (ldap.SecurityProtocol, bool) {
// getAuthSource gets the login source by its id defined in the command line flags. // getAuthSource gets the login source by its id defined in the command line flags.
// It returns an error if the id is not set, does not match any source or if the source is not of expected type. // It returns an error if the id is not set, does not match any source or if the source is not of expected type.
func (a *authService) getAuthSource(ctx context.Context, c *cli.Context, authType auth.Type) (*auth.Source, error) { func (a *authService) getAuthSource(c *cli.Context, authType auth.Type) (*auth.Source, error) {
if err := argsSet(c, "id"); err != nil { if err := argsSet(c, "id"); err != nil {
return nil, err return nil, err
} }
authSource, err := a.getAuthSourceByID(ctx, c.Int64("id")) authSource, err := a.getAuthSourceByID(c.Int64("id"))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -332,7 +332,7 @@ func (a *authService) addLdapBindDn(c *cli.Context) error {
return err return err
} }
return a.createAuthSource(ctx, authSource) return a.createAuthSource(authSource)
} }
// updateLdapBindDn updates a new LDAP via Bind DN authentication source. // updateLdapBindDn updates a new LDAP via Bind DN authentication source.
@ -344,7 +344,7 @@ func (a *authService) updateLdapBindDn(c *cli.Context) error {
return err return err
} }
authSource, err := a.getAuthSource(ctx, c, auth.LDAP) authSource, err := a.getAuthSource(c, auth.LDAP)
if err != nil { if err != nil {
return err return err
} }
@ -354,7 +354,7 @@ func (a *authService) updateLdapBindDn(c *cli.Context) error {
return err return err
} }
return a.updateAuthSource(ctx, authSource) return a.updateAuthSource(authSource)
} }
// addLdapSimpleAuth adds a new LDAP (simple auth) authentication source. // addLdapSimpleAuth adds a new LDAP (simple auth) authentication source.
@ -383,7 +383,7 @@ func (a *authService) addLdapSimpleAuth(c *cli.Context) error {
return err return err
} }
return a.createAuthSource(ctx, authSource) return a.createAuthSource(authSource)
} }
// updateLdapBindDn updates a new LDAP (simple auth) authentication source. // updateLdapBindDn updates a new LDAP (simple auth) authentication source.
@ -395,7 +395,7 @@ func (a *authService) updateLdapSimpleAuth(c *cli.Context) error {
return err return err
} }
authSource, err := a.getAuthSource(ctx, c, auth.DLDAP) authSource, err := a.getAuthSource(c, auth.DLDAP)
if err != nil { if err != nil {
return err return err
} }
@ -405,5 +405,5 @@ func (a *authService) updateLdapSimpleAuth(c *cli.Context) error {
return err return err
} }
return a.updateAuthSource(ctx, authSource) return a.updateAuthSource(authSource)
} }

View File

@ -210,15 +210,15 @@ func TestAddLdapBindDn(t *testing.T) {
initDB: func(context.Context) error { initDB: func(context.Context) error {
return nil return nil
}, },
createAuthSource: func(ctx context.Context, authSource *auth.Source) error { createAuthSource: func(authSource *auth.Source) error {
createdAuthSource = authSource createdAuthSource = authSource
return nil return nil
}, },
updateAuthSource: func(ctx context.Context, authSource *auth.Source) error { updateAuthSource: func(authSource *auth.Source) error {
assert.FailNow(t, "case %d: should not call updateAuthSource", n) assert.FailNow(t, "case %d: should not call updateAuthSource", n)
return nil return nil
}, },
getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) { getAuthSourceByID: func(id int64) (*auth.Source, error) {
assert.FailNow(t, "case %d: should not call getAuthSourceByID", n) assert.FailNow(t, "case %d: should not call getAuthSourceByID", n)
return nil, nil return nil, nil
}, },
@ -441,15 +441,15 @@ func TestAddLdapSimpleAuth(t *testing.T) {
initDB: func(context.Context) error { initDB: func(context.Context) error {
return nil return nil
}, },
createAuthSource: func(ctx context.Context, authSource *auth.Source) error { createAuthSource: func(authSource *auth.Source) error {
createdAuthSource = authSource createdAuthSource = authSource
return nil return nil
}, },
updateAuthSource: func(ctx context.Context, authSource *auth.Source) error { updateAuthSource: func(authSource *auth.Source) error {
assert.FailNow(t, "case %d: should not call updateAuthSource", n) assert.FailNow(t, "case %d: should not call updateAuthSource", n)
return nil return nil
}, },
getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) { getAuthSourceByID: func(id int64) (*auth.Source, error) {
assert.FailNow(t, "case %d: should not call getAuthSourceByID", n) assert.FailNow(t, "case %d: should not call getAuthSourceByID", n)
return nil, nil return nil, nil
}, },
@ -896,15 +896,15 @@ func TestUpdateLdapBindDn(t *testing.T) {
initDB: func(context.Context) error { initDB: func(context.Context) error {
return nil return nil
}, },
createAuthSource: func(ctx context.Context, authSource *auth.Source) error { createAuthSource: func(authSource *auth.Source) error {
assert.FailNow(t, "case %d: should not call createAuthSource", n) assert.FailNow(t, "case %d: should not call createAuthSource", n)
return nil return nil
}, },
updateAuthSource: func(ctx context.Context, authSource *auth.Source) error { updateAuthSource: func(authSource *auth.Source) error {
updatedAuthSource = authSource updatedAuthSource = authSource
return nil return nil
}, },
getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) { getAuthSourceByID: func(id int64) (*auth.Source, error) {
if c.id != 0 { if c.id != 0 {
assert.Equal(t, c.id, id, "case %d: wrong id", n) assert.Equal(t, c.id, id, "case %d: wrong id", n)
} }
@ -1286,15 +1286,15 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
initDB: func(context.Context) error { initDB: func(context.Context) error {
return nil return nil
}, },
createAuthSource: func(ctx context.Context, authSource *auth.Source) error { createAuthSource: func(authSource *auth.Source) error {
assert.FailNow(t, "case %d: should not call createAuthSource", n) assert.FailNow(t, "case %d: should not call createAuthSource", n)
return nil return nil
}, },
updateAuthSource: func(ctx context.Context, authSource *auth.Source) error { updateAuthSource: func(authSource *auth.Source) error {
updatedAuthSource = authSource updatedAuthSource = authSource
return nil return nil
}, },
getAuthSourceByID: func(ctx context.Context, id int64) (*auth.Source, error) { getAuthSourceByID: func(id int64) (*auth.Source, error) {
if c.id != 0 { if c.id != 0 {
assert.Equal(t, c.id, id, "case %d: wrong id", n) assert.Equal(t, c.id, id, "case %d: wrong id", n)
} }

View File

@ -183,7 +183,7 @@ func runAddOauth(c *cli.Context) error {
} }
} }
return auth_model.CreateSource(ctx, &auth_model.Source{ return auth_model.CreateSource(&auth_model.Source{
Type: auth_model.OAuth2, Type: auth_model.OAuth2,
Name: c.String("name"), Name: c.String("name"),
IsActive: true, IsActive: true,
@ -203,7 +203,7 @@ func runUpdateOauth(c *cli.Context) error {
return err return err
} }
source, err := auth_model.GetSourceByID(ctx, c.Int64("id")) source, err := auth_model.GetSourceByID(c.Int64("id"))
if err != nil { if err != nil {
return err return err
} }
@ -294,5 +294,5 @@ func runUpdateOauth(c *cli.Context) error {
oAuth2Config.CustomURLMapping = customURLMapping oAuth2Config.CustomURLMapping = customURLMapping
source.Cfg = oAuth2Config source.Cfg = oAuth2Config
return auth_model.UpdateSource(ctx, source) return auth_model.UpdateSource(source)
} }

View File

@ -156,7 +156,7 @@ func runAddSMTP(c *cli.Context) error {
smtpConfig.Auth = "PLAIN" smtpConfig.Auth = "PLAIN"
} }
return auth_model.CreateSource(ctx, &auth_model.Source{ return auth_model.CreateSource(&auth_model.Source{
Type: auth_model.SMTP, Type: auth_model.SMTP,
Name: c.String("name"), Name: c.String("name"),
IsActive: active, IsActive: active,
@ -176,7 +176,7 @@ func runUpdateSMTP(c *cli.Context) error {
return err return err
} }
source, err := auth_model.GetSourceByID(ctx, c.Int64("id")) source, err := auth_model.GetSourceByID(c.Int64("id"))
if err != nil { if err != nil {
return err return err
} }
@ -197,5 +197,5 @@ func runUpdateSMTP(c *cli.Context) error {
source.Cfg = smtpConfig source.Cfg = smtpConfig
return auth_model.UpdateSource(ctx, source) return auth_model.UpdateSource(source)
} }

View File

@ -7,7 +7,6 @@ package main
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
@ -19,11 +18,8 @@ import (
"github.com/google/go-github/v53/github" "github.com/google/go-github/v53/github"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gopkg.in/yaml.v3"
) )
const defaultVersion = "v1.18" // to backport to
func main() { func main() {
app := cli.NewApp() app := cli.NewApp()
app.Name = "backport" app.Name = "backport"
@ -54,16 +50,6 @@ func main() {
Name: "backport-branch", Name: "backport-branch",
Usage: "Backport branch to backport on to (default: backport-<pr>-<version>", Usage: "Backport branch to backport on to (default: backport-<pr>-<version>",
}, },
&cli.StringFlag{
Name: "remote",
Value: "",
Usage: "Remote for your fork of the Gitea upstream",
},
&cli.StringFlag{
Name: "fork-user",
Value: "",
Usage: "Forked user name on Github",
},
&cli.BoolFlag{ &cli.BoolFlag{
Name: "no-fetch", Name: "no-fetch",
Usage: "Set this flag to prevent fetch of remote branches", Usage: "Set this flag to prevent fetch of remote branches",
@ -72,18 +58,6 @@ func main() {
Name: "no-amend-message", Name: "no-amend-message",
Usage: "Set this flag to prevent automatic amendment of the commit message", Usage: "Set this flag to prevent automatic amendment of the commit message",
}, },
&cli.BoolFlag{
Name: "no-push",
Usage: "Set this flag to prevent pushing the backport up to your fork",
},
&cli.BoolFlag{
Name: "no-xdg-open",
Usage: "Set this flag to not use xdg-open to open the PR URL",
},
&cli.BoolFlag{
Name: "continue",
Usage: "Set this flag to continue from a git cherry-pick that has broken",
},
} }
cli.AppHelpTemplate = `NAME: cli.AppHelpTemplate = `NAME:
{{.Name}} - {{.Usage}} {{.Name}} - {{.Usage}}
@ -101,7 +75,7 @@ OPTIONS:
app.Action = runBackport app.Action = runBackport
if err := app.Run(os.Args); err != nil { if err := app.Run(os.Args); err != nil {
fmt.Fprintf(os.Stderr, "Unable to backport: %v\n", err) fmt.Fprintf(os.Stderr, "%v\n", err)
} }
} }
@ -109,24 +83,9 @@ func runBackport(c *cli.Context) error {
ctx, cancel := installSignals() ctx, cancel := installSignals()
defer cancel() defer cancel()
continuing := c.Bool("continue")
var pr string
version := c.String("version") version := c.String("version")
if version == "" && continuing {
// determine version from current branch name
var err error
pr, version, err = readCurrentBranch(ctx)
if err != nil {
return err
}
}
if version == "" { if version == "" {
version = readVersion() return fmt.Errorf("Provide a version to backport to")
}
if version == "" {
version = defaultVersion
} }
upstream := c.String("upstream") upstream := c.String("upstream")
@ -134,16 +93,6 @@ func runBackport(c *cli.Context) error {
upstream = "origin" upstream = "origin"
} }
forkUser := c.String("fork-user")
remote := c.String("remote")
if remote == "" && !c.Bool("--no-push") {
var err error
remote, forkUser, err = determineRemote(ctx, forkUser)
if err != nil {
return err
}
}
upstreamReleaseBranch := c.String("release-branch") upstreamReleaseBranch := c.String("release-branch")
if upstreamReleaseBranch == "" { if upstreamReleaseBranch == "" {
upstreamReleaseBranch = path.Join("release", version) upstreamReleaseBranch = path.Join("release", version)
@ -152,14 +101,12 @@ func runBackport(c *cli.Context) error {
localReleaseBranch := path.Join(upstream, upstreamReleaseBranch) localReleaseBranch := path.Join(upstream, upstreamReleaseBranch)
args := c.Args().Slice() args := c.Args().Slice()
if len(args) == 0 && pr == "" { if len(args) == 0 {
return fmt.Errorf("no PR number provided\nProvide a PR number to backport") return fmt.Errorf("Provide a PR number to backport")
} else if len(args) != 1 && pr == "" { } else if len(args) != 1 {
return fmt.Errorf("multiple PRs provided %v\nOnly a single PR can be backported at a time", args) return fmt.Errorf("Only a single PR can be backported at a time")
}
if pr == "" {
pr = args[0]
} }
pr := args[0]
backportBranch := c.String("backport-branch") backportBranch := c.String("backport-branch")
if backportBranch == "" { if backportBranch == "" {
@ -186,10 +133,8 @@ func runBackport(c *cli.Context) error {
} }
} }
if !continuing { if err := checkoutBackportBranch(ctx, backportBranch, localReleaseBranch); err != nil {
if err := checkoutBackportBranch(ctx, backportBranch, localReleaseBranch); err != nil { return err
return err
}
} }
if err := cherrypick(ctx, sha); err != nil { if err := cherrypick(ctx, sha); err != nil {
@ -202,41 +147,8 @@ func runBackport(c *cli.Context) error {
} }
} }
if !c.Bool("no-push") { fmt.Printf("Backport done! You can now push it with `git push <your remote> %s`\n", backportBranch)
url := "https://github.com/go-gitea/gitea/compare/" + upstreamReleaseBranch + "..." + forkUser + ":" + backportBranch
if err := gitPushUp(ctx, remote, backportBranch); err != nil {
return err
}
if !c.Bool("no-xdg-open") {
if err := xdgOpen(ctx, url); err != nil {
return err
}
} else {
fmt.Printf("* Navigate to %s to open PR\n", url)
}
}
return nil
}
func xdgOpen(ctx context.Context, url string) error {
fmt.Printf("* `xdg-open %s`\n", url)
out, err := exec.CommandContext(ctx, "xdg-open", url).Output()
if err != nil {
fmt.Fprintf(os.Stderr, "%s", string(out))
return fmt.Errorf("unable to xdg-open to %s: %w", url, err)
}
return nil
}
func gitPushUp(ctx context.Context, remote, backportBranch string) error {
fmt.Printf("* `git push -u %s %s`\n", remote, backportBranch)
out, err := exec.CommandContext(ctx, "git", "push", "-u", remote, backportBranch).Output()
if err != nil {
fmt.Fprintf(os.Stderr, "%s", string(out))
return fmt.Errorf("unable to push up to %s: %w", remote, err)
}
return nil return nil
} }
@ -267,18 +179,6 @@ func amendCommit(ctx context.Context, pr string) error {
} }
func cherrypick(ctx context.Context, sha string) error { func cherrypick(ctx context.Context, sha string) error {
// Check if a CHERRY_PICK_HEAD exists
if _, err := os.Stat(".git/CHERRY_PICK_HEAD"); err == nil {
// Assume that we are in the middle of cherry-pick - continue it
fmt.Println("* Attempting git cherry-pick --continue")
out, err := exec.CommandContext(ctx, "git", "cherry-pick", "--continue").Output()
if err != nil {
fmt.Fprintf(os.Stderr, "git cherry-pick --continue failed:\n%s\n", string(out))
return fmt.Errorf("unable to continue cherry-pick: %w", err)
}
return nil
}
fmt.Printf("* Attempting git cherry-pick %s\n", sha) fmt.Printf("* Attempting git cherry-pick %s\n", sha)
out, err := exec.CommandContext(ctx, "git", "cherry-pick", sha).Output() out, err := exec.CommandContext(ctx, "git", "cherry-pick", sha).Output()
if err != nil { if err != nil {
@ -289,22 +189,8 @@ func cherrypick(ctx context.Context, sha string) error {
} }
func checkoutBackportBranch(ctx context.Context, backportBranch, releaseBranch string) error { func checkoutBackportBranch(ctx context.Context, backportBranch, releaseBranch string) error {
out, err := exec.CommandContext(ctx, "git", "branch", "--show-current").Output() fmt.Printf("* `git branch -D %s`\n", backportBranch)
if err != nil { _ = exec.CommandContext(ctx, "git", "branch", "-D", backportBranch).Run()
return fmt.Errorf("unable to check current branch %w", err)
}
currentBranch := strings.TrimSpace(string(out))
fmt.Printf("* Current branch is %s\n", currentBranch)
if currentBranch == backportBranch {
fmt.Printf("* Current branch is %s - not checking out\n", currentBranch)
return nil
}
if _, err := exec.CommandContext(ctx, "git", "rev-list", "-1", backportBranch).Output(); err == nil {
fmt.Printf("* Branch %s already exists. Checking it out...\n", backportBranch)
return exec.CommandContext(ctx, "git", "checkout", "-f", backportBranch).Run()
}
fmt.Printf("* `git checkout -b %s %s`\n", backportBranch, releaseBranch) fmt.Printf("* `git checkout -b %s %s`\n", backportBranch, releaseBranch)
return exec.CommandContext(ctx, "git", "checkout", "-b", backportBranch, releaseBranch).Run() return exec.CommandContext(ctx, "git", "checkout", "-b", backportBranch, releaseBranch).Run()
@ -317,7 +203,6 @@ func fetchRemoteAndMain(ctx context.Context, remote, releaseBranch string) error
fmt.Println(string(out)) fmt.Println(string(out))
return fmt.Errorf("unable to fetch %s from %s: %w", "main", remote, err) return fmt.Errorf("unable to fetch %s from %s: %w", "main", remote, err)
} }
fmt.Println(string(out))
fmt.Printf("* `git fetch %s %s`\n", remote, releaseBranch) fmt.Printf("* `git fetch %s %s`\n", remote, releaseBranch)
out, err = exec.CommandContext(ctx, "git", "fetch", remote, releaseBranch).Output() out, err = exec.CommandContext(ctx, "git", "fetch", remote, releaseBranch).Output()
@ -325,108 +210,10 @@ func fetchRemoteAndMain(ctx context.Context, remote, releaseBranch string) error
fmt.Println(string(out)) fmt.Println(string(out))
return fmt.Errorf("unable to fetch %s from %s: %w", releaseBranch, remote, err) return fmt.Errorf("unable to fetch %s from %s: %w", releaseBranch, remote, err)
} }
fmt.Println(string(out))
return nil return nil
} }
func determineRemote(ctx context.Context, forkUser string) (string, string, error) {
out, err := exec.CommandContext(ctx, "git", "remote", "-v").Output()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to list git remotes:\n%s\n", string(out))
return "", "", fmt.Errorf("unable to determine forked remote: %w", err)
}
lines := strings.Split(string(out), "\n")
for _, line := range lines {
fields := strings.Split(line, "\t")
name, remote := fields[0], fields[1]
// only look at pushers
if !strings.HasSuffix(remote, " (push)") {
continue
}
// only look at github.com pushes
if !strings.Contains(remote, "github.com") {
continue
}
// ignore go-gitea/gitea
if strings.Contains(remote, "go-gitea/gitea") {
continue
}
if !strings.Contains(remote, forkUser) {
continue
}
if strings.HasPrefix(remote, "git@github.com:") {
forkUser = strings.TrimPrefix(remote, "git@github.com:")
} else if strings.HasPrefix(remote, "https://github.com/") {
forkUser = strings.TrimPrefix(remote, "https://github.com/")
} else if strings.HasPrefix(remote, "https://www.github.com/") {
forkUser = strings.TrimPrefix(remote, "https://www.github.com/")
} else if forkUser == "" {
return "", "", fmt.Errorf("unable to extract forkUser from remote %s: %s", name, remote)
}
idx := strings.Index(forkUser, "/")
if idx >= 0 {
forkUser = forkUser[:idx]
}
return name, forkUser, nil
}
return "", "", fmt.Errorf("unable to find appropriate remote in:\n%s", string(out))
}
func readCurrentBranch(ctx context.Context) (pr, version string, err error) {
out, err := exec.CommandContext(ctx, "git", "branch", "--show-current").Output()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to read current git branch:\n%s\n", string(out))
return "", "", fmt.Errorf("unable to read current git branch: %w", err)
}
parts := strings.Split(strings.TrimSpace(string(out)), "-")
if len(parts) != 3 || parts[0] != "backport" {
fmt.Fprintf(os.Stderr, "Unable to continue from git branch:\n%s\n", string(out))
return "", "", fmt.Errorf("unable to continue from git branch:\n%s", string(out))
}
return parts[1], parts[2], nil
}
func readVersion() string {
bs, err := os.ReadFile("docs/config.yaml")
if err != nil {
if err == os.ErrNotExist {
log.Println("`docs/config.yaml` not present")
return ""
}
fmt.Fprintf(os.Stderr, "Unable to read `docs/config.yaml`: %v\n", err)
return ""
}
type params struct {
Version string
}
type docConfig struct {
Params params
}
dc := &docConfig{}
if err := yaml.Unmarshal(bs, dc); err != nil {
fmt.Fprintf(os.Stderr, "Unable to read `docs/config.yaml`: %v\n", err)
return ""
}
if dc.Params.Version == "" {
fmt.Fprintf(os.Stderr, "No version in `docs/config.yaml`")
return ""
}
version := dc.Params.Version
if version[0] != 'v' {
version = "v" + version
}
split := strings.SplitN(version, ".", 3)
return strings.Join(split[:2], ".")
}
func determineSHAforPR(ctx context.Context, prStr string) (string, error) { func determineSHAforPR(ctx context.Context, prStr string) (string, error) {
prNum, err := strconv.Atoi(prStr) prNum, err := strconv.Atoi(prStr)
if err != nil { if err != nil {

View File

@ -23,7 +23,7 @@ If you don't want your repository to be visible for search engines read further.
## Block search engines indexation using robots.txt ## Block search engines indexation using robots.txt
To make Gitea serve a custom `robots.txt` (default: empty 404) for top level installations, To make Gitea serve a custom `robots.txt` (default: empty 404) for top level installations,
create a file with path `public/robots.txt` in the [`custom` folder or `CustomPath`](administration/customizing-gitea.md) create a file called `robots.txt` in the [`custom` folder or `CustomPath`](administration/customizing-gitea.md)
Examples on how to configure the `robots.txt` can be found at [https://moz.com/learn/seo/robotstxt](https://moz.com/learn/seo/robotstxt). Examples on how to configure the `robots.txt` can be found at [https://moz.com/learn/seo/robotstxt](https://moz.com/learn/seo/robotstxt).

View File

@ -22,7 +22,7 @@ menu:
## 使用 robots.txt 阻止搜索引擎索引 ## 使用 robots.txt 阻止搜索引擎索引
为了使 Gitea 为顶级安装提供自定义的`robots.txt`(默认为空的 404请在 [`custom`文件夹或`CustomPath`]administration/customizing-gitea.md中创建一个名为 `public/robots.txt` 的文件。 为了使 Gitea 为顶级安装提供自定义的`robots.txt`(默认为空的 404请在[`custom`文件夹或`CustomPath`]administration/customizing-gitea.md中创建一个名为 `robots.txt` 的文件。
有关如何配置 `robots.txt` 的示例,请参考 [https://moz.com/learn/seo/robotstxt](https://moz.com/learn/seo/robotstxt)。 有关如何配置 `robots.txt` 的示例,请参考 [https://moz.com/learn/seo/robotstxt](https://moz.com/learn/seo/robotstxt)。

View File

@ -42,7 +42,7 @@ func (jobs ActionJobList) LoadRuns(ctx context.Context, withRepo bool) error {
for _, r := range runs { for _, r := range runs {
runsList = append(runsList, r) runsList = append(runsList, r)
} }
return runsList.LoadRepos(ctx) return runsList.LoadRepos()
} }
return nil return nil
} }

View File

@ -52,9 +52,9 @@ func (runs RunList) LoadTriggerUser(ctx context.Context) error {
return nil return nil
} }
func (runs RunList) LoadRepos(ctx context.Context) error { func (runs RunList) LoadRepos() error {
repoIDs := runs.GetRepoIDs() repoIDs := runs.GetRepoIDs()
repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs) repos, err := repo_model.GetRepositoriesMapByIDs(repoIDs)
if err != nil { if err != nil {
return err return err
} }

View File

@ -49,9 +49,9 @@ func (schedules ScheduleList) LoadTriggerUser(ctx context.Context) error {
return nil return nil
} }
func (schedules ScheduleList) LoadRepos(ctx context.Context) error { func (schedules ScheduleList) LoadRepos() error {
repoIDs := schedules.GetRepoIDs() repoIDs := schedules.GetRepoIDs()
repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs) repos, err := repo_model.GetRepositoriesMapByIDs(repoIDs)
if err != nil { if err != nil {
return err return err
} }

View File

@ -53,9 +53,9 @@ func (specs SpecList) GetRepoIDs() []int64 {
return ids.Values() return ids.Values()
} }
func (specs SpecList) LoadRepos(ctx context.Context) error { func (specs SpecList) LoadRepos() error {
repoIDs := specs.GetRepoIDs() repoIDs := specs.GetRepoIDs()
repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs) repos, err := repo_model.GetRepositoriesMapByIDs(repoIDs)
if err != nil { if err != nil {
return err return err
} }

View File

@ -102,7 +102,7 @@ func GetStatistic(ctx context.Context) (stats Statistic) {
stats.Counter.Follow, _ = e.Count(new(user_model.Follow)) stats.Counter.Follow, _ = e.Count(new(user_model.Follow))
stats.Counter.Mirror, _ = e.Count(new(repo_model.Mirror)) stats.Counter.Mirror, _ = e.Count(new(repo_model.Mirror))
stats.Counter.Release, _ = e.Count(new(repo_model.Release)) stats.Counter.Release, _ = e.Count(new(repo_model.Release))
stats.Counter.AuthSource = auth.CountSources(ctx) stats.Counter.AuthSource = auth.CountSources()
stats.Counter.Webhook, _ = e.Count(new(webhook.Webhook)) stats.Counter.Webhook, _ = e.Count(new(webhook.Webhook))
stats.Counter.Milestone, _ = e.Count(new(issues_model.Milestone)) stats.Counter.Milestone, _ = e.Count(new(issues_model.Milestone))
stats.Counter.Label, _ = e.Count(new(issues_model.Label)) stats.Counter.Label, _ = e.Count(new(issues_model.Label))

View File

@ -91,7 +91,7 @@ func addKey(ctx context.Context, 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(ctx context.Context, ownerID int64, name, content string, authSourceID int64) (*PublicKey, error) { func AddPublicKey(ownerID int64, name, content string, authSourceID int64) (*PublicKey, error) {
log.Trace(content) log.Trace(content)
fingerprint, err := CalcFingerprint(content) fingerprint, err := CalcFingerprint(content)
@ -99,7 +99,7 @@ func AddPublicKey(ctx context.Context, ownerID int64, name, content string, auth
return nil, err return nil, err
} }
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -136,9 +136,9 @@ func AddPublicKey(ctx context.Context, ownerID int64, name, content string, auth
} }
// GetPublicKeyByID returns public key by given ID. // GetPublicKeyByID returns public key by given ID.
func GetPublicKeyByID(ctx context.Context, keyID int64) (*PublicKey, error) { func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
key := new(PublicKey) key := new(PublicKey)
has, err := db.GetEngine(ctx). has, err := db.GetEngine(db.DefaultContext).
ID(keyID). ID(keyID).
Get(key) Get(key)
if err != nil { if err != nil {
@ -180,7 +180,7 @@ func SearchPublicKeyByContentExact(ctx context.Context, content string) (*Public
} }
// SearchPublicKey returns a list of public keys matching the provided arguments. // SearchPublicKey returns a list of public keys matching the provided arguments.
func SearchPublicKey(ctx context.Context, uid int64, fingerprint string) ([]*PublicKey, error) { func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 5) keys := make([]*PublicKey, 0, 5)
cond := builder.NewCond() cond := builder.NewCond()
if uid != 0 { if uid != 0 {
@ -189,12 +189,12 @@ func SearchPublicKey(ctx context.Context, uid int64, fingerprint string) ([]*Pub
if fingerprint != "" { if fingerprint != "" {
cond = cond.And(builder.Eq{"fingerprint": fingerprint}) cond = cond.And(builder.Eq{"fingerprint": fingerprint})
} }
return keys, db.GetEngine(ctx).Where(cond).Find(&keys) return keys, db.GetEngine(db.DefaultContext).Where(cond).Find(&keys)
} }
// ListPublicKeys returns a list of public keys belongs to given user. // ListPublicKeys returns a list of public keys belongs to given user.
func ListPublicKeys(ctx context.Context, uid int64, listOptions db.ListOptions) ([]*PublicKey, error) { func ListPublicKeys(uid int64, listOptions db.ListOptions) ([]*PublicKey, error) {
sess := db.GetEngine(ctx).Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal) sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", uid, KeyTypePrincipal)
if listOptions.Page != 0 { if listOptions.Page != 0 {
sess = db.SetSessionPagination(sess, &listOptions) sess = db.SetSessionPagination(sess, &listOptions)
@ -207,30 +207,30 @@ func ListPublicKeys(ctx context.Context, uid int64, listOptions db.ListOptions)
} }
// CountPublicKeys count public keys a user has // CountPublicKeys count public keys a user has
func CountPublicKeys(ctx context.Context, userID int64) (int64, error) { func CountPublicKeys(userID int64) (int64, error) {
sess := db.GetEngine(ctx).Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal) sess := db.GetEngine(db.DefaultContext).Where("owner_id = ? AND type != ?", userID, KeyTypePrincipal)
return sess.Count(&PublicKey{}) return sess.Count(&PublicKey{})
} }
// ListPublicKeysBySource returns a list of synchronized public keys for a given user and login source. // ListPublicKeysBySource returns a list of synchronized public keys for a given user and login source.
func ListPublicKeysBySource(ctx context.Context, uid, authSourceID int64) ([]*PublicKey, error) { func ListPublicKeysBySource(uid, authSourceID int64) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 5) keys := make([]*PublicKey, 0, 5)
return keys, db.GetEngine(ctx). return keys, db.GetEngine(db.DefaultContext).
Where("owner_id = ? AND login_source_id = ?", uid, authSourceID). Where("owner_id = ? AND login_source_id = ?", uid, authSourceID).
Find(&keys) Find(&keys)
} }
// UpdatePublicKeyUpdated updates public key use time. // UpdatePublicKeyUpdated updates public key use time.
func UpdatePublicKeyUpdated(ctx context.Context, id int64) error { func UpdatePublicKeyUpdated(id int64) error {
// Check if key exists before update as affected rows count is unreliable // Check if key exists before update as affected rows count is unreliable
// and will return 0 affected rows if two updates are made at the same time // and will return 0 affected rows if two updates are made at the same time
if cnt, err := db.GetEngine(ctx).ID(id).Count(&PublicKey{}); err != nil { if cnt, err := db.GetEngine(db.DefaultContext).ID(id).Count(&PublicKey{}); err != nil {
return err return err
} else if cnt != 1 { } else if cnt != 1 {
return ErrKeyNotExist{id} return ErrKeyNotExist{id}
} }
_, err := db.GetEngine(ctx).ID(id).Cols("updated_unix").Update(&PublicKey{ _, err := db.GetEngine(db.DefaultContext).ID(id).Cols("updated_unix").Update(&PublicKey{
UpdatedUnix: timeutil.TimeStampNow(), UpdatedUnix: timeutil.TimeStampNow(),
}) })
if err != nil { if err != nil {
@ -250,7 +250,7 @@ func DeletePublicKeys(ctx context.Context, keyIDs ...int64) error {
} }
// PublicKeysAreExternallyManaged returns whether the provided KeyID represents an externally managed Key // PublicKeysAreExternallyManaged returns whether the provided KeyID represents an externally managed Key
func PublicKeysAreExternallyManaged(ctx context.Context, keys []*PublicKey) ([]bool, error) { func PublicKeysAreExternallyManaged(keys []*PublicKey) ([]bool, error) {
sources := make([]*auth.Source, 0, 5) sources := make([]*auth.Source, 0, 5)
externals := make([]bool, len(keys)) externals := make([]bool, len(keys))
keyloop: keyloop:
@ -272,7 +272,7 @@ keyloop:
if source == nil { if source == nil {
var err error var err error
source, err = auth.GetSourceByID(ctx, key.LoginSourceID) source, err = auth.GetSourceByID(key.LoginSourceID)
if err != nil { if err != nil {
if auth.IsErrSourceNotExist(err) { if auth.IsErrSourceNotExist(err) {
externals[i] = false externals[i] = false
@ -295,15 +295,15 @@ keyloop:
} }
// PublicKeyIsExternallyManaged returns whether the provided KeyID represents an externally managed Key // PublicKeyIsExternallyManaged returns whether the provided KeyID represents an externally managed Key
func PublicKeyIsExternallyManaged(ctx context.Context, id int64) (bool, error) { func PublicKeyIsExternallyManaged(id int64) (bool, error) {
key, err := GetPublicKeyByID(ctx, id) key, err := GetPublicKeyByID(id)
if err != nil { if err != nil {
return false, err return false, err
} }
if key.LoginSourceID == 0 { if key.LoginSourceID == 0 {
return false, nil return false, nil
} }
source, err := auth.GetSourceByID(ctx, key.LoginSourceID) source, err := auth.GetSourceByID(key.LoginSourceID)
if err != nil { if err != nil {
if auth.IsErrSourceNotExist(err) { if auth.IsErrSourceNotExist(err) {
return false, nil return false, nil
@ -318,9 +318,9 @@ func PublicKeyIsExternallyManaged(ctx context.Context, id int64) (bool, error) {
} }
// deleteKeysMarkedForDeletion returns true if ssh keys needs update // deleteKeysMarkedForDeletion returns true if ssh keys needs update
func deleteKeysMarkedForDeletion(ctx context.Context, keys []string) (bool, error) { func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
// Start session // Start session
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -349,7 +349,7 @@ func deleteKeysMarkedForDeletion(ctx context.Context, keys []string) (bool, erro
} }
// AddPublicKeysBySource add a users public keys. Returns true if there are changes. // AddPublicKeysBySource add a users public keys. Returns true if there are changes.
func AddPublicKeysBySource(ctx context.Context, usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool { func AddPublicKeysBySource(usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool {
var sshKeysNeedUpdate bool var sshKeysNeedUpdate bool
for _, sshKey := range sshPublicKeys { for _, sshKey := range sshPublicKeys {
var err error var err error
@ -368,7 +368,7 @@ func AddPublicKeysBySource(ctx context.Context, usr *user_model.User, s *auth.So
marshalled = marshalled[:len(marshalled)-1] marshalled = marshalled[:len(marshalled)-1]
sshKeyName := fmt.Sprintf("%s-%s", s.Name, ssh.FingerprintSHA256(out)) sshKeyName := fmt.Sprintf("%s-%s", s.Name, ssh.FingerprintSHA256(out))
if _, err := AddPublicKey(ctx, usr.ID, sshKeyName, marshalled, s.ID); err != nil { if _, err := AddPublicKey(usr.ID, sshKeyName, marshalled, s.ID); err != nil {
if IsErrKeyAlreadyExist(err) { if IsErrKeyAlreadyExist(err) {
log.Trace("AddPublicKeysBySource[%s]: Public SSH Key %s already exists for user", sshKeyName, usr.Name) log.Trace("AddPublicKeysBySource[%s]: Public SSH Key %s already exists for user", sshKeyName, usr.Name)
} else { } else {
@ -387,14 +387,14 @@ func AddPublicKeysBySource(ctx context.Context, usr *user_model.User, s *auth.So
} }
// SynchronizePublicKeys updates a users public keys. Returns true if there are changes. // SynchronizePublicKeys updates a users public keys. Returns true if there are changes.
func SynchronizePublicKeys(ctx context.Context, usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool { func SynchronizePublicKeys(usr *user_model.User, s *auth.Source, sshPublicKeys []string) bool {
var sshKeysNeedUpdate bool var sshKeysNeedUpdate bool
log.Trace("synchronizePublicKeys[%s]: Handling Public SSH Key synchronization for user %s", s.Name, usr.Name) log.Trace("synchronizePublicKeys[%s]: Handling Public SSH Key synchronization for user %s", s.Name, usr.Name)
// Get Public Keys from DB with current LDAP source // Get Public Keys from DB with current LDAP source
var giteaKeys []string var giteaKeys []string
keys, err := ListPublicKeysBySource(ctx, usr.ID, s.ID) keys, err := ListPublicKeysBySource(usr.ID, s.ID)
if err != nil { if err != nil {
log.Error("synchronizePublicKeys[%s]: Error listing Public SSH Keys for user %s: %v", s.Name, usr.Name, err) log.Error("synchronizePublicKeys[%s]: Error listing Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
} }
@ -429,7 +429,7 @@ func SynchronizePublicKeys(ctx context.Context, usr *user_model.User, s *auth.So
newKeys = append(newKeys, key) newKeys = append(newKeys, key)
} }
} }
if AddPublicKeysBySource(ctx, usr, s, newKeys) { if AddPublicKeysBySource(usr, s, newKeys) {
sshKeysNeedUpdate = true sshKeysNeedUpdate = true
} }
@ -443,7 +443,7 @@ func SynchronizePublicKeys(ctx context.Context, usr *user_model.User, s *auth.So
} }
// Delete keys from DB that no longer exist in the source // Delete keys from DB that no longer exist in the source
needUpd, err := deleteKeysMarkedForDeletion(ctx, giteaKeysToDelete) needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
if err != nil { if err != nil {
log.Error("synchronizePublicKeys[%s]: Error deleting Public Keys marked for deletion for user %s: %v", s.Name, usr.Name, err) log.Error("synchronizePublicKeys[%s]: Error deleting Public Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
} }

View File

@ -21,7 +21,7 @@ import (
func ParseCommitWithSSHSignature(ctx context.Context, c *git.Commit, committer *user_model.User) *CommitVerification { func ParseCommitWithSSHSignature(ctx context.Context, c *git.Commit, committer *user_model.User) *CommitVerification {
// Now try to associate the signature with the committer, if present // Now try to associate the signature with the committer, if present
if committer.ID != 0 { if committer.ID != 0 {
keys, err := ListPublicKeys(ctx, committer.ID, db.ListOptions{}) keys, err := ListPublicKeys(committer.ID, db.ListOptions{})
if err != nil { // Skipping failed to get ssh keys of user if err != nil { // Skipping failed to get ssh keys of user
log.Error("ListPublicKeys: %v", err) log.Error("ListPublicKeys: %v", err)
return &CommitVerification{ return &CommitVerification{

View File

@ -48,8 +48,8 @@ func (key *DeployKey) AfterLoad() {
} }
// GetContent gets associated public key content. // GetContent gets associated public key content.
func (key *DeployKey) GetContent(ctx context.Context) error { func (key *DeployKey) GetContent() error {
pkey, err := GetPublicKeyByID(ctx, key.KeyID) pkey, err := GetPublicKeyByID(key.KeyID)
if err != nil { if err != nil {
return err return err
} }

View File

@ -51,7 +51,7 @@ func Test_SSHParsePublicKey(t *testing.T) {
if err != nil { if err != nil {
// Some servers do not support ecdsa format. // Some servers do not support ecdsa format.
if !strings.Contains(err.Error(), "line 1 too long:") { if !strings.Contains(err.Error(), "line 1 too long:") {
assert.FailNow(t, "%v", err) assert.Fail(t, "%v", err)
} }
} }
assert.Equal(t, tc.keyType, keyTypeK) assert.Equal(t, tc.keyType, keyTypeK)
@ -60,7 +60,7 @@ func Test_SSHParsePublicKey(t *testing.T) {
t.Run("SSHParseKeyNative", func(t *testing.T) { t.Run("SSHParseKeyNative", func(t *testing.T) {
keyTypeK, lengthK, err := SSHNativeParsePublicKey(tc.content) keyTypeK, lengthK, err := SSHNativeParsePublicKey(tc.content)
if err != nil { if err != nil {
assert.FailNow(t, "%v", err) assert.Fail(t, "%v", err)
} }
assert.Equal(t, tc.keyType, keyTypeK) assert.Equal(t, tc.keyType, keyTypeK)
assert.EqualValues(t, tc.length, lengthK) assert.EqualValues(t, tc.length, lengthK)

View File

@ -5,7 +5,6 @@
package auth package auth
import ( import (
"context"
"fmt" "fmt"
"reflect" "reflect"
@ -200,8 +199,8 @@ func (source *Source) SkipVerify() bool {
// CreateSource inserts a AuthSource in the DB if not already // CreateSource inserts a AuthSource in the DB if not already
// existing with the given name. // existing with the given name.
func CreateSource(ctx context.Context, source *Source) error { func CreateSource(source *Source) error {
has, err := db.GetEngine(ctx).Where("name=?", source.Name).Exist(new(Source)) has, err := db.GetEngine(db.DefaultContext).Where("name=?", source.Name).Exist(new(Source))
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
@ -212,7 +211,7 @@ func CreateSource(ctx context.Context, source *Source) error {
source.IsSyncEnabled = false source.IsSyncEnabled = false
} }
_, err = db.GetEngine(ctx).Insert(source) _, err = db.GetEngine(db.DefaultContext).Insert(source)
if err != nil { if err != nil {
return err return err
} }
@ -233,7 +232,7 @@ func CreateSource(ctx context.Context, source *Source) error {
err = registerableSource.RegisterSource() err = registerableSource.RegisterSource()
if err != nil { if err != nil {
// remove the AuthSource in case of errors while registering configuration // remove the AuthSource in case of errors while registering configuration
if _, err := db.GetEngine(ctx).Delete(source); err != nil { if _, err := db.GetEngine(db.DefaultContext).Delete(source); err != nil {
log.Error("CreateSource: Error while wrapOpenIDConnectInitializeError: %v", err) log.Error("CreateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
} }
} }
@ -241,33 +240,33 @@ func CreateSource(ctx context.Context, source *Source) error {
} }
// Sources returns a slice of all login sources found in DB. // Sources returns a slice of all login sources found in DB.
func Sources(ctx context.Context) ([]*Source, error) { func Sources() ([]*Source, error) {
auths := make([]*Source, 0, 6) auths := make([]*Source, 0, 6)
return auths, db.GetEngine(ctx).Find(&auths) return auths, db.GetEngine(db.DefaultContext).Find(&auths)
} }
// SourcesByType returns all sources of the specified type // SourcesByType returns all sources of the specified type
func SourcesByType(ctx context.Context, loginType Type) ([]*Source, error) { func SourcesByType(loginType Type) ([]*Source, error) {
sources := make([]*Source, 0, 1) sources := make([]*Source, 0, 1)
if err := db.GetEngine(ctx).Where("type = ?", loginType).Find(&sources); err != nil { if err := db.GetEngine(db.DefaultContext).Where("type = ?", loginType).Find(&sources); err != nil {
return nil, err return nil, err
} }
return sources, nil return sources, nil
} }
// AllActiveSources returns all active sources // AllActiveSources returns all active sources
func AllActiveSources(ctx context.Context) ([]*Source, error) { func AllActiveSources() ([]*Source, error) {
sources := make([]*Source, 0, 5) sources := make([]*Source, 0, 5)
if err := db.GetEngine(ctx).Where("is_active = ?", true).Find(&sources); err != nil { if err := db.GetEngine(db.DefaultContext).Where("is_active = ?", true).Find(&sources); err != nil {
return nil, err return nil, err
} }
return sources, nil return sources, nil
} }
// ActiveSources returns all active sources of the specified type // ActiveSources returns all active sources of the specified type
func ActiveSources(ctx context.Context, tp Type) ([]*Source, error) { func ActiveSources(tp Type) ([]*Source, error) {
sources := make([]*Source, 0, 1) sources := make([]*Source, 0, 1)
if err := db.GetEngine(ctx).Where("is_active = ? and type = ?", true, tp).Find(&sources); err != nil { if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, tp).Find(&sources); err != nil {
return nil, err return nil, err
} }
return sources, nil return sources, nil
@ -275,11 +274,11 @@ func ActiveSources(ctx context.Context, tp Type) ([]*Source, error) {
// IsSSPIEnabled returns true if there is at least one activated login // IsSSPIEnabled returns true if there is at least one activated login
// source of type LoginSSPI // source of type LoginSSPI
func IsSSPIEnabled(ctx context.Context) bool { func IsSSPIEnabled() bool {
if !db.HasEngine { if !db.HasEngine {
return false return false
} }
sources, err := ActiveSources(ctx, SSPI) sources, err := ActiveSources(SSPI)
if err != nil { if err != nil {
log.Error("ActiveSources: %v", err) log.Error("ActiveSources: %v", err)
return false return false
@ -288,7 +287,7 @@ func IsSSPIEnabled(ctx context.Context) bool {
} }
// GetSourceByID returns login source by given ID. // GetSourceByID returns login source by given ID.
func GetSourceByID(ctx context.Context, id int64) (*Source, error) { func GetSourceByID(id int64) (*Source, error) {
source := new(Source) source := new(Source)
if id == 0 { if id == 0 {
source.Cfg = registeredConfigs[NoType]() source.Cfg = registeredConfigs[NoType]()
@ -298,7 +297,7 @@ func GetSourceByID(ctx context.Context, id int64) (*Source, error) {
return source, nil return source, nil
} }
has, err := db.GetEngine(ctx).ID(id).Get(source) has, err := db.GetEngine(db.DefaultContext).ID(id).Get(source)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -308,24 +307,24 @@ func GetSourceByID(ctx context.Context, id int64) (*Source, error) {
} }
// UpdateSource updates a Source record in DB. // UpdateSource updates a Source record in DB.
func UpdateSource(ctx context.Context, source *Source) error { func UpdateSource(source *Source) error {
var originalSource *Source var originalSource *Source
if source.IsOAuth2() { if source.IsOAuth2() {
// keep track of the original values so we can restore in case of errors while registering OAuth2 providers // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
var err error var err error
if originalSource, err = GetSourceByID(ctx, source.ID); err != nil { if originalSource, err = GetSourceByID(source.ID); err != nil {
return err return err
} }
} }
has, err := db.GetEngine(ctx).Where("name=? AND id!=?", source.Name, source.ID).Exist(new(Source)) has, err := db.GetEngine(db.DefaultContext).Where("name=? AND id!=?", source.Name, source.ID).Exist(new(Source))
if err != nil { if err != nil {
return err return err
} else if has { } else if has {
return ErrSourceAlreadyExist{source.Name} return ErrSourceAlreadyExist{source.Name}
} }
_, err = db.GetEngine(ctx).ID(source.ID).AllCols().Update(source) _, err = db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(source)
if err != nil { if err != nil {
return err return err
} }
@ -346,7 +345,7 @@ func UpdateSource(ctx context.Context, source *Source) error {
err = registerableSource.RegisterSource() err = registerableSource.RegisterSource()
if err != nil { if err != nil {
// restore original values since we cannot update the provider it self // restore original values since we cannot update the provider it self
if _, err := db.GetEngine(ctx).ID(source.ID).AllCols().Update(originalSource); err != nil { if _, err := db.GetEngine(db.DefaultContext).ID(source.ID).AllCols().Update(originalSource); err != nil {
log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err) log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
} }
} }
@ -354,8 +353,8 @@ func UpdateSource(ctx context.Context, source *Source) error {
} }
// CountSources returns number of login sources. // CountSources returns number of login sources.
func CountSources(ctx context.Context) int64 { func CountSources() int64 {
count, _ := db.GetEngine(ctx).Count(new(Source)) count, _ := db.GetEngine(db.DefaultContext).Count(new(Source))
return count return count
} }

View File

@ -42,7 +42,7 @@ func TestDumpAuthSource(t *testing.T) {
auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource)) auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource))
auth_model.CreateSource(db.DefaultContext, &auth_model.Source{ auth_model.CreateSource(&auth_model.Source{
Type: auth_model.OAuth2, Type: auth_model.OAuth2,
Name: "TestSource", Name: "TestSource",
IsActive: false, IsActive: false,

View File

@ -111,7 +111,7 @@ func findCodeComments(ctx context.Context, opts FindCommentsOptions, issue *Issu
if comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{ if comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
Ctx: ctx, Ctx: ctx,
URLPrefix: issue.Repo.Link(), URLPrefix: issue.Repo.Link(),
Metas: issue.Repo.ComposeMetas(ctx), Metas: issue.Repo.ComposeMetas(),
}, comment.Content); err != nil { }, comment.Content); err != nil {
return nil, err return nil, err
} }

View File

@ -127,8 +127,8 @@ const (
) )
// CreateIssueDependency creates a new dependency for an issue // CreateIssueDependency creates a new dependency for an issue
func CreateIssueDependency(ctx context.Context, user *user_model.User, issue, dep *Issue) error { func CreateIssueDependency(user *user_model.User, issue, dep *Issue) error {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -168,8 +168,8 @@ func CreateIssueDependency(ctx context.Context, user *user_model.User, issue, de
} }
// RemoveIssueDependency removes a dependency from an issue // RemoveIssueDependency removes a dependency from an issue
func RemoveIssueDependency(ctx context.Context, user *user_model.User, issue, dep *Issue, depType DependencyType) (err error) { func RemoveIssueDependency(user *user_model.User, issue, dep *Issue, depType DependencyType) (err error) {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }

View File

@ -28,16 +28,16 @@ func TestCreateIssueDependency(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
// Create a dependency and check if it was successful // Create a dependency and check if it was successful
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2) err = issues_model.CreateIssueDependency(user1, issue1, issue2)
assert.NoError(t, err) assert.NoError(t, err)
// Do it again to see if it will check if the dependency already exists // Do it again to see if it will check if the dependency already exists
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2) err = issues_model.CreateIssueDependency(user1, issue1, issue2)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, issues_model.IsErrDependencyExists(err)) assert.True(t, issues_model.IsErrDependencyExists(err))
// Check for circular dependencies // Check for circular dependencies
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue2, issue1) err = issues_model.CreateIssueDependency(user1, issue2, issue1)
assert.Error(t, err) assert.Error(t, err)
assert.True(t, issues_model.IsErrCircularDependency(err)) assert.True(t, issues_model.IsErrCircularDependency(err))
@ -57,6 +57,6 @@ func TestCreateIssueDependency(t *testing.T) {
assert.True(t, left) assert.True(t, left)
// Test removing the dependency // Test removing the dependency
err = issues_model.RemoveIssueDependency(db.DefaultContext, user1, issue1, issue2, issues_model.DependencyTypeBlockedBy) err = issues_model.RemoveIssueDependency(user1, issue1, issue2, issues_model.DependencyTypeBlockedBy)
assert.NoError(t, err) assert.NoError(t, err)
} }

View File

@ -83,12 +83,12 @@ func RemoveDuplicateExclusiveIssueLabels(ctx context.Context, issue *Issue, labe
} }
// NewIssueLabel creates a new issue-label relation. // NewIssueLabel creates a new issue-label relation.
func NewIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) (err error) { func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error) {
if HasIssueLabel(ctx, issue.ID, label.ID) { if HasIssueLabel(db.DefaultContext, issue.ID, label.ID) {
return nil return nil
} }
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -149,8 +149,8 @@ func newIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *us
} }
// NewIssueLabels creates a list of issue-label relations. // NewIssueLabels creates a list of issue-label relations.
func NewIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) { func NewIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err error) {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -359,8 +359,8 @@ func clearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User)
// ClearIssueLabels removes all issue labels as the given user. // ClearIssueLabels removes all issue labels as the given user.
// Triggers appropriate WebHooks, if any. // Triggers appropriate WebHooks, if any.
func ClearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User) (err error) { func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -432,8 +432,8 @@ func RemoveDuplicateExclusiveLabels(labels []*Label) []*Label {
// ReplaceIssueLabels removes all current labels and add new labels to the issue. // ReplaceIssueLabels removes all current labels and add new labels to the issue.
// Triggers appropriate WebHooks, if any. // Triggers appropriate WebHooks, if any.
func ReplaceIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) { func ReplaceIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err error) {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }

View File

@ -6,7 +6,6 @@ package issues_test
import ( import (
"testing" "testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
@ -22,7 +21,7 @@ func TestNewIssueLabelsScope(t *testing.T) {
label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8}) label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer)) assert.NoError(t, issues_model.NewIssueLabels(issue, []*issues_model.Label{label1, label2}, doer))
assert.Len(t, issue.Labels, 1) assert.Len(t, issue.Labels, 1)
assert.Equal(t, label2.ID, issue.Labels[0].ID) assert.Equal(t, label2.ID, issue.Labels[0].ID)

View File

@ -4,8 +4,6 @@
package issues package issues
import ( import (
"context"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
) )
@ -19,16 +17,16 @@ type IssueLockOptions struct {
// LockIssue locks an issue. This would limit commenting abilities to // LockIssue locks an issue. This would limit commenting abilities to
// users with write access to the repo // users with write access to the repo
func LockIssue(ctx context.Context, opts *IssueLockOptions) error { func LockIssue(opts *IssueLockOptions) error {
return updateIssueLock(ctx, opts, true) return updateIssueLock(opts, true)
} }
// UnlockIssue unlocks a previously locked issue. // UnlockIssue unlocks a previously locked issue.
func UnlockIssue(ctx context.Context, opts *IssueLockOptions) error { func UnlockIssue(opts *IssueLockOptions) error {
return updateIssueLock(ctx, opts, false) return updateIssueLock(opts, false)
} }
func updateIssueLock(ctx context.Context, opts *IssueLockOptions, lock bool) error { func updateIssueLock(opts *IssueLockOptions, lock bool) error {
if opts.Issue.IsLocked == lock { if opts.Issue.IsLocked == lock {
return nil return nil
} }
@ -41,7 +39,7 @@ func updateIssueLock(ctx context.Context, opts *IssueLockOptions, lock bool) err
commentType = CommentTypeUnlock commentType = CommentTypeUnlock
} }
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }

View File

@ -38,7 +38,11 @@ func (issue *Issue) projectID(ctx context.Context) int64 {
} }
// ProjectBoardID return project board id if issue was assigned to one // ProjectBoardID return project board id if issue was assigned to one
func (issue *Issue) ProjectBoardID(ctx context.Context) int64 { func (issue *Issue) ProjectBoardID() int64 {
return issue.projectBoardID(db.DefaultContext)
}
func (issue *Issue) projectBoardID(ctx context.Context) int64 {
var ip project_model.ProjectIssue var ip project_model.ProjectIssue
has, err := db.GetEngine(ctx).Where("issue_id=?", issue.ID).Get(&ip) has, err := db.GetEngine(ctx).Where("issue_id=?", issue.ID).Get(&ip)
if err != nil || !has { if err != nil || !has {
@ -96,8 +100,8 @@ func LoadIssuesFromBoardList(ctx context.Context, bs project_model.BoardList) (m
} }
// ChangeProjectAssign changes the project associated with an issue // ChangeProjectAssign changes the project associated with an issue
func ChangeProjectAssign(ctx context.Context, issue *Issue, doer *user_model.User, newProjectID int64) error { func ChangeProjectAssign(issue *Issue, doer *user_model.User, newProjectID int64) error {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -152,8 +156,8 @@ func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.U
} }
// MoveIssueAcrossProjectBoards move a card from one board to another // MoveIssueAcrossProjectBoards move a card from one board to another
func MoveIssueAcrossProjectBoards(ctx context.Context, issue *Issue, board *project_model.Board) error { func MoveIssueAcrossProjectBoards(issue *Issue, board *project_model.Board) error {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }

View File

@ -444,9 +444,9 @@ func applySubscribedCondition(sess *xorm.Session, subscriberID int64) *xorm.Sess
} }
// GetRepoIDsForIssuesOptions find all repo ids for the given options // GetRepoIDsForIssuesOptions find all repo ids for the given options
func GetRepoIDsForIssuesOptions(ctx context.Context, opts *IssuesOptions, user *user_model.User) ([]int64, error) { func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *user_model.User) ([]int64, error) {
repoIDs := make([]int64, 0, 5) repoIDs := make([]int64, 0, 5)
e := db.GetEngine(ctx) e := db.GetEngine(db.DefaultContext)
sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")

View File

@ -34,7 +34,7 @@ func TestIssue_ReplaceLabels(t *testing.T) {
for i, labelID := range labelIDs { for i, labelID := range labelIDs {
labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID, RepoID: repo.ID}) labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID, RepoID: repo.ID})
} }
assert.NoError(t, issues_model.ReplaceIssueLabels(db.DefaultContext, issue, labels, doer)) assert.NoError(t, issues_model.ReplaceIssueLabels(issue, labels, doer))
unittest.AssertCount(t, &issues_model.IssueLabel{IssueID: issueID}, len(expectedLabelIDs)) unittest.AssertCount(t, &issues_model.IssueLabel{IssueID: issueID}, len(expectedLabelIDs))
for _, labelID := range expectedLabelIDs { for _, labelID := range expectedLabelIDs {
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID})
@ -122,7 +122,7 @@ func TestIssue_ClearLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID})
assert.NoError(t, issues_model.ClearIssueLabels(db.DefaultContext, issue, doer)) assert.NoError(t, issues_model.ClearIssueLabels(issue, doer))
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: test.issueID}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: test.issueID})
} }
} }
@ -230,7 +230,7 @@ func TestGetRepoIDsForIssuesOptions(t *testing.T) {
[]int64{1, 2}, []int64{1, 2},
}, },
} { } {
repoIDs, err := issues_model.GetRepoIDsForIssuesOptions(db.DefaultContext, &test.Opts, user) repoIDs, err := issues_model.GetRepoIDsForIssuesOptions(&test.Opts, user)
assert.NoError(t, err) assert.NoError(t, err)
if assert.Len(t, repoIDs, len(test.ExpectedRepoIDs)) { if assert.Len(t, repoIDs, len(test.ExpectedRepoIDs)) {
for i, repoID := range repoIDs { for i, repoID := range repoIDs {

View File

@ -307,7 +307,7 @@ func TestNewIssueLabel(t *testing.T) {
// add new IssueLabel // add new IssueLabel
prevNumIssues := label.NumIssues prevNumIssues := label.NumIssues
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer)) assert.NoError(t, issues_model.NewIssueLabel(issue, label, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
Type: issues_model.CommentTypeLabel, Type: issues_model.CommentTypeLabel,
@ -320,7 +320,7 @@ func TestNewIssueLabel(t *testing.T) {
assert.EqualValues(t, prevNumIssues+1, label.NumIssues) assert.EqualValues(t, prevNumIssues+1, label.NumIssues)
// re-add existing IssueLabel // re-add existing IssueLabel
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer)) assert.NoError(t, issues_model.NewIssueLabel(issue, label, doer))
unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{}) unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
} }
@ -334,19 +334,19 @@ func TestNewIssueExclusiveLabel(t *testing.T) {
exclusiveLabelB := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8}) exclusiveLabelB := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
// coexisting regular and exclusive label // coexisting regular and exclusive label
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, otherLabel, doer)) assert.NoError(t, issues_model.NewIssueLabel(issue, otherLabel, doer))
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer)) assert.NoError(t, issues_model.NewIssueLabel(issue, exclusiveLabelA, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
// exclusive label replaces existing one // exclusive label replaces existing one
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelB, doer)) assert.NoError(t, issues_model.NewIssueLabel(issue, exclusiveLabelB, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID})
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
// exclusive label replaces existing one again // exclusive label replaces existing one again
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer)) assert.NoError(t, issues_model.NewIssueLabel(issue, exclusiveLabelA, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID})
@ -359,7 +359,7 @@ func TestNewIssueLabels(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 5}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 5})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer)) assert.NoError(t, issues_model.NewIssueLabels(issue, []*issues_model.Label{label1, label2}, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label1.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label1.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
Type: issues_model.CommentTypeLabel, Type: issues_model.CommentTypeLabel,
@ -377,7 +377,7 @@ func TestNewIssueLabels(t *testing.T) {
assert.EqualValues(t, 1, label2.NumClosedIssues) assert.EqualValues(t, 1, label2.NumClosedIssues)
// corner case: test empty slice // corner case: test empty slice
assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{}, doer)) assert.NoError(t, issues_model.NewIssueLabels(issue, []*issues_model.Label{}, doer))
unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{}) unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
} }

View File

@ -58,8 +58,8 @@ func (opts GetMilestonesOption) toCond() builder.Cond {
} }
// GetMilestones returns milestones filtered by GetMilestonesOption's // GetMilestones returns milestones filtered by GetMilestonesOption's
func GetMilestones(ctx context.Context, opts GetMilestonesOption) (MilestoneList, int64, error) { func GetMilestones(opts GetMilestonesOption) (MilestoneList, int64, error) {
sess := db.GetEngine(ctx).Where(opts.toCond()) sess := db.GetEngine(db.DefaultContext).Where(opts.toCond())
if opts.Page != 0 { if opts.Page != 0 {
sess = db.SetSessionPagination(sess, &opts) sess = db.SetSessionPagination(sess, &opts)

View File

@ -40,7 +40,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64, state api.StateType) { test := func(repoID int64, state api.StateType) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
milestones, _, err := issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{ milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
RepoID: repo.ID, RepoID: repo.ID,
State: state, State: state,
}) })
@ -77,7 +77,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
test(3, api.StateClosed) test(3, api.StateClosed)
test(3, api.StateAll) test(3, api.StateAll)
milestones, _, err := issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{ milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
RepoID: unittest.NonexistentID, RepoID: unittest.NonexistentID,
State: api.StateOpen, State: api.StateOpen,
}) })
@ -90,7 +90,7 @@ func TestGetMilestones(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
test := func(sortType string, sortCond func(*issues_model.Milestone) int) { test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
for _, page := range []int{0, 1} { for _, page := range []int{0, 1} {
milestones, _, err := issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{ milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: page, Page: page,
PageSize: setting.UI.IssuePagingNum, PageSize: setting.UI.IssuePagingNum,
@ -107,7 +107,7 @@ func TestGetMilestones(t *testing.T) {
} }
assert.True(t, sort.IntsAreSorted(values)) assert.True(t, sort.IntsAreSorted(values))
milestones, _, err = issues_model.GetMilestones(db.DefaultContext, issues_model.GetMilestonesOption{ milestones, _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: page, Page: page,
PageSize: setting.UI.IssuePagingNum, PageSize: setting.UI.IssuePagingNum,

View File

@ -378,9 +378,9 @@ func (pr *PullRequest) GetApprovalCounts(ctx context.Context) ([]*ReviewCount, e
} }
// GetApprovers returns the approvers of the pull request // GetApprovers returns the approvers of the pull request
func (pr *PullRequest) GetApprovers(ctx context.Context) string { func (pr *PullRequest) GetApprovers() string {
stringBuilder := strings.Builder{} stringBuilder := strings.Builder{}
if err := pr.getReviewedByLines(ctx, &stringBuilder); err != nil { if err := pr.getReviewedByLines(&stringBuilder); err != nil {
log.Error("Unable to getReviewedByLines: Error: %v", err) log.Error("Unable to getReviewedByLines: Error: %v", err)
return "" return ""
} }
@ -388,14 +388,14 @@ func (pr *PullRequest) GetApprovers(ctx context.Context) string {
return stringBuilder.String() return stringBuilder.String()
} }
func (pr *PullRequest) getReviewedByLines(ctx context.Context, writer io.Writer) error { func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
if maxReviewers == 0 { if maxReviewers == 0 {
return nil return nil
} }
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -594,9 +594,9 @@ func GetUnmergedPullRequest(ctx context.Context, headRepoID, baseRepoID int64, h
// GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status) // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
// by given head information (repo and branch). // by given head information (repo and branch).
func GetLatestPullRequestByHeadInfo(ctx context.Context, repoID int64, branch string) (*PullRequest, error) { func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
pr := new(PullRequest) pr := new(PullRequest)
has, err := db.GetEngine(ctx). has, err := db.GetEngine(db.DefaultContext).
Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub). Where("head_repo_id = ? AND head_branch = ? AND flow = ?", repoID, branch, PullRequestFlowGithub).
OrderBy("id DESC"). OrderBy("id DESC").
Get(pr) Get(pr)
@ -646,9 +646,9 @@ func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) {
} }
// GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
func GetPullRequestByIssueIDWithNoAttributes(ctx context.Context, issueID int64) (*PullRequest, error) { func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
var pr PullRequest var pr PullRequest
has, err := db.GetEngine(ctx).Where("issue_id = ?", issueID).Get(&pr) has, err := db.GetEngine(db.DefaultContext).Where("issue_id = ?", issueID).Get(&pr)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -687,14 +687,14 @@ func GetAllUnmergedAgitPullRequestByPoster(ctx context.Context, uid int64) ([]*P
} }
// Update updates all fields of pull request. // Update updates all fields of pull request.
func (pr *PullRequest) Update(ctx context.Context) error { func (pr *PullRequest) Update() error {
_, err := db.GetEngine(ctx).ID(pr.ID).AllCols().Update(pr) _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).AllCols().Update(pr)
return err return err
} }
// UpdateCols updates specific fields of pull request. // UpdateCols updates specific fields of pull request.
func (pr *PullRequest) UpdateCols(ctx context.Context, cols ...string) error { func (pr *PullRequest) UpdateCols(cols ...string) error {
_, err := db.GetEngine(ctx).ID(pr.ID).Cols(cols...).Update(pr) _, err := db.GetEngine(db.DefaultContext).ID(pr.ID).Cols(cols...).Update(pr)
return err return err
} }
@ -706,8 +706,8 @@ func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string
// IsWorkInProgress determine if the Pull Request is a Work In Progress by its title // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
// Issue must be set before this method can be called. // Issue must be set before this method can be called.
func (pr *PullRequest) IsWorkInProgress(ctx context.Context) bool { func (pr *PullRequest) IsWorkInProgress() bool {
if err := pr.LoadIssue(ctx); err != nil { if err := pr.LoadIssue(db.DefaultContext); err != nil {
log.Error("LoadIssue: %v", err) log.Error("LoadIssue: %v", err)
return false return false
} }
@ -774,8 +774,8 @@ func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRep
} }
// GetBaseBranchLink returns the relative URL of the base branch // GetBaseBranchLink returns the relative URL of the base branch
func (pr *PullRequest) GetBaseBranchLink(ctx context.Context) string { func (pr *PullRequest) GetBaseBranchLink() string {
if err := pr.LoadBaseRepo(ctx); err != nil { if err := pr.LoadBaseRepo(db.DefaultContext); err != nil {
log.Error("LoadBaseRepo: %v", err) log.Error("LoadBaseRepo: %v", err)
return "" return ""
} }
@ -786,12 +786,12 @@ func (pr *PullRequest) GetBaseBranchLink(ctx context.Context) string {
} }
// GetHeadBranchLink returns the relative URL of the head branch // GetHeadBranchLink returns the relative URL of the head branch
func (pr *PullRequest) GetHeadBranchLink(ctx context.Context) string { func (pr *PullRequest) GetHeadBranchLink() string {
if pr.Flow == PullRequestFlowAGit { if pr.Flow == PullRequestFlowAGit {
return "" return ""
} }
if err := pr.LoadHeadRepo(ctx); err != nil { if err := pr.LoadHeadRepo(db.DefaultContext); err != nil {
log.Error("LoadHeadRepo: %v", err) log.Error("LoadHeadRepo: %v", err)
return "" return ""
} }
@ -810,14 +810,14 @@ func UpdateAllowEdits(ctx context.Context, pr *PullRequest) error {
} }
// Mergeable returns if the pullrequest is mergeable. // Mergeable returns if the pullrequest is mergeable.
func (pr *PullRequest) Mergeable(ctx context.Context) bool { func (pr *PullRequest) Mergeable() bool {
// If a pull request isn't mergable if it's: // If a pull request isn't mergable if it's:
// - Being conflict checked. // - Being conflict checked.
// - Has a conflict. // - Has a conflict.
// - Received a error while being conflict checked. // - Received a error while being conflict checked.
// - Is a work-in-progress pull request. // - Is a work-in-progress pull request.
return pr.Status != PullRequestStatusChecking && pr.Status != PullRequestStatusConflict && return pr.Status != PullRequestStatusChecking && pr.Status != PullRequestStatusConflict &&
pr.Status != PullRequestStatusError && !pr.IsWorkInProgress(ctx) pr.Status != PullRequestStatusError && !pr.IsWorkInProgress()
} }
// HasEnoughApprovals returns true if pr has enough granted approvals. // HasEnoughApprovals returns true if pr has enough granted approvals.
@ -890,7 +890,7 @@ func MergeBlockedByOutdatedBranch(protectBranch *git_model.ProtectedBranch, pr *
func PullRequestCodeOwnersReview(ctx context.Context, pull *Issue, pr *PullRequest) error { func PullRequestCodeOwnersReview(ctx context.Context, pull *Issue, pr *PullRequest) error {
files := []string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"} files := []string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"}
if pr.IsWorkInProgress(ctx) { if pr.IsWorkInProgress() {
return nil return nil
} }

View File

@ -213,7 +213,7 @@ func TestPullRequest_Update(t *testing.T) {
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
pr.BaseBranch = "baseBranch" pr.BaseBranch = "baseBranch"
pr.HeadBranch = "headBranch" pr.HeadBranch = "headBranch"
pr.Update(db.DefaultContext) pr.Update()
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID}) pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID})
assert.Equal(t, "baseBranch", pr.BaseBranch) assert.Equal(t, "baseBranch", pr.BaseBranch)
@ -228,7 +228,7 @@ func TestPullRequest_UpdateCols(t *testing.T) {
BaseBranch: "baseBranch", BaseBranch: "baseBranch",
HeadBranch: "headBranch", HeadBranch: "headBranch",
} }
assert.NoError(t, pr.UpdateCols(db.DefaultContext, "head_branch")) assert.NoError(t, pr.UpdateCols("head_branch"))
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.Equal(t, "master", pr.BaseBranch) assert.Equal(t, "master", pr.BaseBranch)
@ -260,13 +260,13 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) {
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
pr.LoadIssue(db.DefaultContext) pr.LoadIssue(db.DefaultContext)
assert.False(t, pr.IsWorkInProgress(db.DefaultContext)) assert.False(t, pr.IsWorkInProgress())
pr.Issue.Title = "WIP: " + pr.Issue.Title pr.Issue.Title = "WIP: " + pr.Issue.Title
assert.True(t, pr.IsWorkInProgress(db.DefaultContext)) assert.True(t, pr.IsWorkInProgress())
pr.Issue.Title = "[wip]: " + pr.Issue.Title pr.Issue.Title = "[wip]: " + pr.Issue.Title
assert.True(t, pr.IsWorkInProgress(db.DefaultContext)) assert.True(t, pr.IsWorkInProgress())
} }
func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) {
@ -334,7 +334,7 @@ func TestGetApprovers(t *testing.T) {
// Official reviews are already deduplicated. Allow unofficial reviews // Official reviews are already deduplicated. Allow unofficial reviews
// to assert that there are no duplicated approvers. // to assert that there are no duplicated approvers.
setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly = false setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly = false
approvers := pr.GetApprovers(db.DefaultContext) approvers := pr.GetApprovers()
expected := "Reviewed-by: User Five <user5@example.com>\nReviewed-by: Org Six <org6@example.com>\n" expected := "Reviewed-by: User Five <user5@example.com>\nReviewed-by: Org Six <org6@example.com>\n"
assert.EqualValues(t, expected, approvers) assert.EqualValues(t, expected, approvers)
} }

View File

@ -277,8 +277,8 @@ func UpdateRepoStats(ctx context.Context, id int64) error {
return nil return nil
} }
func updateUserStarNumbers(ctx context.Context, users []user_model.User) error { func updateUserStarNumbers(users []user_model.User) error {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -294,19 +294,19 @@ func updateUserStarNumbers(ctx context.Context, users []user_model.User) error {
} }
// DoctorUserStarNum recalculate Stars number for all user // DoctorUserStarNum recalculate Stars number for all user
func DoctorUserStarNum(ctx context.Context) (err error) { func DoctorUserStarNum() (err error) {
const batchSize = 100 const batchSize = 100
for start := 0; ; start += batchSize { for start := 0; ; start += batchSize {
users := make([]user_model.User, 0, batchSize) users := make([]user_model.User, 0, batchSize)
if err = db.GetEngine(ctx).Limit(batchSize, start).Where("type = ?", 0).Cols("id").Find(&users); err != nil { if err = db.GetEngine(db.DefaultContext).Limit(batchSize, start).Where("type = ?", 0).Cols("id").Find(&users); err != nil {
return err return err
} }
if len(users) == 0 { if len(users) == 0 {
break break
} }
if err = updateUserStarNumbers(ctx, users); err != nil { if err = updateUserStarNumbers(users); err != nil {
return err return err
} }
} }

View File

@ -31,8 +31,8 @@ func ExistsWithAvatarAtStoragePath(ctx context.Context, storagePath string) (boo
} }
// RelAvatarLink returns a relative link to the repository's avatar. // RelAvatarLink returns a relative link to the repository's avatar.
func (repo *Repository) RelAvatarLink(ctx context.Context) string { func (repo *Repository) RelAvatarLink() string {
return repo.relAvatarLink(ctx) return repo.relAvatarLink(db.DefaultContext)
} }
// generateRandomAvatar generates a random avatar for repository. // generateRandomAvatar generates a random avatar for repository.

View File

@ -108,8 +108,8 @@ func GetLanguageStats(ctx context.Context, repo *Repository) (LanguageStatList,
} }
// GetTopLanguageStats returns the top language statistics for a repository // GetTopLanguageStats returns the top language statistics for a repository
func GetTopLanguageStats(ctx context.Context, repo *Repository, limit int) (LanguageStatList, error) { func GetTopLanguageStats(repo *Repository, limit int) (LanguageStatList, error) {
stats, err := GetLanguageStats(ctx, repo) stats, err := GetLanguageStats(db.DefaultContext, repo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -140,8 +140,8 @@ func GetTopLanguageStats(ctx context.Context, repo *Repository, limit int) (Lang
} }
// UpdateLanguageStats updates the language statistics for repository // UpdateLanguageStats updates the language statistics for repository
func UpdateLanguageStats(ctx context.Context, repo *Repository, commitID string, stats map[string]int64) error { func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int64) error {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }
@ -212,8 +212,8 @@ func UpdateLanguageStats(ctx context.Context, repo *Repository, commitID string,
} }
// CopyLanguageStat Copy originalRepo language stat information to destRepo (use for forked repo) // CopyLanguageStat Copy originalRepo language stat information to destRepo (use for forked repo)
func CopyLanguageStat(ctx context.Context, originalRepo, destRepo *Repository) error { func CopyLanguageStat(originalRepo, destRepo *Repository) error {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(db.DefaultContext)
if err != nil { if err != nil {
return err return err
} }

View File

@ -447,7 +447,7 @@ func (repo *Repository) MustOwner(ctx context.Context) *user_model.User {
} }
// ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers. // ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers.
func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string { func (repo *Repository) ComposeMetas() map[string]string {
if len(repo.RenderingMetas) == 0 { if len(repo.RenderingMetas) == 0 {
metas := map[string]string{ metas := map[string]string{
"user": repo.OwnerName, "user": repo.OwnerName,
@ -456,7 +456,7 @@ func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string {
"mode": "comment", "mode": "comment",
} }
unit, err := repo.GetUnit(ctx, unit.TypeExternalTracker) unit, err := repo.GetUnit(db.DefaultContext, unit.TypeExternalTracker)
if err == nil { if err == nil {
metas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat metas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat
switch unit.ExternalTrackerConfig().ExternalTrackerStyle { switch unit.ExternalTrackerConfig().ExternalTrackerStyle {
@ -470,10 +470,10 @@ func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string {
} }
} }
repo.MustOwner(ctx) repo.MustOwner(db.DefaultContext)
if repo.Owner.IsOrganization() { if repo.Owner.IsOrganization() {
teams := make([]string, 0, 5) teams := make([]string, 0, 5)
_ = db.GetEngine(ctx).Table("team_repo"). _ = db.GetEngine(db.DefaultContext).Table("team_repo").
Join("INNER", "team", "team.id = team_repo.team_id"). Join("INNER", "team", "team.id = team_repo.team_id").
Where("team_repo.repo_id = ?", repo.ID). Where("team_repo.repo_id = ?", repo.ID).
Select("team.lower_name"). Select("team.lower_name").
@ -489,10 +489,10 @@ func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string {
} }
// ComposeDocumentMetas composes a map of metas for properly rendering documents // ComposeDocumentMetas composes a map of metas for properly rendering documents
func (repo *Repository) ComposeDocumentMetas(ctx context.Context) map[string]string { func (repo *Repository) ComposeDocumentMetas() map[string]string {
if len(repo.DocumentRenderingMetas) == 0 { if len(repo.DocumentRenderingMetas) == 0 {
metas := map[string]string{} metas := map[string]string{}
for k, v := range repo.ComposeMetas(ctx) { for k, v := range repo.ComposeMetas() {
metas[k] = v metas[k] = v
} }
metas["mode"] = "document" metas["mode"] = "document"
@ -566,8 +566,8 @@ func (repo *Repository) CanEnablePulls() bool {
} }
// AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled. // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
func (repo *Repository) AllowsPulls(ctx context.Context) bool { func (repo *Repository) AllowsPulls() bool {
return repo.CanEnablePulls() && repo.UnitEnabled(ctx, unit.TypePullRequests) return repo.CanEnablePulls() && repo.UnitEnabled(db.DefaultContext, unit.TypePullRequests)
} }
// CanEnableEditor returns true if repository meets the requirements of web editor. // CanEnableEditor returns true if repository meets the requirements of web editor.
@ -718,12 +718,12 @@ func GetRepositoryByOwnerAndName(ctx context.Context, ownerName, repoName string
} }
// GetRepositoryByName returns the repository by given name under user if exists. // GetRepositoryByName returns the repository by given name under user if exists.
func GetRepositoryByName(ctx context.Context, ownerID int64, name string) (*Repository, error) { func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
repo := &Repository{ repo := &Repository{
OwnerID: ownerID, OwnerID: ownerID,
LowerName: strings.ToLower(name), LowerName: strings.ToLower(name),
} }
has, err := db.GetEngine(ctx).Get(repo) has, err := db.GetEngine(db.DefaultContext).Get(repo)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
@ -788,9 +788,9 @@ func GetRepositoryByID(ctx context.Context, id int64) (*Repository, error) {
} }
// GetRepositoriesMapByIDs returns the repositories by given id slice. // GetRepositoriesMapByIDs returns the repositories by given id slice.
func GetRepositoriesMapByIDs(ctx context.Context, ids []int64) (map[int64]*Repository, error) { func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
repos := make(map[int64]*Repository, len(ids)) repos := make(map[int64]*Repository, len(ids))
return repos, db.GetEngine(ctx).In("id", ids).Find(&repos) return repos, db.GetEngine(db.DefaultContext).In("id", ids).Find(&repos)
} }
// IsRepositoryModelOrDirExist returns true if the repository with given name under user has already existed. // IsRepositoryModelOrDirExist returns true if the repository with given name under user has already existed.
@ -822,8 +822,8 @@ func GetTemplateRepo(ctx context.Context, repo *Repository) (*Repository, error)
} }
// TemplateRepo returns the repository, which is template of this repository // TemplateRepo returns the repository, which is template of this repository
func (repo *Repository) TemplateRepo(ctx context.Context) *Repository { func (repo *Repository) TemplateRepo() *Repository {
repo, err := GetTemplateRepo(ctx, repo) repo, err := GetTemplateRepo(db.DefaultContext, repo)
if err != nil { if err != nil {
log.Error("TemplateRepo: %v", err) log.Error("TemplateRepo: %v", err)
return nil return nil

View File

@ -36,14 +36,14 @@ func init() {
} }
// GetUnindexedRepos returns repos which do not have an indexer status // GetUnindexedRepos returns repos which do not have an indexer status
func GetUnindexedRepos(ctx context.Context, indexerType RepoIndexerType, maxRepoID int64, page, pageSize int) ([]int64, error) { func GetUnindexedRepos(indexerType RepoIndexerType, maxRepoID int64, page, pageSize int) ([]int64, error) {
ids := make([]int64, 0, 50) ids := make([]int64, 0, 50)
cond := builder.Cond(builder.IsNull{ cond := builder.Cond(builder.IsNull{
"repo_indexer_status.id", "repo_indexer_status.id",
}).And(builder.Eq{ }).And(builder.Eq{
"repository.is_empty": false, "repository.is_empty": false,
}) })
sess := db.GetEngine(ctx).Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType) sess := db.GetEngine(db.DefaultContext).Table("repository").Join("LEFT OUTER", "repo_indexer_status", "repository.id = repo_indexer_status.repo_id AND repo_indexer_status.indexer_type = ?", indexerType)
if maxRepoID > 0 { if maxRepoID > 0 {
cond = builder.And(cond, builder.Lte{ cond = builder.And(cond, builder.Lte{
"repository.id": maxRepoID, "repository.id": maxRepoID,

View File

@ -21,8 +21,8 @@ import (
) )
// FindReposMapByIDs find repos as map // FindReposMapByIDs find repos as map
func FindReposMapByIDs(ctx context.Context, repoIDs []int64, res map[int64]*Repository) error { func FindReposMapByIDs(repoIDs []int64, res map[int64]*Repository) error {
return db.GetEngine(ctx).In("id", repoIDs).Find(&res) return db.GetEngine(db.DefaultContext).In("id", repoIDs).Find(&res)
} }
// RepositoryListDefaultPageSize is the default number of repositories // RepositoryListDefaultPageSize is the default number of repositories
@ -672,12 +672,12 @@ func SearchRepositoryByName(ctx context.Context, opts *SearchRepoOptions) (Repos
// SearchRepositoryIDs takes keyword and part of repository name to search, // SearchRepositoryIDs takes keyword and part of repository name to search,
// it returns results in given range and number of total results. // it returns results in given range and number of total results.
func SearchRepositoryIDs(ctx context.Context, opts *SearchRepoOptions) ([]int64, int64, error) { func SearchRepositoryIDs(opts *SearchRepoOptions) ([]int64, int64, error) {
opts.IncludeDescription = false opts.IncludeDescription = false
cond := SearchRepositoryCondition(opts) cond := SearchRepositoryCondition(opts)
sess, count, err := searchRepositoryByCondition(ctx, opts, cond) sess, count, err := searchRepositoryByCondition(db.DefaultContext, opts, cond)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }

View File

@ -83,7 +83,7 @@ func TestMetas(t *testing.T) {
repo.Units = nil repo.Units = nil
metas := repo.ComposeMetas(db.DefaultContext) metas := repo.ComposeMetas()
assert.Equal(t, "testRepo", metas["repo"]) assert.Equal(t, "testRepo", metas["repo"])
assert.Equal(t, "testOwner", metas["user"]) assert.Equal(t, "testOwner", metas["user"])
@ -97,7 +97,7 @@ func TestMetas(t *testing.T) {
testSuccess := func(expectedStyle string) { testSuccess := func(expectedStyle string) {
repo.Units = []*repo_model.RepoUnit{&externalTracker} repo.Units = []*repo_model.RepoUnit{&externalTracker}
repo.RenderingMetas = nil repo.RenderingMetas = nil
metas := repo.ComposeMetas(db.DefaultContext) metas := repo.ComposeMetas()
assert.Equal(t, expectedStyle, metas["style"]) assert.Equal(t, expectedStyle, metas["style"])
assert.Equal(t, "testRepo", metas["repo"]) assert.Equal(t, "testRepo", metas["repo"])
assert.Equal(t, "testOwner", metas["user"]) assert.Equal(t, "testOwner", metas["user"])
@ -118,7 +118,7 @@ func TestMetas(t *testing.T) {
repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3)
assert.NoError(t, err) assert.NoError(t, err)
metas = repo.ComposeMetas(db.DefaultContext) metas = repo.ComposeMetas()
assert.Contains(t, metas, "org") assert.Contains(t, metas, "org")
assert.Contains(t, metas, "teams") assert.Contains(t, metas, "teams")
assert.Equal(t, "org3", metas["org"]) assert.Equal(t, "org3", metas["org"])

View File

@ -20,5 +20,5 @@ func TestCheckRepoStats(t *testing.T) {
func TestDoctorUserStarNum(t *testing.T) { func TestDoctorUserStarNum(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, DoctorUserStarNum(db.DefaultContext)) assert.NoError(t, DoctorUserStarNum())
} }

View File

@ -47,7 +47,8 @@ func checkForConsistency(t assert.TestingT, bean any) {
assert.NoError(t, err) assert.NoError(t, err)
f := consistencyCheckMap[tb.Name] f := consistencyCheckMap[tb.Name]
if f == nil { if f == nil {
assert.FailNow(t, "unknown bean type: %#v", bean) assert.Fail(t, "unknown bean type: %#v", bean)
return
} }
f(t, bean) f(t, bean)
} }

View File

@ -495,7 +495,7 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
} }
// Get repository. // Get repository.
repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, repoName) repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName) redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName)
@ -711,13 +711,13 @@ func RepoAssignment(ctx *Context) context.CancelFunc {
// Pull request is allowed if this is a fork repository // Pull request is allowed if this is a fork repository
// and base repository accepts pull requests. // and base repository accepts pull requests.
if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls(ctx) { if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
canCompare = true canCompare = true
ctx.Data["BaseRepo"] = repo.BaseRepo ctx.Data["BaseRepo"] = repo.BaseRepo
ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
ctx.Repo.PullRequest.Allowed = canPush ctx.Repo.PullRequest.Allowed = canPush
ctx.Repo.PullRequest.HeadInfoSubURL = url.PathEscape(ctx.Repo.Owner.Name) + ":" + util.PathEscapeSegments(ctx.Repo.BranchName) ctx.Repo.PullRequest.HeadInfoSubURL = url.PathEscape(ctx.Repo.Owner.Name) + ":" + util.PathEscapeSegments(ctx.Repo.BranchName)
} else if repo.AllowsPulls(ctx) { } else if repo.AllowsPulls() {
// Or, this is repository accepts pull requests between branches. // Or, this is repository accepts pull requests between branches.
canCompare = true canCompare = true
ctx.Data["BaseRepo"] = repo ctx.Data["BaseRepo"] = repo

View File

@ -83,7 +83,8 @@ func LoadRepo(t *testing.T, ctx gocontext.Context, repoID int64) {
ctx.Repo = repo ctx.Repo = repo
doer = ctx.Doer doer = ctx.Doer
default: default:
assert.FailNow(t, "context is not *context.Context or *context.APIContext") assert.Fail(t, "context is not *context.Context or *context.APIContext")
return
} }
repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
@ -104,7 +105,8 @@ func LoadRepoCommit(t *testing.T, ctx gocontext.Context) {
case *context.APIContext: case *context.APIContext:
repo = ctx.Repo repo = ctx.Repo
default: default:
assert.FailNow(t, "context is not *context.Context or *context.APIContext") assert.Fail(t, "context is not *context.Context or *context.APIContext")
return
} }
gitRepo, err := git.OpenRepository(ctx, repo.Repository.RepoPath()) gitRepo, err := git.OpenRepository(ctx, repo.Repository.RepoPath())
@ -128,7 +130,8 @@ func LoadUser(t *testing.T, ctx gocontext.Context, userID int64) {
case *context.APIContext: case *context.APIContext:
ctx.Doer = doer ctx.Doer = doer
default: default:
assert.FailNow(t, "context is not *context.Context or *context.APIContext") assert.Fail(t, "context is not *context.Context or *context.APIContext")
return
} }
} }

View File

@ -74,7 +74,7 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro
pr.MergeBase = strings.TrimSpace(pr.MergeBase) pr.MergeBase = strings.TrimSpace(pr.MergeBase)
if pr.MergeBase != oldMergeBase { if pr.MergeBase != oldMergeBase {
if autofix { if autofix {
if err := pr.UpdateCols(ctx, "merge_base"); err != nil { if err := pr.UpdateCols("merge_base"); err != nil {
logger.Critical("Failed to update merge_base. ERROR: %v", err) logger.Critical("Failed to update merge_base. ERROR: %v", err)
return fmt.Errorf("Failed to update merge_base. ERROR: %w", err) return fmt.Errorf("Failed to update merge_base. ERROR: %w", err)
} }

View File

@ -74,7 +74,7 @@ func checkHooks(ctx context.Context, logger log.Logger, autofix bool) error {
func checkUserStarNum(ctx context.Context, logger log.Logger, autofix bool) error { func checkUserStarNum(ctx context.Context, logger log.Logger, autofix bool) error {
if autofix { if autofix {
if err := models.DoctorUserStarNum(ctx); err != nil { if err := models.DoctorUserStarNum(); err != nil {
logger.Critical("Unable update User Stars numbers") logger.Critical("Unable update User Stars numbers")
return err return err
} }

View File

@ -27,7 +27,7 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) {
assert.Equal(t, "linguist-vendored", attr.Attribute) assert.Equal(t, "linguist-vendored", attr.Attribute)
assert.Equal(t, "unspecified", attr.Value) assert.Equal(t, "unspecified", attr.Value)
case <-time.After(100 * time.Millisecond): case <-time.After(100 * time.Millisecond):
assert.FailNow(t, "took too long to read an attribute from the list") assert.Fail(t, "took too long to read an attribute from the list")
} }
// Write a second attribute again // Write a second attribute again
n, err = wr.Write([]byte(testStr)) n, err = wr.Write([]byte(testStr))
@ -41,7 +41,7 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) {
assert.Equal(t, "linguist-vendored", attr.Attribute) assert.Equal(t, "linguist-vendored", attr.Attribute)
assert.Equal(t, "unspecified", attr.Value) assert.Equal(t, "unspecified", attr.Value)
case <-time.After(100 * time.Millisecond): case <-time.After(100 * time.Millisecond):
assert.FailNow(t, "took too long to read an attribute from the list") assert.Fail(t, "took too long to read an attribute from the list")
} }
// Write a partial attribute // Write a partial attribute
@ -52,14 +52,14 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) {
select { select {
case <-wr.ReadAttribute(): case <-wr.ReadAttribute():
assert.FailNow(t, "There should not be an attribute ready to read") assert.Fail(t, "There should not be an attribute ready to read")
case <-time.After(100 * time.Millisecond): case <-time.After(100 * time.Millisecond):
} }
_, err = wr.Write([]byte("attribute\x00")) _, err = wr.Write([]byte("attribute\x00"))
assert.NoError(t, err) assert.NoError(t, err)
select { select {
case <-wr.ReadAttribute(): case <-wr.ReadAttribute():
assert.FailNow(t, "There should not be an attribute ready to read") assert.Fail(t, "There should not be an attribute ready to read")
case <-time.After(100 * time.Millisecond): case <-time.After(100 * time.Millisecond):
} }

View File

@ -71,6 +71,7 @@ func TestRepository_GetTag(t *testing.T) {
if lTag == nil { if lTag == nil {
assert.NotNil(t, lTag) assert.NotNil(t, lTag)
assert.FailNow(t, "nil lTag: %s", lTagName) assert.FailNow(t, "nil lTag: %s", lTagName)
return
} }
assert.EqualValues(t, lTagName, lTag.Name) assert.EqualValues(t, lTagName, lTag.Name)
assert.EqualValues(t, lTagCommitID, lTag.ID.String()) assert.EqualValues(t, lTagCommitID, lTag.ID.String())
@ -104,6 +105,7 @@ func TestRepository_GetTag(t *testing.T) {
if aTag == nil { if aTag == nil {
assert.NotNil(t, aTag) assert.NotNil(t, aTag)
assert.FailNow(t, "nil aTag: %s", aTagName) assert.FailNow(t, "nil aTag: %s", aTagName)
return
} }
assert.EqualValues(t, aTagName, aTag.Name) assert.EqualValues(t, aTagName, aTag.Name)
assert.EqualValues(t, aTagID, aTag.ID.String()) assert.EqualValues(t, aTagID, aTag.ID.String())

View File

@ -288,7 +288,7 @@ func populateRepoIndexer(ctx context.Context) {
return return
default: default:
} }
ids, err := repo_model.GetUnindexedRepos(ctx, repo_model.RepoIndexerTypeCode, maxRepoID, 0, 50) ids, err := repo_model.GetUnindexedRepos(repo_model.RepoIndexerTypeCode, maxRepoID, 0, 50)
if err != nil { if err != nil {
log.Error("populateRepoIndexer: %v", err) log.Error("populateRepoIndexer: %v", err)
return return

View File

@ -96,10 +96,11 @@ func TestBleveIndexAndSearch(t *testing.T) {
idx := bleve.NewIndexer(dir) idx := bleve.NewIndexer(dir)
_, err := idx.Init(context.Background()) _, err := idx.Init(context.Background())
if err != nil { if err != nil {
assert.Fail(t, "Unable to create bleve indexer Error: %v", err)
if idx != nil { if idx != nil {
idx.Close() idx.Close()
} }
assert.FailNow(t, "Unable to create bleve indexer Error: %v", err) return
} }
defer idx.Close() defer idx.Close()
@ -117,10 +118,11 @@ func TestESIndexAndSearch(t *testing.T) {
indexer := elasticsearch.NewIndexer(u, "gitea_codes") indexer := elasticsearch.NewIndexer(u, "gitea_codes")
if _, err := indexer.Init(context.Background()); err != nil { if _, err := indexer.Init(context.Background()); err != nil {
assert.Fail(t, "Unable to init ES indexer Error: %v", err)
if indexer != nil { if indexer != nil {
indexer.Close() indexer.Close()
} }
assert.FailNow(t, "Unable to init ES indexer Error: %v", err) return
} }
defer indexer.Close() defer indexer.Close()

View File

@ -107,7 +107,7 @@ func getIssueIndexerData(ctx context.Context, issueID int64) (*internal.IndexerD
NoLabel: len(labels) == 0, NoLabel: len(labels) == 0,
MilestoneID: issue.MilestoneID, MilestoneID: issue.MilestoneID,
ProjectID: projectID, ProjectID: projectID,
ProjectBoardID: issue.ProjectBoardID(ctx), ProjectBoardID: issue.ProjectBoardID(),
PosterID: issue.PosterID, PosterID: issue.PosterID,
AssigneeID: issue.AssigneeID, AssigneeID: issue.AssigneeID,
MentionIDs: mentionIDs, MentionIDs: mentionIDs,

View File

@ -68,7 +68,7 @@ func (db *DBIndexer) Index(id int64) error {
} }
return err return err
} }
err = repo_model.UpdateLanguageStats(ctx, repo, commitID, stats) err = repo_model.UpdateLanguageStats(repo, commitID, stats)
if err != nil { if err != nil {
log.Error("Unable to update language stats for ID %s for default branch %s in %s. Error: %v", commitID, repo.DefaultBranch, repo.RepoPath(), err) log.Error("Unable to update language stats for ID %s for default branch %s in %s. Error: %v", commitID, repo.DefaultBranch, repo.RepoPath(), err)
return err return err

View File

@ -4,8 +4,6 @@
package stats package stats
import ( import (
"context"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/graceful"
@ -30,14 +28,14 @@ func Init() error {
return err return err
} }
go populateRepoIndexer(db.DefaultContext) go populateRepoIndexer()
return nil return nil
} }
// populateRepoIndexer populate the repo indexer with pre-existing data. This // populateRepoIndexer populate the repo indexer with pre-existing data. This
// should only be run when the indexer is created for the first time. // should only be run when the indexer is created for the first time.
func populateRepoIndexer(ctx context.Context) { func populateRepoIndexer() {
log.Info("Populating the repo stats indexer with existing repositories") log.Info("Populating the repo stats indexer with existing repositories")
isShutdown := graceful.GetManager().IsShutdown() isShutdown := graceful.GetManager().IsShutdown()
@ -64,7 +62,7 @@ func populateRepoIndexer(ctx context.Context) {
return return
default: default:
} }
ids, err := repo_model.GetUnindexedRepos(ctx, repo_model.RepoIndexerTypeStats, maxRepoID, 0, 50) ids, err := repo_model.GetUnindexedRepos(repo_model.RepoIndexerTypeStats, maxRepoID, 0, 50)
if err != nil { if err != nil {
log.Error("populateRepoIndexer: %v", err) log.Error("populateRepoIndexer: %v", err)
return return

View File

@ -45,7 +45,7 @@ func TestRepoStatsIndex(t *testing.T) {
status, err := repo_model.GetIndexerStatus(db.DefaultContext, repo, repo_model.RepoIndexerTypeStats) status, err := repo_model.GetIndexerStatus(db.DefaultContext, repo, repo_model.RepoIndexerTypeStats)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.CommitSha) assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.CommitSha)
langs, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, 5) langs, err := repo_model.GetTopLanguageStats(repo, 5)
assert.NoError(t, err) assert.NoError(t, err)
assert.Empty(t, langs) assert.Empty(t, langs)
} }

View File

@ -50,7 +50,7 @@ func TestManager_Cancel(t *testing.T) {
select { select {
case <-ctx.Done(): case <-ctx.Done():
default: default:
assert.FailNow(t, "Cancel should cancel the provided context") assert.Fail(t, "Cancel should cancel the provided context")
} }
finished() finished()
@ -62,7 +62,7 @@ func TestManager_Cancel(t *testing.T) {
select { select {
case <-ctx.Done(): case <-ctx.Done():
default: default:
assert.FailNow(t, "Cancel should cancel the provided context") assert.Fail(t, "Cancel should cancel the provided context")
} }
finished() finished()
} }

View File

@ -1777,7 +1777,6 @@ pulls.rebase_conflict_summary=Fehlermeldung
pulls.unrelated_histories=Merge fehlgeschlagen: Der Head des Merges und die Basis haben keinen gemeinsamen Verlauf. Hinweis: Versuche eine andere Strategie pulls.unrelated_histories=Merge fehlgeschlagen: Der Head des Merges und die Basis haben keinen gemeinsamen Verlauf. Hinweis: Versuche eine andere Strategie
pulls.merge_out_of_date=Merge fehlgeschlagen: Während des Mergens wurde die Basis aktualisiert. Hinweis: Versuche es erneut. pulls.merge_out_of_date=Merge fehlgeschlagen: Während des Mergens wurde die Basis aktualisiert. Hinweis: Versuche es erneut.
pulls.head_out_of_date=Mergen fehlgeschlagen: Der Head wurde aktualisiert während der Merge erstellt wurde. Tipp: Versuche es erneut. pulls.head_out_of_date=Mergen fehlgeschlagen: Der Head wurde aktualisiert während der Merge erstellt wurde. Tipp: Versuche es erneut.
pulls.has_merged=Fehler: Der Pull-Request wurde gemerged, du kannst den Zielbranch nicht wieder mergen oder ändern.
pulls.push_rejected=Mergen fehlgeschlagen: Der Push wurde abgelehnt. Überprüfe die Git Hooks für dieses Repository. pulls.push_rejected=Mergen fehlgeschlagen: Der Push wurde abgelehnt. Überprüfe die Git Hooks für dieses Repository.
pulls.push_rejected_summary=Vollständige Ablehnungsmeldung pulls.push_rejected_summary=Vollständige Ablehnungsmeldung
pulls.push_rejected_no_message=Mergen fehlgeschlagen: Der Push wurde abgelehnt, aber es gab keine Fehlermeldung.<br>Überprüfe die Git Hooks für dieses Repository pulls.push_rejected_no_message=Mergen fehlgeschlagen: Der Push wurde abgelehnt, aber es gab keine Fehlermeldung.<br>Überprüfe die Git Hooks für dieses Repository
@ -1818,7 +1817,6 @@ pulls.auto_merge_canceled_schedule_comment=`hat den Automerge für diesen Pull-R
pulls.delete.title=Diesen Pull-Request löschen? pulls.delete.title=Diesen Pull-Request löschen?
pulls.delete.text=Willst du diesen Pull-Request wirklich löschen? (Dies wird den Inhalt unwiderruflich löschen. Überlege, ob du ihn nicht lieber schließen willst, um ihn zu archivieren) pulls.delete.text=Willst du diesen Pull-Request wirklich löschen? (Dies wird den Inhalt unwiderruflich löschen. Überlege, ob du ihn nicht lieber schließen willst, um ihn zu archivieren)
pulls.recently_pushed_new_branches=Du hast auf den Branch <strong>%[1]s</strong> %[2]s gepusht
pull.deleted_branch=(gelöscht):%s pull.deleted_branch=(gelöscht):%s
@ -1828,7 +1826,6 @@ milestones.update_ago=%s aktualisiert
milestones.no_due_date=Kein Fälligkeitsdatum milestones.no_due_date=Kein Fälligkeitsdatum
milestones.open=Öffnen milestones.open=Öffnen
milestones.close=Schließen milestones.close=Schließen
milestones.new_subheader=Benutze Meilensteine, um Issues zu organisieren und den Fortschritt darzustellen.
milestones.completeness=%d%% abgeschlossen milestones.completeness=%d%% abgeschlossen
milestones.create=Meilenstein erstellen milestones.create=Meilenstein erstellen
milestones.title=Titel milestones.title=Titel
@ -1859,11 +1856,6 @@ signing.wont_sign.never=Commits werden nie signiert.
signing.wont_sign.always=Commits werden immer signiert. signing.wont_sign.always=Commits werden immer signiert.
signing.wont_sign.pubkey=Der Commit wird nicht signiert, da du keinen öffentlichen Schlüssel mit deinem Account verknüpft hast. signing.wont_sign.pubkey=Der Commit wird nicht signiert, da du keinen öffentlichen Schlüssel mit deinem Account verknüpft hast.
signing.wont_sign.twofa=Du musst Zwei-Faktor-Authentifizierung aktivieren, damit Commits signiert werden. signing.wont_sign.twofa=Du musst Zwei-Faktor-Authentifizierung aktivieren, damit Commits signiert werden.
signing.wont_sign.parentsigned=Der Commit wird nicht signiert werden, da der vorherige Commit nicht signiert ist.
signing.wont_sign.basesigned=Der Merge Commit wird nicht signiert werden, da der Basis-Commit nicht signiert ist.
signing.wont_sign.headsigned=Der Merge Commit wird nicht signiert werden, da der Head-Commit nicht signiert ist.
signing.wont_sign.commitssigned=Der Merge Commit wird nicht signiert werden, da alle zugehörigen Commits nicht signiert sind.
signing.wont_sign.approved=Der Merge Commit wird nicht signiert werden, da der Pull Request nicht genehmigt wurde.
signing.wont_sign.not_signed_in=Du bist nicht eingeloggt. signing.wont_sign.not_signed_in=Du bist nicht eingeloggt.
ext_wiki=Zugriff auf externes Wiki ext_wiki=Zugriff auf externes Wiki
@ -1996,7 +1988,6 @@ settings.mirror_settings.docs.can_still_use=Obwohl du existierende Mirrors gerad
settings.mirror_settings.docs.pull_mirror_instructions=Um einen Pull-Mirror einzurichten, konsultiere bitte: settings.mirror_settings.docs.pull_mirror_instructions=Um einen Pull-Mirror einzurichten, konsultiere bitte:
settings.mirror_settings.docs.more_information_if_disabled=Hier kannst du mehr über Push- und Pull-Mirrors erfahren: settings.mirror_settings.docs.more_information_if_disabled=Hier kannst du mehr über Push- und Pull-Mirrors erfahren:
settings.mirror_settings.docs.doc_link_title=Wie spiegele ich Repositories? settings.mirror_settings.docs.doc_link_title=Wie spiegele ich Repositories?
settings.mirror_settings.docs.doc_link_pull_section=den Abschnitt "Von einem entfernten Repository pullen" in der Dokumentation.
settings.mirror_settings.docs.pulling_remote_title=Aus einem Remote-Repository pullen settings.mirror_settings.docs.pulling_remote_title=Aus einem Remote-Repository pullen
settings.mirror_settings.mirrored_repository=Gespiegeltes Repository settings.mirror_settings.mirrored_repository=Gespiegeltes Repository
settings.mirror_settings.direction=Richtung settings.mirror_settings.direction=Richtung
@ -2006,7 +1997,6 @@ settings.mirror_settings.last_update=Letzte Aktualisierung
settings.mirror_settings.push_mirror.none=Keine Push-Mirrors konfiguriert settings.mirror_settings.push_mirror.none=Keine Push-Mirrors konfiguriert
settings.mirror_settings.push_mirror.remote_url=URL zum Git-Remote-Repository settings.mirror_settings.push_mirror.remote_url=URL zum Git-Remote-Repository
settings.mirror_settings.push_mirror.add=Push-Mirror hinzufügen settings.mirror_settings.push_mirror.add=Push-Mirror hinzufügen
settings.mirror_settings.push_mirror.edit_sync_time=Mirror-Sync-Intervall anpassen
settings.sync_mirror=Jetzt synchronisieren settings.sync_mirror=Jetzt synchronisieren
settings.pull_mirror_sync_in_progress=Aktuell werden Änderungen von %s gepullt. settings.pull_mirror_sync_in_progress=Aktuell werden Änderungen von %s gepullt.
@ -2348,7 +2338,6 @@ settings.tags.protection.allowed.teams=Erlaubte Teams
settings.tags.protection.allowed.noone=Niemand settings.tags.protection.allowed.noone=Niemand
settings.tags.protection.create=Tag schützen settings.tags.protection.create=Tag schützen
settings.tags.protection.none=Es gibt keine geschützten Tags. settings.tags.protection.none=Es gibt keine geschützten Tags.
settings.tags.protection.pattern.description=Du kannst einen einzigen Namen oder ein globales Schema oder einen regulären Ausdruck verwenden, um mehrere Tags zu schützen. Mehr dazu im <a target="_blank" rel="noopener" href="https://docs.gitea.com/usage/protected-tags">Guide für geschützte Tags (Englisch)</a>.
settings.bot_token=Bot-Token settings.bot_token=Bot-Token
settings.chat_id=Chat-ID settings.chat_id=Chat-ID
settings.thread_id=Thread-ID settings.thread_id=Thread-ID
@ -2357,7 +2346,6 @@ settings.matrix.room_id=Raum-ID
settings.matrix.message_type=Nachrichtentyp settings.matrix.message_type=Nachrichtentyp
settings.archive.button=Repo archivieren settings.archive.button=Repo archivieren
settings.archive.header=Dieses Repo archivieren settings.archive.header=Dieses Repo archivieren
settings.archive.text=Durch das Archivieren wird ein Repo vollständig schreibgeschützt. Es wird vom Dashboard versteckt. Niemand (nicht einmal du!) wird in der Lage sein, neue Commits zu erstellen oder Issues oder Pull-Requests zu öffnen.
settings.archive.success=Das Repo wurde erfolgreich archiviert. settings.archive.success=Das Repo wurde erfolgreich archiviert.
settings.archive.error=Beim Versuch, das Repository zu archivieren, ist ein Fehler aufgetreten. Weitere Details finden sich im Log. settings.archive.error=Beim Versuch, das Repository zu archivieren, ist ein Fehler aufgetreten. Weitere Details finden sich im Log.
settings.archive.error_ismirror=Du kannst keinen Repo-Mirror archivieren. settings.archive.error_ismirror=Du kannst keinen Repo-Mirror archivieren.
@ -2365,9 +2353,6 @@ settings.archive.branchsettings_unavailable=Branch-Einstellungen sind nicht verf
settings.archive.tagsettings_unavailable=Tag Einstellungen sind nicht verfügbar, wenn das Repo archiviert wurde. settings.archive.tagsettings_unavailable=Tag Einstellungen sind nicht verfügbar, wenn das Repo archiviert wurde.
settings.unarchive.button=Archivieren rückgängig machen settings.unarchive.button=Archivieren rückgängig machen
settings.unarchive.header=Archivieren dieses Repositories rückgängig machen settings.unarchive.header=Archivieren dieses Repositories rückgängig machen
settings.unarchive.text=Durch das Aufheben der Archivierung kann das Repo wieder Commits und Pushes sowie neue Issues und Pull-Requests empfangen.
settings.unarchive.success=Die Archivierung des Repos wurde erfolgreich wieder rückgängig gemacht.
settings.unarchive.error=Beim Versuch, die Archivierung des Repos aufzuheben, ist ein Fehler aufgetreten. Weitere Details finden sich im Log.
settings.update_avatar_success=Der Repository-Avatar wurde aktualisiert. settings.update_avatar_success=Der Repository-Avatar wurde aktualisiert.
settings.lfs=LFS settings.lfs=LFS
settings.lfs_filelist=LFS-Dateien, die in diesem Repository gespeichert sind settings.lfs_filelist=LFS-Dateien, die in diesem Repository gespeichert sind
@ -2434,7 +2419,6 @@ diff.show_more=Mehr anzeigen
diff.load=Diff laden diff.load=Diff laden
diff.generated=generiert diff.generated=generiert
diff.vendored=vendored diff.vendored=vendored
diff.comment.add_line_comment=Einzelnen Kommentar hinzufügen
diff.comment.placeholder=Kommentieren... diff.comment.placeholder=Kommentieren...
diff.comment.markdown_info=Styling mit Markdown wird unterstützt. diff.comment.markdown_info=Styling mit Markdown wird unterstützt.
diff.comment.add_single_comment=Einzelnen Kommentar hinzufügen diff.comment.add_single_comment=Einzelnen Kommentar hinzufügen
@ -2491,7 +2475,6 @@ release.edit_release=Release aktualisieren
release.delete_release=Release löschen release.delete_release=Release löschen
release.delete_tag=Tag löschen release.delete_tag=Tag löschen
release.deletion=Release löschen release.deletion=Release löschen
release.deletion_desc=Beim Entfernen wird ein Release nur von Gitea gelöscht. Es betrifft weder den Git-Tag, noch den Inhalt des Repos oder seinen Änderungsverlauf. Fortfahren?
release.deletion_success=Das Release wurde gelöscht. release.deletion_success=Das Release wurde gelöscht.
release.deletion_tag_desc=Löscht dieses Tag aus dem Projektarchiv. Repository-Inhalt und Verlauf bleiben unverändert. Fortfahren? release.deletion_tag_desc=Löscht dieses Tag aus dem Projektarchiv. Repository-Inhalt und Verlauf bleiben unverändert. Fortfahren?
release.deletion_tag_success=Der Tag wurde gelöscht. release.deletion_tag_success=Der Tag wurde gelöscht.
@ -2512,7 +2495,6 @@ branch.already_exists=Ein Branch mit dem Namen "%s" existiert bereits.
branch.delete_head=Löschen branch.delete_head=Löschen
branch.delete=Branch "%s" löschen branch.delete=Branch "%s" löschen
branch.delete_html=Branch löschen branch.delete_html=Branch löschen
branch.delete_desc=Das Löschen eines Branches ist permanent. Obwohl der Branch für eine kurze Zeit weiter existieren könnte, kann diese Aktion in den meisten Fällen NICHT rückgängig gemacht werden. Fortfahren?
branch.deletion_success=Branch "%s" wurde gelöscht. branch.deletion_success=Branch "%s" wurde gelöscht.
branch.deletion_failed=Branch "%s" konnte nicht gelöscht werden. branch.deletion_failed=Branch "%s" konnte nicht gelöscht werden.
branch.delete_branch_has_new_commits=Der Branch "%s" kann nicht gelöscht werden, da seit dem letzten Merge neue Commits hinzugefügt wurden. branch.delete_branch_has_new_commits=Der Branch "%s" kann nicht gelöscht werden, da seit dem letzten Merge neue Commits hinzugefügt wurden.
@ -2552,7 +2534,6 @@ tag.create_success=Tag "%s" wurde erstellt.
topic.manage_topics=Themen verwalten topic.manage_topics=Themen verwalten
topic.done=Fertig topic.done=Fertig
topic.count_prompt=Du kannst nicht mehr als 25 Themen auswählen topic.count_prompt=Du kannst nicht mehr als 25 Themen auswählen
topic.format_prompt=Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) und Punkte ('.') enthalten und bis zu 35 Zeichen lang sein. Nur Kleinbuchstaben sind zulässig.
find_file.go_to_file=Datei suchen find_file.go_to_file=Datei suchen
find_file.no_matching=Keine passende Datei gefunden find_file.no_matching=Keine passende Datei gefunden
@ -2605,7 +2586,6 @@ settings.visibility.private_shortname=Privat
settings.update_settings=Einstellungen speichern settings.update_settings=Einstellungen speichern
settings.update_setting_success=Organisationseinstellungen wurden aktualisiert. settings.update_setting_success=Organisationseinstellungen wurden aktualisiert.
settings.change_orgname_prompt=Hinweis: Das Ändern des Organisationsnamens wird auch die URL deiner Organisation ändern und den alten Namen freigeben.
settings.change_orgname_redirect_prompt=Der alte Name wird weiterleiten, bis er wieder beansprucht wird. settings.change_orgname_redirect_prompt=Der alte Name wird weiterleiten, bis er wieder beansprucht wird.
settings.update_avatar_success=Der Organisationsavatar wurde aktualisiert. settings.update_avatar_success=Der Organisationsavatar wurde aktualisiert.
settings.delete=Organisation löschen settings.delete=Organisation löschen
@ -2681,16 +2661,13 @@ teams.all_repositories_helper=Team hat Zugriff auf alle Repositories. Wenn dies
teams.all_repositories_read_permission_desc=Dieses Team gewährt <strong>Lese</strong>-Zugriff auf <strong>Repositories</strong>: Mitglieder können Repositories ansehen und klonen. teams.all_repositories_read_permission_desc=Dieses Team gewährt <strong>Lese</strong>-Zugriff auf <strong>Repositories</strong>: Mitglieder können Repositories ansehen und klonen.
teams.all_repositories_write_permission_desc=Dieses Team gewährt <strong>Schreib</strong>-Zugriff auf <strong>alle Repositories</strong>: Mitglieder können Repositories lesen und auf sie pushen. teams.all_repositories_write_permission_desc=Dieses Team gewährt <strong>Schreib</strong>-Zugriff auf <strong>alle Repositories</strong>: Mitglieder können Repositories lesen und auf sie pushen.
teams.all_repositories_admin_permission_desc=Dieses Team gewährt <strong>Administrator</strong>-Zugriff auf <strong>alle Repositories</strong>: Mitglieder können Repositories lesen, auf sie pushen und Mitwirkende zu Repositorys hinzufügen. teams.all_repositories_admin_permission_desc=Dieses Team gewährt <strong>Administrator</strong>-Zugriff auf <strong>alle Repositories</strong>: Mitglieder können Repositories lesen, auf sie pushen und Mitwirkende zu Repositorys hinzufügen.
teams.invite.title=Du wurdest eingeladen, dem Team <strong>%s</strong> in der Organisation <strong>%s</strong> beizutreten.
teams.invite.by=Von %s eingeladen teams.invite.by=Von %s eingeladen
teams.invite.description=Bitte klicke auf die folgende Schaltfläche, um dem Team beizutreten. teams.invite.description=Bitte klicke auf die folgende Schaltfläche, um dem Team beizutreten.
[admin] [admin]
dashboard=Dashboard dashboard=Dashboard
identity_access=Identität & Zugriff
users=Benutzerkonten users=Benutzerkonten
organizations=Organisationen organizations=Organisationen
assets=Code-Assets
repositories=Repositories repositories=Repositories
hooks=Webhooks hooks=Webhooks
integrations=Integrationen integrations=Integrationen
@ -2731,7 +2708,6 @@ dashboard.delete_repo_archives.started=Löschen aller Repository-Archive gestart
dashboard.delete_missing_repos=Alle Repository-Datensätze mit verloren gegangenen Git-Dateien löschen dashboard.delete_missing_repos=Alle Repository-Datensätze mit verloren gegangenen Git-Dateien löschen
dashboard.delete_missing_repos.started=Alle Repositories löschen, die den Git-File-Task nicht gestartet haben. dashboard.delete_missing_repos.started=Alle Repositories löschen, die den Git-File-Task nicht gestartet haben.
dashboard.delete_generated_repository_avatars=Generierte Repository-Avatare löschen dashboard.delete_generated_repository_avatars=Generierte Repository-Avatare löschen
dashboard.sync_repo_branches=Fehlende Branches aus den Git-Daten in die Datenbank synchronisieren
dashboard.update_mirrors=Mirrors aktualisieren dashboard.update_mirrors=Mirrors aktualisieren
dashboard.repo_health_check=Healthchecks für alle Repositories ausführen dashboard.repo_health_check=Healthchecks für alle Repositories ausführen
dashboard.check_repo_stats=Überprüfe alle Repository-Statistiken dashboard.check_repo_stats=Überprüfe alle Repository-Statistiken
@ -2748,7 +2724,6 @@ dashboard.reinit_missing_repos=Alle Git-Repositories neu einlesen, für die Eint
dashboard.sync_external_users=Externe Benutzerdaten synchronisieren dashboard.sync_external_users=Externe Benutzerdaten synchronisieren
dashboard.cleanup_hook_task_table=Hook-Task-Tabelle bereinigen dashboard.cleanup_hook_task_table=Hook-Task-Tabelle bereinigen
dashboard.cleanup_packages=Veraltete Pakete löschen dashboard.cleanup_packages=Veraltete Pakete löschen
dashboard.cleanup_actions=Abgelaufene Logs und Artefakte von Actions bereinigen
dashboard.server_uptime=Server-Uptime dashboard.server_uptime=Server-Uptime
dashboard.current_goroutine=Aktuelle Goroutinen dashboard.current_goroutine=Aktuelle Goroutinen
dashboard.current_memory_usage=Aktuelle Speichernutzung dashboard.current_memory_usage=Aktuelle Speichernutzung
@ -2786,9 +2761,6 @@ dashboard.gc_lfs=Garbage-Collection für LFS Meta-Objekte ausführen
dashboard.stop_zombie_tasks=Zombie-Aufgaben stoppen dashboard.stop_zombie_tasks=Zombie-Aufgaben stoppen
dashboard.stop_endless_tasks=Endlose Aufgaben stoppen dashboard.stop_endless_tasks=Endlose Aufgaben stoppen
dashboard.cancel_abandoned_jobs=Aufgegebene Jobs abbrechen dashboard.cancel_abandoned_jobs=Aufgegebene Jobs abbrechen
dashboard.start_schedule_tasks=Terminierte Aufgaben starten
dashboard.sync_branch.started=Synchronisierung der Branches gestartet
dashboard.rebuild_issue_indexer=Issue-Indexer neu bauen
users.user_manage_panel=Benutzerkontenverwaltung users.user_manage_panel=Benutzerkontenverwaltung
users.new_account=Benutzerkonto erstellen users.new_account=Benutzerkonto erstellen
@ -2894,12 +2866,10 @@ packages.size=Größe
packages.published=Veröffentlicht packages.published=Veröffentlicht
defaulthooks=Standard-Webhooks defaulthooks=Standard-Webhooks
defaulthooks.desc=Webhooks senden automatisch eine HTTP-POST-Anfrage an einen Server, wenn bestimmte Gitea-Events ausgelöst werden. Hier definierte Webhooks sind die Standardwerte, die in alle neuen Repositories kopiert werden. Mehr Infos findest du in der <a target="_blank" rel="noopener" href="https://docs.gitea.com/usage/webhooks">Webhooks-Anleitung</a> (auf Englisch).
defaulthooks.add_webhook=Standard-Webhook hinzufügen defaulthooks.add_webhook=Standard-Webhook hinzufügen
defaulthooks.update_webhook=Standard-Webhook aktualisieren defaulthooks.update_webhook=Standard-Webhook aktualisieren
systemhooks=System-Webhooks systemhooks=System-Webhooks
systemhooks.desc=Webhooks senden automatisch HTTP-POST-Anfragen an einen Server, wenn bestimmte Gitea-Events ausgelöst werden. Hier definierte Webhooks werden auf alle Repositories des Systems übertragen, beachte daher mögliche Performance-Einbrüche. Mehr Infos findest du in der <a target="_blank" rel="noopener" href="https://docs.gitea.com/usage/webhooks">Webhooks-Anleitung</a> (auf Englisch).
systemhooks.add_webhook=System-Webhook hinzufügen systemhooks.add_webhook=System-Webhook hinzufügen
systemhooks.update_webhook=System-Webhook aktualisieren systemhooks.update_webhook=System-Webhook aktualisieren
@ -2992,7 +2962,6 @@ auths.sspi_default_language=Standardsprache für Benutzer
auths.sspi_default_language_helper=Standardsprache für Benutzer, die automatisch mit der SSPI Authentifizierungsmethode erstellt wurden. Leer lassen, wenn du es bevorzugst, dass eine Sprache automatisch erkannt wird. auths.sspi_default_language_helper=Standardsprache für Benutzer, die automatisch mit der SSPI Authentifizierungsmethode erstellt wurden. Leer lassen, wenn du es bevorzugst, dass eine Sprache automatisch erkannt wird.
auths.tips=Tipps auths.tips=Tipps
auths.tips.oauth2.general=OAuth2-Authentifizierung auths.tips.oauth2.general=OAuth2-Authentifizierung
auths.tips.oauth2.general.tip=Beim Registrieren einer OAuth2-Anwendung sollte die Callback-URL folgendermaßen lauten:
auths.tip.oauth2_provider=OAuth2-Anbieter auths.tip.oauth2_provider=OAuth2-Anbieter
auths.tip.bitbucket=Registriere einen neuen OAuth-Consumer unter https://bitbucket.org/account/user/<dein-benutzername>/oauth-consumers/new und füge die Berechtigung „Account“ „Read“ hinzu. auths.tip.bitbucket=Registriere einen neuen OAuth-Consumer unter https://bitbucket.org/account/user/<dein-benutzername>/oauth-consumers/new und füge die Berechtigung „Account“ „Read“ hinzu.
auths.tip.nextcloud=Registriere über das "Settings -> Security -> OAuth 2.0 client"-Menü einen neuen "OAuth consumer" auf der Nextcloud-Instanz auths.tip.nextcloud=Registriere über das "Settings -> Security -> OAuth 2.0 client"-Menü einen neuen "OAuth consumer" auf der Nextcloud-Instanz
@ -3004,7 +2973,6 @@ auths.tip.google_plus=Du erhältst die OAuth2-Client-Zugangsdaten in der Google-
auths.tip.openid_connect=Benutze die OpenID-Connect-Discovery-URL (<server>/.well-known/openid-configuration), um die Endpunkte zu spezifizieren auths.tip.openid_connect=Benutze die OpenID-Connect-Discovery-URL (<server>/.well-known/openid-configuration), um die Endpunkte zu spezifizieren
auths.tip.twitter=Gehe auf https://dev.twitter.com/apps, erstelle eine Anwendung und stelle sicher, dass die Option „Allow this application to be used to Sign in with Twitter“ aktiviert ist auths.tip.twitter=Gehe auf https://dev.twitter.com/apps, erstelle eine Anwendung und stelle sicher, dass die Option „Allow this application to be used to Sign in with Twitter“ aktiviert ist
auths.tip.discord=Erstelle unter https://discordapp.com/developers/applications/me eine neue Anwendung. auths.tip.discord=Erstelle unter https://discordapp.com/developers/applications/me eine neue Anwendung.
auths.tip.gitea=Registriere eine neue OAuth2-Anwendung. Eine Anleitung findest du unter https://docs.gitea.com/development/oauth2-provider/
auths.tip.yandex=`Erstelle eine neue Anwendung auf https://oauth.yandex.com/client/new. Wähle folgende Berechtigungen aus dem "Yandex.Passport API" Bereich: "Zugriff auf E-Mail-Adresse", "Zugriff auf Benutzeravatar" und "Zugriff auf Benutzername, Vor- und Nachname, Geschlecht"` auths.tip.yandex=`Erstelle eine neue Anwendung auf https://oauth.yandex.com/client/new. Wähle folgende Berechtigungen aus dem "Yandex.Passport API" Bereich: "Zugriff auf E-Mail-Adresse", "Zugriff auf Benutzeravatar" und "Zugriff auf Benutzername, Vor- und Nachname, Geschlecht"`
auths.tip.mastodon=Gebe eine benutzerdefinierte URL für die Mastodon-Instanz ein, mit der du dich authentifizieren möchtest (oder benutze die standardmäßige) auths.tip.mastodon=Gebe eine benutzerdefinierte URL für die Mastodon-Instanz ein, mit der du dich authentifizieren möchtest (oder benutze die standardmäßige)
auths.edit=Authentifikationsquelle bearbeiten auths.edit=Authentifikationsquelle bearbeiten
@ -3186,10 +3154,8 @@ monitor.queue.name=Name
monitor.queue.type=Typ monitor.queue.type=Typ
monitor.queue.exemplar=Beispieltyp monitor.queue.exemplar=Beispieltyp
monitor.queue.numberworkers=Anzahl der Worker monitor.queue.numberworkers=Anzahl der Worker
monitor.queue.activeworkers=Aktive Worker
monitor.queue.maxnumberworkers=Maximale Anzahl der Worker monitor.queue.maxnumberworkers=Maximale Anzahl der Worker
monitor.queue.numberinqueue=Nummer in der Warteschlange monitor.queue.numberinqueue=Nummer in der Warteschlange
monitor.queue.review_add=Worker hinzufügen / prüfen
monitor.queue.settings.title=Pool-Einstellungen monitor.queue.settings.title=Pool-Einstellungen
monitor.queue.settings.desc=Pools wachsen dynamisch basierend auf der Blockierung der Arbeitswarteschlange. monitor.queue.settings.desc=Pools wachsen dynamisch basierend auf der Blockierung der Arbeitswarteschlange.
monitor.queue.settings.maxnumberworkers=Maximale Anzahl an Workern monitor.queue.settings.maxnumberworkers=Maximale Anzahl an Workern
@ -3426,17 +3392,14 @@ settings.delete.success=Das Paket wurde gelöscht.
settings.delete.error=Löschen des Pakets fehlgeschlagen. settings.delete.error=Löschen des Pakets fehlgeschlagen.
owner.settings.cargo.title=Cargo-Registry-Index owner.settings.cargo.title=Cargo-Registry-Index
owner.settings.cargo.initialize=Index initialisieren owner.settings.cargo.initialize=Index initialisieren
owner.settings.cargo.initialize.description=Ein spezielles Index-Repository wird benötigt, um die Cargo-Registry zu nutzen. Diese Option wird dieses Repository (neu) erstellen und automatisch konfigurieren.
owner.settings.cargo.initialize.error=Cargo-Index konnte nicht initialisiert werden: %v owner.settings.cargo.initialize.error=Cargo-Index konnte nicht initialisiert werden: %v
owner.settings.cargo.initialize.success=Der Cargo-Index wurde erfolgreich erstellt. owner.settings.cargo.initialize.success=Der Cargo-Index wurde erfolgreich erstellt.
owner.settings.cargo.rebuild=Index neu erstellen owner.settings.cargo.rebuild=Index neu erstellen
owner.settings.cargo.rebuild.description=Neubauen kann hilfreich sein, wenn der Index nicht mit den gespeicherten Cargo-Paketen synchronisiert ist.
owner.settings.cargo.rebuild.error=Cargo-Index konnte nicht neu erstellt werden: %v owner.settings.cargo.rebuild.error=Cargo-Index konnte nicht neu erstellt werden: %v
owner.settings.cargo.rebuild.success=Der Cargo-Index wurde erfolgreich neu erstellt. owner.settings.cargo.rebuild.success=Der Cargo-Index wurde erfolgreich neu erstellt.
owner.settings.cleanuprules.title=Bereinigungsregeln verwalten owner.settings.cleanuprules.title=Bereinigungsregeln verwalten
owner.settings.cleanuprules.add=Bereinigungsregel hinzufügen owner.settings.cleanuprules.add=Bereinigungsregel hinzufügen
owner.settings.cleanuprules.edit=Bereinigungsregel bearbeiten owner.settings.cleanuprules.edit=Bereinigungsregel bearbeiten
owner.settings.cleanuprules.none=Keine Bereinigungs-Regeln verfügbar. Bitte konsultiere die Dokumentation.
owner.settings.cleanuprules.preview=Vorschau der Bereinigungsregel owner.settings.cleanuprules.preview=Vorschau der Bereinigungsregel
owner.settings.cleanuprules.preview.overview=%d Pakete sollen entfernt werden. owner.settings.cleanuprules.preview.overview=%d Pakete sollen entfernt werden.
owner.settings.cleanuprules.preview.none=Bereinigungsregel stimmt mit keinem Paket überein. owner.settings.cleanuprules.preview.none=Bereinigungsregel stimmt mit keinem Paket überein.
@ -3455,7 +3418,6 @@ owner.settings.cleanuprules.success.update=Bereinigungsregel wurde aktualisiert.
owner.settings.cleanuprules.success.delete=Bereinigungsregel wurde gelöscht. owner.settings.cleanuprules.success.delete=Bereinigungsregel wurde gelöscht.
owner.settings.chef.title=Chef-Registry owner.settings.chef.title=Chef-Registry
owner.settings.chef.keypair=Schlüsselpaar generieren owner.settings.chef.keypair=Schlüsselpaar generieren
owner.settings.chef.keypair.description=Ein Schlüsselpaar ist notwendig, um mit der Chef-Registry zu authentifizieren. Wenn du bereits eins erstellt hast, wird dieses durch eine Neuerstellung verworfen.
[secrets] [secrets]
secrets=Secrets secrets=Secrets

View File

@ -97,7 +97,6 @@ locked=ロック済み
copy=コピー copy=コピー
copy_url=URLをコピー copy_url=URLをコピー
copy_hash=ハッシュをコピー
copy_content=内容をコピー copy_content=内容をコピー
copy_branch=ブランチ名をコピー copy_branch=ブランチ名をコピー
copy_success=コピーされました! copy_success=コピーされました!
@ -113,7 +112,6 @@ step2=ステップ 2:
error=エラー error=エラー
error404=アクセスしようとしたページは<strong>存在しない</strong>か、閲覧が<strong>許可されていません</strong>。 error404=アクセスしようとしたページは<strong>存在しない</strong>か、閲覧が<strong>許可されていません</strong>。
go_back=戻る
never=無し never=無し
unknown=不明 unknown=不明
@ -945,8 +943,6 @@ fork_from=フォーク元
already_forked=%s はフォーク済み already_forked=%s はフォーク済み
fork_to_different_account=別のアカウントにフォークする fork_to_different_account=別のアカウントにフォークする
fork_visibility_helper=フォークしたリポジトリの公開/非公開は変更できません。 fork_visibility_helper=フォークしたリポジトリの公開/非公開は変更できません。
fork_branch=フォークにクローンされるブランチ
all_branches=すべてのブランチ
fork_no_valid_owners=このリポジトリには有効なオーナーがいないため、フォークできません。 fork_no_valid_owners=このリポジトリには有効なオーナーがいないため、フォークできません。
use_template=このテンプレートを使用 use_template=このテンプレートを使用
clone_in_vsc=VSCodeでクローン clone_in_vsc=VSCodeでクローン
@ -1012,13 +1008,8 @@ delete_preexisting=既存のファイルを削除
delete_preexisting_content=%s のファイルを削除します delete_preexisting_content=%s のファイルを削除します
delete_preexisting_success=%s の未登録ファイルを削除しました delete_preexisting_success=%s の未登録ファイルを削除しました
blame_prior=この変更より前のBlameを表示 blame_prior=この変更より前のBlameを表示
blame.ignore_revs=<a href="%s">.git-blame-ignore-revs</a> で指定されたリビジョンは除外しています。 これを迂回して通常のBlame表示を見るには <a href="%s">ここ</a>をクリック。
blame.ignore_revs.failed=<a href="%s">.git-blame-ignore-revs</a> によるリビジョンの無視は失敗しました。
author_search_tooltip=最大30人までのユーザーを表示 author_search_tooltip=最大30人までのユーザーを表示
tree_path_not_found_commit=パス %[1]s はコミット %[2]s に存在しません
tree_path_not_found_branch=パス %[1]s はブランチ %[2]s に存在しません
tree_path_not_found_tag=パス %[1]s はタグ %[2]s に存在しません
transfer.accept=移転を承認 transfer.accept=移転を承認
transfer.accept_desc=`"%s" に移転` transfer.accept_desc=`"%s" に移転`
@ -1284,7 +1275,6 @@ commits.signed_by_untrusted_user=信頼できないユーザーによる署名
commits.signed_by_untrusted_user_unmatched=コミッターと一致しない信頼できないユーザーによる署名 commits.signed_by_untrusted_user_unmatched=コミッターと一致しない信頼できないユーザーによる署名
commits.gpg_key_id=GPGキーID commits.gpg_key_id=GPGキーID
commits.ssh_key_fingerprint=SSH鍵のフィンガープリント commits.ssh_key_fingerprint=SSH鍵のフィンガープリント
commits.view_path=この時点を表示
commit.operations=操作 commit.operations=操作
commit.revert=リバート commit.revert=リバート
@ -1521,8 +1511,6 @@ issues.label_description=説明
issues.label_color=カラー issues.label_color=カラー
issues.label_exclusive=排他 issues.label_exclusive=排他
issues.label_archive=アーカイブ ラベル issues.label_archive=アーカイブ ラベル
issues.label_archived_filter=アーカイブされたラベルを表示
issues.label_archive_tooltip=アーカイブされたラベルは、ラベルによる検索時のサジェストからデフォルトで除外されます。
issues.label_exclusive_desc=ラベル名を <code>スコープ/アイテム</code> の形にすることで、他の <code>スコープ/</code> ラベルと排他的になります。 issues.label_exclusive_desc=ラベル名を <code>スコープ/アイテム</code> の形にすることで、他の <code>スコープ/</code> ラベルと排他的になります。
issues.label_exclusive_warning=イシューやプルリクエストのラベル編集では、競合するスコープ付きラベルは解除されます。 issues.label_exclusive_warning=イシューやプルリクエストのラベル編集では、競合するスコープ付きラベルは解除されます。
issues.label_count=ラベル %d件 issues.label_count=ラベル %d件
@ -2009,8 +1997,6 @@ settings.mirror_settings.push_mirror.add=プッシュミラーを追加
settings.mirror_settings.push_mirror.edit_sync_time=ミラー同期の間隔を編集 settings.mirror_settings.push_mirror.edit_sync_time=ミラー同期の間隔を編集
settings.sync_mirror=今すぐ同期 settings.sync_mirror=今すぐ同期
settings.pull_mirror_sync_in_progress=現在、リモート %s から変更をプルしています。
settings.push_mirror_sync_in_progress=現在、リモート %s へ変更をプッシュしています。
settings.site=Webサイト settings.site=Webサイト
settings.update_settings=設定を更新 settings.update_settings=設定を更新
settings.update_mirror_settings=ミラーリング設定を更新 settings.update_mirror_settings=ミラーリング設定を更新

View File

@ -36,7 +36,7 @@ func parseAuthSource(ctx *context.APIContext, u *user_model.User, sourceID int64
return return
} }
source, err := auth.GetSourceByID(ctx, sourceID) source, err := auth.GetSourceByID(sourceID)
if err != nil { if err != nil {
if auth.IsErrSourceNotExist(err) { if auth.IsErrSourceNotExist(err) {
ctx.Error(http.StatusUnprocessableEntity, "", err) ctx.Error(http.StatusUnprocessableEntity, "", err)

View File

@ -70,7 +70,6 @@ import (
actions_model "code.gitea.io/gitea/models/actions" actions_model "code.gitea.io/gitea/models/actions"
auth_model "code.gitea.io/gitea/models/auth" auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
access_model "code.gitea.io/gitea/models/perm/access" access_model "code.gitea.io/gitea/models/perm/access"
@ -166,7 +165,7 @@ func repoAssignment() func(ctx *context.APIContext) {
ctx.ContextUser = owner ctx.ContextUser = owner
// Get repository. // Get repository.
repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, repoName) repo, err := repo_model.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName) redirectRepoID, err := repo_model.LookupRedirect(owner.ID, repoName)
@ -717,7 +716,7 @@ func buildAuthGroup() *auth.Group {
group.Add(&auth.ReverseProxy{}) group.Add(&auth.ReverseProxy{})
} }
if setting.IsWindows && auth_model.IsSSPIEnabled(db.DefaultContext) { if setting.IsWindows && auth_model.IsSSPIEnabled() {
group.Add(&auth.SSPI{}) // it MUST be the last, see the comment of SSPI group.Add(&auth.SSPI{}) // it MUST be the last, see the comment of SSPI
} }

View File

@ -43,7 +43,7 @@ func UpdateAvatar(ctx *context.APIContext) {
return return
} }
err = user_service.UploadAvatar(ctx, ctx.Org.Organization.AsUser(), content) err = user_service.UploadAvatar(ctx.Org.Organization.AsUser(), content)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "UploadAvatar", err) ctx.Error(http.StatusInternalServerError, "UploadAvatar", err)
} }
@ -69,7 +69,7 @@ func DeleteAvatar(ctx *context.APIContext) {
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
err := user_service.DeleteAvatar(ctx, ctx.Org.Organization.AsUser()) err := user_service.DeleteAvatar(ctx.Org.Organization.AsUser())
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err) ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err)
} }

View File

@ -638,7 +638,7 @@ func GetTeamRepo(ctx *context.APIContext) {
// getRepositoryByParams get repository by a team's organization ID and repo name // getRepositoryByParams get repository by a team's organization ID and repo name
func getRepositoryByParams(ctx *context.APIContext) *repo_model.Repository { func getRepositoryByParams(ctx *context.APIContext) *repo_model.Repository {
repo, err := repo_model.GetRepositoryByName(ctx, ctx.Org.Team.OrgID, ctx.Params(":reponame")) repo, err := repo_model.GetRepositoryByName(ctx.Org.Team.OrgID, ctx.Params(":reponame"))
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -188,7 +188,7 @@ func SearchIssues(ctx *context.APIContext) {
allPublic = true allPublic = true
opts.AllPublic = false // set it false to avoid returning too many repos, we could filter by indexer opts.AllPublic = false // set it false to avoid returning too many repos, we could filter by indexer
} }
repoIDs, _, err = repo_model.SearchRepositoryIDs(ctx, opts) repoIDs, _, err = repo_model.SearchRepositoryIDs(opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err) ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err)
return return
@ -837,7 +837,7 @@ func EditIssue(ctx *context.APIContext) {
issue.MilestoneID != *form.Milestone { issue.MilestoneID != *form.Milestone {
oldMilestoneID := issue.MilestoneID oldMilestoneID := issue.MilestoneID
issue.MilestoneID = *form.Milestone issue.MilestoneID = *form.Milestone
if err = issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil { if err = issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err) ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
return return
} }

View File

@ -576,7 +576,7 @@ func createIssueDependency(ctx *context.APIContext, target, dependency *issues_m
return return
} }
err := issues_model.CreateIssueDependency(ctx, ctx.Doer, target, dependency) err := issues_model.CreateIssueDependency(ctx.Doer, target, dependency)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "CreateIssueDependency", err) ctx.Error(http.StatusInternalServerError, "CreateIssueDependency", err)
return return
@ -602,7 +602,7 @@ func removeIssueDependency(ctx *context.APIContext, target, dependency *issues_m
return return
} }
err := issues_model.RemoveIssueDependency(ctx, ctx.Doer, target, dependency, issues_model.DependencyTypeBlockedBy) err := issues_model.RemoveIssueDependency(ctx.Doer, target, dependency, issues_model.DependencyTypeBlockedBy)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "CreateIssueDependency", err) ctx.Error(http.StatusInternalServerError, "CreateIssueDependency", err)
return return

View File

@ -105,7 +105,7 @@ func ListDeployKeys(ctx *context.APIContext) {
apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
apiKeys := make([]*api.DeployKey, len(keys)) apiKeys := make([]*api.DeployKey, len(keys))
for i := range keys { for i := range keys {
if err := keys[i].GetContent(ctx); err != nil { if err := keys[i].GetContent(); err != nil {
ctx.Error(http.StatusInternalServerError, "GetContent", err) ctx.Error(http.StatusInternalServerError, "GetContent", err)
return return
} }
@ -159,7 +159,7 @@ func GetDeployKey(ctx *context.APIContext) {
return return
} }
if err = key.GetContent(ctx); err != nil { if err = key.GetContent(); err != nil {
ctx.Error(http.StatusInternalServerError, "GetContent", err) ctx.Error(http.StatusInternalServerError, "GetContent", err)
return return
} }

View File

@ -58,7 +58,7 @@ func ListMilestones(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
milestones, total, err := issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{ milestones, total, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
ListOptions: utils.GetListOptions(ctx), ListOptions: utils.GetListOptions(ctx),
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
State: api.StateType(ctx.FormString("state")), State: api.StateType(ctx.FormString("state")),

View File

@ -555,7 +555,7 @@ func EditPullRequest(ctx *context.APIContext) {
issue.MilestoneID != form.Milestone { issue.MilestoneID != form.Milestone {
oldMilestoneID := issue.MilestoneID oldMilestoneID := issue.MilestoneID
issue.MilestoneID = form.Milestone issue.MilestoneID = form.Milestone
if err = issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil { if err = issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err) ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
return return
} }
@ -578,7 +578,7 @@ func EditPullRequest(ctx *context.APIContext) {
labels = append(labels, orgLabels...) labels = append(labels, orgLabels...)
} }
if err = issues_model.ReplaceIssueLabels(ctx, issue, labels, ctx.Doer); err != nil { if err = issues_model.ReplaceIssueLabels(issue, labels, ctx.Doer); err != nil {
ctx.Error(http.StatusInternalServerError, "ReplaceLabelsError", err) ctx.Error(http.StatusInternalServerError, "ReplaceLabelsError", err)
return return
} }

View File

@ -36,7 +36,7 @@ func UpdateAvatar(ctx *context.APIContext) {
return return
} }
err = user_service.UploadAvatar(ctx, ctx.Doer, content) err = user_service.UploadAvatar(ctx.Doer, content)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "UploadAvatar", err) ctx.Error(http.StatusInternalServerError, "UploadAvatar", err)
} }
@ -54,7 +54,7 @@ func DeleteAvatar(ctx *context.APIContext) {
// responses: // responses:
// "204": // "204":
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
err := user_service.DeleteAvatar(ctx, ctx.Doer) err := user_service.DeleteAvatar(ctx.Doer)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err) ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err)
} }

View File

@ -59,14 +59,14 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
// Querying not just listing // Querying not just listing
if username != "" { if username != "" {
// Restrict to provided uid // Restrict to provided uid
keys, err = asymkey_model.SearchPublicKey(ctx, user.ID, fingerprint) keys, err = asymkey_model.SearchPublicKey(user.ID, fingerprint)
} else { } else {
// Unrestricted // Unrestricted
keys, err = asymkey_model.SearchPublicKey(ctx, 0, fingerprint) keys, err = asymkey_model.SearchPublicKey(0, fingerprint)
} }
count = len(keys) count = len(keys)
} else { } else {
total, err2 := asymkey_model.CountPublicKeys(ctx, user.ID) total, err2 := asymkey_model.CountPublicKeys(user.ID)
if err2 != nil { if err2 != nil {
ctx.InternalServerError(err) ctx.InternalServerError(err)
return return
@ -74,7 +74,7 @@ func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
count = int(total) count = int(total)
// Use ListPublicKeys // Use ListPublicKeys
keys, err = asymkey_model.ListPublicKeys(ctx, user.ID, utils.GetListOptions(ctx)) keys, err = asymkey_model.ListPublicKeys(user.ID, utils.GetListOptions(ctx))
} }
if err != nil { if err != nil {
@ -176,7 +176,7 @@ func GetPublicKey(ctx *context.APIContext) {
// "404": // "404":
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
key, err := asymkey_model.GetPublicKeyByID(ctx, ctx.ParamsInt64(":id")) key, err := asymkey_model.GetPublicKeyByID(ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
if asymkey_model.IsErrKeyNotExist(err) { if asymkey_model.IsErrKeyNotExist(err) {
ctx.NotFound() ctx.NotFound()
@ -202,7 +202,7 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid
return return
} }
key, err := asymkey_model.AddPublicKey(ctx, uid, form.Title, content, 0) key, err := asymkey_model.AddPublicKey(uid, form.Title, content, 0)
if err != nil { if err != nil {
repo.HandleAddKeyError(ctx, err) repo.HandleAddKeyError(ctx, err)
return return
@ -262,7 +262,7 @@ func DeletePublicKey(ctx *context.APIContext) {
// "$ref": "#/responses/notFound" // "$ref": "#/responses/notFound"
id := ctx.ParamsInt64(":id") id := ctx.ParamsInt64(":id")
externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(ctx, id) externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(id)
if err != nil { if err != nil {
if asymkey_model.IsErrKeyNotExist(err) { if asymkey_model.IsErrKeyNotExist(err) {
ctx.NotFound() ctx.NotFound()

View File

@ -65,9 +65,9 @@ func RenderMarkup(ctx *context.Base, repo *context.Repository, mode, text, urlPr
meta := map[string]string{} meta := map[string]string{}
if repo != nil && repo.Repository != nil { if repo != nil && repo.Repository != nil {
if mode == "comment" { if mode == "comment" {
meta = repo.Repository.ComposeMetas(ctx) meta = repo.Repository.ComposeMetas()
} else { } else {
meta = repo.Repository.ComposeDocumentMetas(ctx) meta = repo.Repository.ComposeDocumentMetas()
} }
} }
if mode != "comment" { if mode != "comment" {

View File

@ -121,7 +121,7 @@ func InitWebInstalled(ctx context.Context) {
mustInit(cache.NewContext) mustInit(cache.NewContext)
mustInit(feed_service.Init) mustInit(feed_service.Init)
mustInit(uinotification.Init) mustInit(uinotification.Init)
mustInitCtx(ctx, archiver.Init) mustInit(archiver.Init)
highlight.NewContext() highlight.NewContext()
external.RegisterRenderers() external.RegisterRenderers()

View File

@ -83,7 +83,7 @@ func parseScope(ctx *context.PrivateContext, scope string) (ownerID, repoID int6
return ownerID, repoID, nil return ownerID, repoID, nil
} }
r, err := repo_model.GetRepositoryByName(ctx, u.ID, repoName) r, err := repo_model.GetRepositoryByName(u.ID, repoName)
if err != nil { if err != nil {
return ownerID, repoID, err return ownerID, repoID, err
} }

View File

@ -150,7 +150,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
} }
results = append(results, private.HookPostReceiveBranchResult{ results = append(results, private.HookPostReceiveBranchResult{
Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(ctx), Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
Create: false, Create: false,
Branch: "", Branch: "",
URL: fmt.Sprintf("%s/pulls/%d", repo.HTMLURL(), pr.Index), URL: fmt.Sprintf("%s/pulls/%d", repo.HTMLURL(), pr.Index),
@ -179,12 +179,12 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
}) })
return return
} }
if repo.BaseRepo.AllowsPulls(ctx) { if repo.BaseRepo.AllowsPulls() {
baseRepo = repo.BaseRepo baseRepo = repo.BaseRepo
} }
} }
if !baseRepo.AllowsPulls(ctx) { if !baseRepo.AllowsPulls() {
// We can stop there's no need to go any further // We can stop there's no need to go any further
ctx.JSON(http.StatusOK, private.HookPostReceiveResult{ ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
RepoWasEmpty: wasEmpty, RepoWasEmpty: wasEmpty,
@ -217,14 +217,14 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch) branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
} }
results = append(results, private.HookPostReceiveBranchResult{ results = append(results, private.HookPostReceiveBranchResult{
Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(ctx), Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(),
Create: true, Create: true,
Branch: branch, Branch: branch,
URL: fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)), URL: fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
}) })
} else { } else {
results = append(results, private.HookPostReceiveBranchResult{ results = append(results, private.HookPostReceiveBranchResult{
Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(ctx), Message: setting.Git.PullRequestPushMessage && baseRepo.AllowsPulls(),
Create: false, Create: false,
Branch: branch, Branch: branch,
URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index), URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),

View File

@ -16,7 +16,7 @@ import (
func UpdatePublicKeyInRepo(ctx *context.PrivateContext) { func UpdatePublicKeyInRepo(ctx *context.PrivateContext) {
keyID := ctx.ParamsInt64(":id") keyID := ctx.ParamsInt64(":id")
repoID := ctx.ParamsInt64(":repoid") repoID := ctx.ParamsInt64(":repoid")
if err := asymkey_model.UpdatePublicKeyUpdated(ctx, keyID); err != nil { if err := asymkey_model.UpdatePublicKeyUpdated(keyID); err != nil {
ctx.JSON(http.StatusInternalServerError, private.Response{ ctx.JSON(http.StatusInternalServerError, private.Response{
Err: err.Error(), Err: err.Error(),
}) })

View File

@ -33,7 +33,7 @@ func ServNoCommand(ctx *context.PrivateContext) {
} }
results := private.KeyAndOwner{} results := private.KeyAndOwner{}
key, err := asymkey_model.GetPublicKeyByID(ctx, keyID) key, err := asymkey_model.GetPublicKeyByID(keyID)
if err != nil { if err != nil {
if asymkey_model.IsErrKeyNotExist(err) { if asymkey_model.IsErrKeyNotExist(err) {
ctx.JSON(http.StatusUnauthorized, private.Response{ ctx.JSON(http.StatusUnauthorized, private.Response{
@ -132,7 +132,7 @@ func ServCommand(ctx *context.PrivateContext) {
// Now get the Repository and set the results section // Now get the Repository and set the results section
repoExist := true repoExist := true
repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, results.RepoName) repo, err := repo_model.GetRepositoryByName(owner.ID, results.RepoName)
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
repoExist = false repoExist = false
@ -184,7 +184,7 @@ func ServCommand(ctx *context.PrivateContext) {
} }
// Get the Public Key represented by the keyID // Get the Public Key represented by the keyID
key, err := asymkey_model.GetPublicKeyByID(ctx, keyID) key, err := asymkey_model.GetPublicKeyByID(keyID)
if err != nil { if err != nil {
if asymkey_model.IsErrKeyNotExist(err) { if asymkey_model.IsErrKeyNotExist(err) {
ctx.JSON(http.StatusNotFound, private.Response{ ctx.JSON(http.StatusNotFound, private.Response{

View File

@ -48,13 +48,13 @@ func Authentications(ctx *context.Context) {
ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["PageIsAdminAuthentications"] = true
var err error var err error
ctx.Data["Sources"], err = auth.Sources(ctx) ctx.Data["Sources"], err = auth.Sources()
if err != nil { if err != nil {
ctx.ServerError("auth.Sources", err) ctx.ServerError("auth.Sources", err)
return return
} }
ctx.Data["Total"] = auth.CountSources(ctx) ctx.Data["Total"] = auth.CountSources()
ctx.HTML(http.StatusOK, tplAuths) ctx.HTML(http.StatusOK, tplAuths)
} }
@ -284,7 +284,7 @@ func NewAuthSourcePost(ctx *context.Context) {
ctx.RenderWithErr(err.Error(), tplAuthNew, form) ctx.RenderWithErr(err.Error(), tplAuthNew, form)
return return
} }
existing, err := auth.SourcesByType(ctx, auth.SSPI) existing, err := auth.SourcesByType(auth.SSPI)
if err != nil || len(existing) > 0 { if err != nil || len(existing) > 0 {
ctx.Data["Err_Type"] = true ctx.Data["Err_Type"] = true
ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_of_type_exist"), tplAuthNew, form) ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_of_type_exist"), tplAuthNew, form)
@ -301,7 +301,7 @@ func NewAuthSourcePost(ctx *context.Context) {
return return
} }
if err := auth.CreateSource(ctx, &auth.Source{ if err := auth.CreateSource(&auth.Source{
Type: auth.Type(form.Type), Type: auth.Type(form.Type),
Name: form.Name, Name: form.Name,
IsActive: form.IsActive, IsActive: form.IsActive,
@ -337,7 +337,7 @@ func EditAuthSource(ctx *context.Context) {
oauth2providers := oauth2.GetOAuth2Providers() oauth2providers := oauth2.GetOAuth2Providers()
ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["OAuth2Providers"] = oauth2providers
source, err := auth.GetSourceByID(ctx, ctx.ParamsInt64(":authid")) source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid"))
if err != nil { if err != nil {
ctx.ServerError("auth.GetSourceByID", err) ctx.ServerError("auth.GetSourceByID", err)
return return
@ -371,7 +371,7 @@ func EditAuthSourcePost(ctx *context.Context) {
oauth2providers := oauth2.GetOAuth2Providers() oauth2providers := oauth2.GetOAuth2Providers()
ctx.Data["OAuth2Providers"] = oauth2providers ctx.Data["OAuth2Providers"] = oauth2providers
source, err := auth.GetSourceByID(ctx, ctx.ParamsInt64(":authid")) source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid"))
if err != nil { if err != nil {
ctx.ServerError("auth.GetSourceByID", err) ctx.ServerError("auth.GetSourceByID", err)
return return
@ -421,7 +421,7 @@ func EditAuthSourcePost(ctx *context.Context) {
source.IsActive = form.IsActive source.IsActive = form.IsActive
source.IsSyncEnabled = form.IsSyncEnabled source.IsSyncEnabled = form.IsSyncEnabled
source.Cfg = config source.Cfg = config
if err := auth.UpdateSource(ctx, source); err != nil { if err := auth.UpdateSource(source); err != nil {
if auth.IsErrSourceAlreadyExist(err) { if auth.IsErrSourceAlreadyExist(err) {
ctx.Data["Err_Name"] = true ctx.Data["Err_Name"] = true
ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(auth.ErrSourceAlreadyExist).Name), tplAuthEdit, form) ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(auth.ErrSourceAlreadyExist).Name), tplAuthEdit, form)
@ -442,7 +442,7 @@ func EditAuthSourcePost(ctx *context.Context) {
// DeleteAuthSource response for deleting an auth source // DeleteAuthSource response for deleting an auth source
func DeleteAuthSource(ctx *context.Context) { func DeleteAuthSource(ctx *context.Context) {
source, err := auth.GetSourceByID(ctx, ctx.ParamsInt64(":authid")) source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid"))
if err != nil { if err != nil {
ctx.ServerError("auth.GetSourceByID", err) ctx.ServerError("auth.GetSourceByID", err)
return return

View File

@ -90,7 +90,7 @@ func NewUser(ctx *context.Context) {
ctx.Data["login_type"] = "0-0" ctx.Data["login_type"] = "0-0"
sources, err := auth.Sources(ctx) sources, err := auth.Sources()
if err != nil { if err != nil {
ctx.ServerError("auth.Sources", err) ctx.ServerError("auth.Sources", err)
return return
@ -109,7 +109,7 @@ func NewUserPost(ctx *context.Context) {
ctx.Data["DefaultUserVisibilityMode"] = setting.Service.DefaultUserVisibilityMode ctx.Data["DefaultUserVisibilityMode"] = setting.Service.DefaultUserVisibilityMode
ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice() ctx.Data["AllowedUserVisibilityModes"] = setting.Service.AllowedUserVisibilityModesSlice.ToVisibleTypeSlice()
sources, err := auth.Sources(ctx) sources, err := auth.Sources()
if err != nil { if err != nil {
ctx.ServerError("auth.Sources", err) ctx.ServerError("auth.Sources", err)
return return
@ -221,7 +221,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User {
ctx.Data["User"] = u ctx.Data["User"] = u
if u.LoginSource > 0 { if u.LoginSource > 0 {
ctx.Data["LoginSource"], err = auth.GetSourceByID(ctx, u.LoginSource) ctx.Data["LoginSource"], err = auth.GetSourceByID(u.LoginSource)
if err != nil { if err != nil {
ctx.ServerError("auth.GetSourceByID", err) ctx.ServerError("auth.GetSourceByID", err)
return nil return nil
@ -230,7 +230,7 @@ func prepareUserInfo(ctx *context.Context) *user_model.User {
ctx.Data["LoginSource"] = &auth.Source{} ctx.Data["LoginSource"] = &auth.Source{}
} }
sources, err := auth.Sources(ctx) sources, err := auth.Sources()
if err != nil { if err != nil {
ctx.ServerError("auth.Sources", err) ctx.ServerError("auth.Sources", err)
return nil return nil
@ -532,7 +532,7 @@ func DeleteAvatar(ctx *context.Context) {
return return
} }
if err := user_service.DeleteAvatar(ctx, u); err != nil { if err := user_service.DeleteAvatar(u); err != nil {
ctx.Flash.Error(err.Error()) ctx.Flash.Error(err.Error())
} }

View File

@ -157,7 +157,7 @@ func SignIn(ctx *context.Context) {
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
ctx.Data["PageIsSignIn"] = true ctx.Data["PageIsSignIn"] = true
ctx.Data["PageIsLogin"] = true ctx.Data["PageIsLogin"] = true
ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx) ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled()
if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin { if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
context.SetCaptchaData(ctx) context.SetCaptchaData(ctx)
@ -181,7 +181,7 @@ func SignInPost(ctx *context.Context) {
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
ctx.Data["PageIsSignIn"] = true ctx.Data["PageIsSignIn"] = true
ctx.Data["PageIsLogin"] = true ctx.Data["PageIsLogin"] = true
ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx) ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled()
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(http.StatusOK, tplSignIn) ctx.HTML(http.StatusOK, tplSignIn)

View File

@ -152,7 +152,7 @@ func LinkAccountPostSignIn(ctx *context.Context) {
} }
func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, remember bool) { func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, remember bool) {
updateAvatarIfNeed(ctx, gothUser.AvatarURL, u) updateAvatarIfNeed(gothUser.AvatarURL, u)
// If this user is enrolled in 2FA, we can't sign the user in just yet. // If this user is enrolled in 2FA, we can't sign the user in just yet.
// Instead, redirect them to the 2FA authentication page. // Instead, redirect them to the 2FA authentication page.

View File

@ -1074,7 +1074,7 @@ func showLinkingLogin(ctx *context.Context, gothUser goth.User) {
ctx.Redirect(setting.AppSubURL + "/user/link_account") ctx.Redirect(setting.AppSubURL + "/user/link_account")
} }
func updateAvatarIfNeed(ctx *context.Context, url string, u *user_model.User) { func updateAvatarIfNeed(url string, u *user_model.User) {
if setting.OAuth2Client.UpdateAvatar && len(url) > 0 { if setting.OAuth2Client.UpdateAvatar && len(url) > 0 {
resp, err := http.Get(url) resp, err := http.Get(url)
if err == nil { if err == nil {
@ -1086,14 +1086,14 @@ func updateAvatarIfNeed(ctx *context.Context, url string, u *user_model.User) {
if err == nil && resp.StatusCode == http.StatusOK { if err == nil && resp.StatusCode == http.StatusOK {
data, err := io.ReadAll(io.LimitReader(resp.Body, setting.Avatar.MaxFileSize+1)) data, err := io.ReadAll(io.LimitReader(resp.Body, setting.Avatar.MaxFileSize+1))
if err == nil && int64(len(data)) <= setting.Avatar.MaxFileSize { if err == nil && int64(len(data)) <= setting.Avatar.MaxFileSize {
_ = user_service.UploadAvatar(ctx, u, data) _ = user_service.UploadAvatar(u, data)
} }
} }
} }
} }
func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model.User, gothUser goth.User) { func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model.User, gothUser goth.User) {
updateAvatarIfNeed(ctx, gothUser.AvatarURL, u) updateAvatarIfNeed(gothUser.AvatarURL, u)
needs2FA := false needs2FA := false
if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA { if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA {

View File

@ -37,14 +37,6 @@ func WebAuthn(ctx *context.Context) {
return return
} }
hasTwoFactor, err := auth.HasTwoFactorByUID(ctx, ctx.Session.Get("twofaUid").(int64))
if err != nil {
ctx.ServerError("HasTwoFactorByUID", err)
return
}
ctx.Data["HasTwoFactor"] = hasTwoFactor
ctx.HTML(http.StatusOK, tplWebAuthn) ctx.HTML(http.StatusOK, tplWebAuthn)
} }

View File

@ -102,7 +102,7 @@ func Code(ctx *context.Context) {
} }
} }
repoMaps, err := repo_model.GetRepositoriesMapByIDs(ctx, loadRepoIDs) repoMaps, err := repo_model.GetRepositoriesMapByIDs(loadRepoIDs)
if err != nil { if err != nil {
ctx.ServerError("GetRepositoriesMapByIDs", err) ctx.ServerError("GetRepositoriesMapByIDs", err)
return return

View File

@ -290,7 +290,7 @@ func releasesToFeedItems(ctx *context.Context, releases []*repo_model.Release, i
content, err = markdown.RenderString(&markup.RenderContext{ content, err = markdown.RenderString(&markup.RenderContext{
Ctx: ctx, Ctx: ctx,
URLPrefix: rel.Repo.Link(), URLPrefix: rel.Repo.Link(),
Metas: rel.Repo.ComposeMetas(ctx), Metas: rel.Repo.ComposeMetas(),
}, rel.Note) }, rel.Note)
if err != nil { if err != nil {

View File

@ -468,7 +468,7 @@ func UpdateIssueProject(ctx *context.Context) {
} }
} }
if err := issues_model.ChangeProjectAssign(ctx, issue, ctx.Doer, projectID); err != nil { if err := issues_model.ChangeProjectAssign(issue, ctx.Doer, projectID); err != nil {
ctx.ServerError("ChangeProjectAssign", err) ctx.ServerError("ChangeProjectAssign", err)
return return
} }

View File

@ -160,7 +160,7 @@ func SettingsAvatar(ctx *context.Context) {
// SettingsDeleteAvatar response for delete avatar on settings page // SettingsDeleteAvatar response for delete avatar on settings page
func SettingsDeleteAvatar(ctx *context.Context) { func SettingsDeleteAvatar(ctx *context.Context) {
if err := user_service.DeleteAvatar(ctx, ctx.Org.Organization.AsUser()); err != nil { if err := user_service.DeleteAvatar(ctx.Org.Organization.AsUser()); err != nil {
ctx.Flash.Error(err.Error()) ctx.Flash.Error(err.Error())
} }

View File

@ -237,7 +237,7 @@ func TeamsRepoAction(ctx *context.Context) {
case "add": case "add":
repoName := path.Base(ctx.FormString("repo_name")) repoName := path.Base(ctx.FormString("repo_name"))
var repo *repo_model.Repository var repo *repo_model.Repository
repo, err = repo_model.GetRepositoryByName(ctx, ctx.Org.Organization.ID, repoName) repo, err = repo_model.GetRepositoryByName(ctx.Org.Organization.ID, repoName)
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
ctx.Flash.Error(ctx.Tr("org.teams.add_nonexistent_repo")) ctx.Flash.Error(ctx.Tr("org.teams.add_nonexistent_repo"))

View File

@ -37,7 +37,7 @@ const (
func Branches(ctx *context.Context) { func Branches(ctx *context.Context) {
ctx.Data["Title"] = "Branches" ctx.Data["Title"] = "Branches"
ctx.Data["IsRepoToolbarBranches"] = true ctx.Data["IsRepoToolbarBranches"] = true
ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls(ctx) ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls()
ctx.Data["IsWriter"] = ctx.Repo.CanWrite(unit.TypeCode) ctx.Data["IsWriter"] = ctx.Repo.CanWrite(unit.TypeCode)
ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror
ctx.Data["CanPull"] = ctx.Repo.CanWrite(unit.TypeCode) || ctx.Data["CanPull"] = ctx.Repo.CanWrite(unit.TypeCode) ||

View File

@ -32,7 +32,6 @@ import (
"code.gitea.io/gitea/modules/markup" "code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/typesniffer"
"code.gitea.io/gitea/modules/upload" "code.gitea.io/gitea/modules/upload"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/services/gitdiff" "code.gitea.io/gitea/services/gitdiff"
@ -61,21 +60,6 @@ func setCompareContext(ctx *context.Context, before, head *git.Commit, headOwner
return blob return blob
} }
ctx.Data["GetSniffedTypeForBlob"] = func(blob *git.Blob) typesniffer.SniffedType {
st := typesniffer.SniffedType{}
if blob == nil {
return st
}
st, err := blob.GuessContentType()
if err != nil {
log.Error("GuessContentType failed: %v", err)
return st
}
return st
}
setPathsCompareContext(ctx, before, head, headOwner, headName) setPathsCompareContext(ctx, before, head, headOwner, headName)
setImageCompareContext(ctx) setImageCompareContext(ctx)
setCsvCompareContext(ctx) setCsvCompareContext(ctx)
@ -103,7 +87,16 @@ func setPathsCompareContext(ctx *context.Context, base, head *git.Commit, headOw
// setImageCompareContext sets context data that is required by image compare template // setImageCompareContext sets context data that is required by image compare template
func setImageCompareContext(ctx *context.Context) { func setImageCompareContext(ctx *context.Context) {
ctx.Data["IsSniffedTypeAnImage"] = func(st typesniffer.SniffedType) bool { ctx.Data["IsBlobAnImage"] = func(blob *git.Blob) bool {
if blob == nil {
return false
}
st, err := blob.GuessContentType()
if err != nil {
log.Error("GuessContentType failed: %v", err)
return false
}
return st.IsImage() && (setting.UI.SVG.Enabled || !st.IsSvgImage()) return st.IsImage() && (setting.UI.SVG.Enabled || !st.IsSvgImage())
} }
} }

View File

@ -105,7 +105,7 @@ func httpBase(ctx *context.Context) *serviceHandler {
} }
repoExist := true repoExist := true
repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, reponame) repo, err := repo_model.GetRepositoryByName(owner.ID, reponame)
if err != nil { if err != nil {
if repo_model.IsErrRepoNotExist(err) { if repo_model.IsErrRepoNotExist(err) {
if redirectRepoID, err := repo_model.LookupRedirect(owner.ID, reponame); err == nil { if redirectRepoID, err := repo_model.LookupRedirect(owner.ID, reponame); err == nil {

View File

@ -495,7 +495,7 @@ func Issues(ctx *context.Context) {
func renderMilestones(ctx *context.Context) { func renderMilestones(ctx *context.Context) {
// Get milestones // Get milestones
milestones, _, err := issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{ milestones, _, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
State: api.StateAll, State: api.StateAll,
}) })
@ -519,7 +519,7 @@ func renderMilestones(ctx *context.Context) {
// RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.Repository) { func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.Repository) {
var err error var err error
ctx.Data["OpenMilestones"], _, err = issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{ ctx.Data["OpenMilestones"], _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
RepoID: repo.ID, RepoID: repo.ID,
State: api.StateOpen, State: api.StateOpen,
}) })
@ -527,7 +527,7 @@ func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *repo_model.R
ctx.ServerError("GetMilestones", err) ctx.ServerError("GetMilestones", err)
return return
} }
ctx.Data["ClosedMilestones"], _, err = issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{ ctx.Data["ClosedMilestones"], _, err = issues_model.GetMilestones(issues_model.GetMilestonesOption{
RepoID: repo.ID, RepoID: repo.ID,
State: api.StateClosed, State: api.StateClosed,
}) })
@ -1229,7 +1229,7 @@ func NewIssuePost(ctx *context.Context) {
ctx.Error(http.StatusBadRequest, "user hasn't permissions to read projects") ctx.Error(http.StatusBadRequest, "user hasn't permissions to read projects")
return return
} }
if err := issues_model.ChangeProjectAssign(ctx, issue, ctx.Doer, projectID); err != nil { if err := issues_model.ChangeProjectAssign(issue, ctx.Doer, projectID); err != nil {
ctx.ServerError("ChangeProjectAssign", err) ctx.ServerError("ChangeProjectAssign", err)
return return
} }
@ -1332,7 +1332,7 @@ func ViewIssue(ctx *context.Context) {
extIssueUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit.TypeExternalTracker) extIssueUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit.TypeExternalTracker)
if err == nil && extIssueUnit != nil { if err == nil && extIssueUnit != nil {
if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" { if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" {
metas := ctx.Repo.Repository.ComposeMetas(ctx) metas := ctx.Repo.Repository.ComposeMetas()
metas["index"] = ctx.Params(":index") metas["index"] = ctx.Params(":index")
res, err := vars.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas) res, err := vars.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas)
if err != nil { if err != nil {
@ -1425,7 +1425,7 @@ func ViewIssue(ctx *context.Context) {
issue.RenderedContent, err = markdown.RenderString(&markup.RenderContext{ issue.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
URLPrefix: ctx.Repo.RepoLink, URLPrefix: ctx.Repo.RepoLink,
Metas: ctx.Repo.Repository.ComposeMetas(ctx), Metas: ctx.Repo.Repository.ComposeMetas(),
GitRepo: ctx.Repo.GitRepo, GitRepo: ctx.Repo.GitRepo,
Ctx: ctx, Ctx: ctx,
}, issue.Content) }, issue.Content)
@ -1588,7 +1588,7 @@ func ViewIssue(ctx *context.Context) {
comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{ comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
URLPrefix: ctx.Repo.RepoLink, URLPrefix: ctx.Repo.RepoLink,
Metas: ctx.Repo.Repository.ComposeMetas(ctx), Metas: ctx.Repo.Repository.ComposeMetas(),
GitRepo: ctx.Repo.GitRepo, GitRepo: ctx.Repo.GitRepo,
Ctx: ctx, Ctx: ctx,
}, comment.Content) }, comment.Content)
@ -1665,7 +1665,7 @@ func ViewIssue(ctx *context.Context) {
} else if comment.Type.HasContentSupport() { } else if comment.Type.HasContentSupport() {
comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{ comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
URLPrefix: ctx.Repo.RepoLink, URLPrefix: ctx.Repo.RepoLink,
Metas: ctx.Repo.Repository.ComposeMetas(ctx), Metas: ctx.Repo.Repository.ComposeMetas(),
GitRepo: ctx.Repo.GitRepo, GitRepo: ctx.Repo.GitRepo,
Ctx: ctx, Ctx: ctx,
}, comment.Content) }, comment.Content)
@ -1909,7 +1909,7 @@ func ViewIssue(ctx *context.Context) {
if pull.HasMerged || issue.IsClosed || !ctx.IsSigned { if pull.HasMerged || issue.IsClosed || !ctx.IsSigned {
return false return false
} }
if pull.CanAutoMerge() || pull.IsWorkInProgress(ctx) || pull.IsChecking() { if pull.CanAutoMerge() || pull.IsWorkInProgress() || pull.IsChecking() {
return false return false
} }
if (ctx.Doer.IsAdmin || ctx.Repo.IsAdmin()) && prConfig.AllowManualMerge { if (ctx.Doer.IsAdmin || ctx.Repo.IsAdmin()) && prConfig.AllowManualMerge {
@ -2223,7 +2223,7 @@ func UpdateIssueContent(ctx *context.Context) {
content, err := markdown.RenderString(&markup.RenderContext{ content, err := markdown.RenderString(&markup.RenderContext{
URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ? URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ?
Metas: ctx.Repo.Repository.ComposeMetas(ctx), Metas: ctx.Repo.Repository.ComposeMetas(),
GitRepo: ctx.Repo.GitRepo, GitRepo: ctx.Repo.GitRepo,
Ctx: ctx, Ctx: ctx,
}, issue.Content) }, issue.Content)
@ -2286,7 +2286,7 @@ func UpdateIssueMilestone(ctx *context.Context) {
continue continue
} }
issue.MilestoneID = milestoneID issue.MilestoneID = milestoneID
if err := issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil { if err := issue_service.ChangeMilestoneAssign(issue, ctx.Doer, oldMilestoneID); err != nil {
ctx.ServerError("ChangeMilestoneAssign", err) ctx.ServerError("ChangeMilestoneAssign", err)
return return
} }
@ -2536,7 +2536,7 @@ func SearchIssues(ctx *context.Context) {
allPublic = true allPublic = true
opts.AllPublic = false // set it false to avoid returning too many repos, we could filter by indexer opts.AllPublic = false // set it false to avoid returning too many repos, we could filter by indexer
} }
repoIDs, _, err = repo_model.SearchRepositoryIDs(ctx, opts) repoIDs, _, err = repo_model.SearchRepositoryIDs(opts)
if err != nil { if err != nil {
ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err.Error()) ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err.Error())
return return
@ -3127,7 +3127,7 @@ func UpdateCommentContent(ctx *context.Context) {
content, err := markdown.RenderString(&markup.RenderContext{ content, err := markdown.RenderString(&markup.RenderContext{
URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ? URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ?
Metas: ctx.Repo.Repository.ComposeMetas(ctx), Metas: ctx.Repo.Repository.ComposeMetas(),
GitRepo: ctx.Repo.GitRepo, GitRepo: ctx.Repo.GitRepo,
Ctx: ctx, Ctx: ctx,
}, comment.Content) }, comment.Content)

View File

@ -72,7 +72,7 @@ func AddDependency(ctx *context.Context) {
return return
} }
err = issues_model.CreateIssueDependency(ctx, ctx.Doer, issue, dep) err = issues_model.CreateIssueDependency(ctx.Doer, issue, dep)
if err != nil { if err != nil {
if issues_model.IsErrDependencyExists(err) { if issues_model.IsErrDependencyExists(err) {
ctx.Flash.Error(ctx.Tr("repo.issues.dependency.add_error_dep_exists")) ctx.Flash.Error(ctx.Tr("repo.issues.dependency.add_error_dep_exists"))
@ -131,7 +131,7 @@ func RemoveDependency(ctx *context.Context) {
return return
} }
if err = issues_model.RemoveIssueDependency(ctx, ctx.Doer, issue, dep, depType); err != nil { if err = issues_model.RemoveIssueDependency(ctx.Doer, issue, dep, depType); err != nil {
if issues_model.IsErrDependencyNotExists(err) { if issues_model.IsErrDependencyNotExists(err) {
ctx.Flash.Error(ctx.Tr("repo.issues.dependency.add_error_dep_not_exist")) ctx.Flash.Error(ctx.Tr("repo.issues.dependency.add_error_dep_not_exist"))
return return

View File

@ -29,7 +29,7 @@ func LockIssue(ctx *context.Context) {
return return
} }
if err := issues_model.LockIssue(ctx, &issues_model.IssueLockOptions{ if err := issues_model.LockIssue(&issues_model.IssueLockOptions{
Doer: ctx.Doer, Doer: ctx.Doer,
Issue: issue, Issue: issue,
Reason: form.Reason, Reason: form.Reason,
@ -53,7 +53,7 @@ func UnlockIssue(ctx *context.Context) {
return return
} }
if err := issues_model.UnlockIssue(ctx, &issues_model.IssueLockOptions{ if err := issues_model.UnlockIssue(&issues_model.IssueLockOptions{
Doer: ctx.Doer, Doer: ctx.Doer,
Issue: issue, Issue: issue,
}); err != nil { }); err != nil {

View File

@ -50,7 +50,7 @@ func Milestones(ctx *context.Context) {
state = structs.StateClosed state = structs.StateClosed
} }
miles, total, err := issues_model.GetMilestones(ctx, issues_model.GetMilestonesOption{ miles, total, err := issues_model.GetMilestones(issues_model.GetMilestonesOption{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: page, Page: page,
PageSize: setting.UI.IssuePagingNum, PageSize: setting.UI.IssuePagingNum,
@ -82,7 +82,7 @@ func Milestones(ctx *context.Context) {
for _, m := range miles { for _, m := range miles {
m.RenderedContent, err = markdown.RenderString(&markup.RenderContext{ m.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
URLPrefix: ctx.Repo.RepoLink, URLPrefix: ctx.Repo.RepoLink,
Metas: ctx.Repo.Repository.ComposeMetas(ctx), Metas: ctx.Repo.Repository.ComposeMetas(),
GitRepo: ctx.Repo.GitRepo, GitRepo: ctx.Repo.GitRepo,
Ctx: ctx, Ctx: ctx,
}, m.Content) }, m.Content)
@ -275,7 +275,7 @@ func MilestoneIssuesAndPulls(ctx *context.Context) {
milestone.RenderedContent, err = markdown.RenderString(&markup.RenderContext{ milestone.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
URLPrefix: ctx.Repo.RepoLink, URLPrefix: ctx.Repo.RepoLink,
Metas: ctx.Repo.Repository.ComposeMetas(ctx), Metas: ctx.Repo.Repository.ComposeMetas(),
GitRepo: ctx.Repo.GitRepo, GitRepo: ctx.Repo.GitRepo,
Ctx: ctx, Ctx: ctx,
}, milestone.Content) }, milestone.Content)

Some files were not shown because too many files have changed in this diff Show More