Compare commits

..

30 Commits

Author SHA1 Message Date
Loïc Dachary f8641c7909 Merge pull request '[DOCS] RELEASE-NOTES: relevant repositories' (#478) from earl-warren/forgejo:wip-1.19-release-notes-relevant into forgejo-development
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/478
2023-03-12 09:10:37 +00:00
Earl Warren 5b7f94dc11 Merge pull request '[ACTIONS] forgejo actions --registration-token-admin' (#505) from earl-warren/forgejo:wip-runner into forgejo-development
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/505
2023-03-11 07:22:52 +00:00
Loïc Dachary 402c979125 Merge pull request '[DOCS] RELEASE-NOTES: 1.19.0-0 is really : 1.19.0-2' (#509) from earl-warren/forgejo:wip-1.19-release-notes into forgejo-development
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/509
2023-03-10 17:21:56 +00:00
Earl Warren de6ed5b87f
[DOCS] RELEASE-NOTES: relevant repositories 2023-03-10 18:01:21 +01:00
Earl Warren 60d770c2c9
[DOCS] RELEASE-NOTES: 1.19.0-0 is really : 1.19.0-2 2023-03-10 17:20:01 +01:00
Loïc Dachary da8b1ed282 Merge pull request '[DOCS] RELEASE-NOTES: cosmetic improvements' (#507) from dachary/forgejo:doc-release-notes-1.19.0 into forgejo-development
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/507
2023-03-10 15:15:56 +00:00
Loïc Dachary b93df350d9
[DOCS] RELEASE-NOTES: cosmetic improvements 2023-03-10 15:31:35 +01:00
Earl Warren 5a0428ede3
do not run initDB within integration tests 2023-03-09 14:46:23 +01:00
Earl Warren dc4eb0ea17 Merge pull request '[DOCS] RELEASE-NOTES: webhook authorization header' (#479) from earl-warren/forgejo:wip-1.19-release-notes-webhooks into forgejo-development
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/479
2023-03-09 13:28:05 +00:00
Earl Warren 6621b04458
s/Printf/Print/ 2023-03-09 13:36:39 +01:00
Earl Warren d8f313f9e2
address oliverpool comments 2023-03-09 11:36:26 +01:00
Earl Warren 481d813539
[ACTIONS] forgejo actions --registration-token-admin 2023-03-09 11:02:59 +01:00
Loïc Dachary bc4ecc7025 Merge pull request '[DOCS] RELEASE-NOTES: move scoped labels to the documentation' (#496) from earl-warren/forgejo:wip-1.19-release-notes-labels into forgejo-development
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/496
2023-03-06 10:21:30 +00:00
Loïc Dachary 300139ee53 Merge pull request '[DOCS] RELEASE-NOTES: video element in markdown' (#495) from earl-warren/forgejo:wip-1.19-release-notes-video into forgejo-development
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/495
2023-03-06 10:20:16 +00:00
Earl Warren c5eedaf4f3
[DOCS] RELEASE-NOTES: move scoped labels to the documentation 2023-03-06 10:43:59 +01:00
Earl Warren bcb0bd51d2
[DOCS] RELEASE-NOTES: video element in markdown 2023-03-06 10:27:49 +01:00
Earl Warren c35e2c4f6f
[DOCS] RELEASE-NOTES: webhook authorization header 2023-03-05 21:59:49 +01:00
Loïc Dachary ad08ca9955
[DOCS] RELEASE-NOTES: 1.19.0-0-rc0
(cherry picked from commit e84e43887b)

[DOCS] RELEASE-NOTES: add scoped access tokens

(cherry picked from commit 688f831853)

[DOCS] RELEASE-NOTES: Scoped labels

(cherry picked from commit 747479a07b)

[DOCS] RELEASE-NOTES: OIDC groups

(cherry picked from commit 10c505fe89)

[DOCS] RELEASE-NOTES: Copy Link is broken

On firefox it fails with Uncaught TypeError: navigator.clipboard is
   undefined
On chromium it fails with Uncaught TypeError: Cannot read properties of undefined (reading 'writeText')

(cherry picked from commit 148b2ff093)

[DOCS] RELEASE-NOTES: Copy citation

(cherry picked from commit d0f217735f)

[DOCS] RELEASE-NOTES: Support org/user level projects

(cherry picked from commit de845c7bcf)

[DOCS] RELEASE-NOTES: v1.19 has a documentation

(cherry picked from commit 9a5b46da32)

[DOCS] RELEASE-NOTES: do not split webhook section

(cherry picked from commit 00ed020321)

[DOCS] RELEASE-NOTES: Incoming emails

(cherry picked from commit 06c455b33b)

[DOCS] RELEASE-NOTES: secrets are an implementation detail

(cherry picked from commit 8236dc3a57)

[DOCS] RELEASE-NOTES: Prohibit fork if user reached maximum

(cherry picked from commit 0f80b8c696)

[DOCS] RELEASE-NOTES: scoped tokens: do not duplicate the docs

(cherry picked from commit 9bc4793c07)

[DOCS] RELEASE-NOTES: rss feed for tags and releases

(cherry picked from commit 599b36fada)

[DOCS] RELEASE-NOTES: protected branches wildcard

(cherry picked from commit 2b316c4950)

[DOCS] RELEASE-NOTES: disable releases

(cherry picked from commit 9a60773f1d)

[DOCS] RELEASE-NOTES: review box

(cherry picked from commit 09867dd122)

[DOCS] RELEASE-NOTES: asciicast support

(cherry picked from commit ea9658379b)

[DOCS] RELEASE-NOTES: attention blocks

(cherry picked from commit 70b387750b)

[DOCS] RELEASE-NOTES: commit cross reference

(cherry picked from commit fe706dad13)

[DOCS] RELEASE-NOTES: strip user completion border case

(cherry picked from commit 33ca51b4b6)

[DOCS] RELEASE-NOTES: card preview

(cherry picked from commit 626cd78ca6)

[DOCS] RELEASE-NOTES: raw copy button

(cherry picked from commit edfb467d64)

[DOCS] RELEASE-NOTES: allow edits by maintainers by default

(cherry picked from commit 7006405bc6)

[DOCS] RELEASE-NOTES: database auto migration is a little arcane

(cherry picked from commit 78030fa9af)

[DOCS] RELEASE-NOTES: fix typos & minor rewording

(cherry picked from commit ae1d47f656)
2023-03-05 20:28:14 +01:00
Loïc Dachary bd2a5fa292
[SECURITY] default to pbkdf2 with 320,000 iterations
(cherry picked from commit 3ea0b287d7)
(cherry picked from commit db8392a8ac)
2023-03-05 20:28:11 +01:00
Earl Warren 5ea2309851
[API] Forgejo API /api/forgejo/v1
(cherry picked from commit 20b5669269)
(cherry picked from commit 1574643a6a)

Update semantic version according to specification

(cherry picked from commit 22510f4130)

Mise à jour de 'Makefile'

(cherry picked from commit c3d85d8409)
2023-03-05 20:28:07 +01:00
Percy Ma e7fbfb34a9
[DOCS] LICENSE: add Forgejo Authors
(cherry picked from commit 7c98a4c54e)
(cherry picked from commit 1ec4a8e6cf)
(cherry picked from commit 79de60a5d8)
2023-03-05 20:28:06 +01:00
Loïc Dachary ca85c880b4
[DOCS] RELEASE-NOTES.md
(cherry picked from commit b07123ee7b)
2023-03-05 20:28:06 +01:00
Loïc Dachary b90dc5fc4f
[WORKFLOW] issues & pr templates
(cherry picked from commit 9dd224f00c)
(cherry picked from commit 710af007bc)
(cherry picked from commit 2ccd6e2bd6)
2023-03-05 20:28:06 +01:00
Loïc Dachary b90ffbb309
[DOCS] README
(cherry picked from commit a47b474586)
(cherry picked from commit 2fcc61c1d9)
(cherry picked from commit 67debe2247)
2023-03-05 20:28:06 +01:00
Loïc Dachary 5df52b8a4f
[DOCS] CONTRIBUTING
Refs: https://codeberg.org/forgejo/forgejo/issues/8
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/153
Refs: https://codeberg.org/forgejo/forgejo/issues/123
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/299
(cherry picked from commit 08dcef0c8c)

[DOCS] CONTRIBUTING/RELEASE: https://forgejo.org/docs/admin

Because the version is not displayed on the landing page of Forgejo,
there cannot be a link to a versionned documentation. There must exist
a link that points to the latest version on the website for the
forgejo instance to display.

Better but more complicated approaches could be to:

* Embed the documentation in Forgejo
* Allow the admin to not display the help
* Allow the admin to display a versionned help or not

(cherry picked from commit 83cc389239)
2023-03-05 20:27:49 +01:00
Loïc Dachary d17fe25e2f
delete Gitea specific files that need rewriting for Forgejo
Although it would be possible to modify these files, it would create
conflicts when rebasing. Instead, this commit removes them entirely
and another commit can start from scratch, borrowing content from the
original files.

The drawback of this approach is that some content updates from Gitea
that also need updating in Forgejo will have to be copy/pasted
instead of being merged.

(cherry picked from commit eb85782115)
(cherry picked from commit 34401f2004)
(cherry picked from commit ef43b1c691)
2023-03-05 20:22:28 +01:00
Loïc Dachary 0b81815209
[CI] set PASSWORD_HASH_ALGO = argon2 for integration tests
(cherry picked from commit 1d7ce2a39c)
(cherry picked from commit 3af8757583)
2023-03-05 19:11:42 +01:00
Loïc Dachary e7673e5d22
[CI] implementation: forgejo container images
(cherry picked from commit dd1971d4e6)
(cherry picked from commit 3981dbaf8c)
(cherry picked from commit 8dff3cc2d1)
2023-03-05 19:11:42 +01:00
Loïc Dachary 63608a221e
[CI] implementation: Woodpecker based CI
(cherry picked from commit c2a7aaeee8)
(cherry picked from commit 6b6007fbce)
2023-03-05 19:11:41 +01:00
Loïc Dachary ef232fa20c
[CI] implementation: publish forgejo- binaries instead of gitea-
(cherry picked from commit 6d910daafb)
(cherry picked from commit d447861cc9)
(cherry picked from commit dc6e9d8799)
2023-03-05 19:11:41 +01:00
346 changed files with 2165 additions and 5925 deletions

View File

@ -32,7 +32,6 @@ steps:
pull: always
commands:
- make deps-backend
- make deps-tools
volumes:
- name: deps
path: /go
@ -169,112 +168,7 @@ steps:
---
kind: pipeline
type: docker
name: testing-pgsql
platform:
os: linux
arch: amd64
depends_on:
- compliance
trigger:
event:
- push
- tag
- pull_request
paths:
exclude:
- docs/**
volumes:
- name: deps
temp: {}
services:
- name: pgsql
pull: default
image: postgres:15
environment:
POSTGRES_DB: test
POSTGRES_PASSWORD: postgres
- name: ldap
image: gitea/test-openldap:latest
pull: always
- name: minio
image: minio/minio:RELEASE.2021-03-12T00-00-47Z
pull: always
commands:
- minio server /data
environment:
MINIO_ACCESS_KEY: 123456
MINIO_SECRET_KEY: 12345678
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git config --global --add safe.directory /drone/src
- git fetch --tags --force
when:
event:
exclude:
- pull_request
- name: deps-backend
image: golang:1.20
pull: always
commands:
- make deps-backend
volumes:
- name: deps
path: /go
- name: prepare-test-env
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
pull: always
commands:
- ./build/test-env-prepare.sh
- name: build
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- ./build/test-env-check.sh
- make backend
environment:
GOPROXY: https://goproxy.io # proxy.golang.org is blocked in China, this proxy is not
GOSUMDB: sum.golang.org
TAGS: bindata
depends_on: [deps-backend, prepare-test-env]
volumes:
- name: deps
path: /go
- name: test-pgsql
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- timeout -s ABRT 50m make test-pgsql-migration test-pgsql
environment:
GOPROXY: https://goproxy.io
TAGS: bindata gogit
RACE_ENABLED: true
TEST_TAGS: gogit
TEST_LDAP: 1
USE_REPO_TEST_DIR: 1
depends_on: [build]
volumes:
- name: deps
path: /go
---
kind: pipeline
type: docker
name: testing-mysql
name: testing-amd64
platform:
os: linux
@ -304,12 +198,40 @@ services:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: test
- name: mysql8
image: mysql:8
pull: always
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: testgitea
- name: mssql
image: mcr.microsoft.com/mssql/server:latest
pull: always
environment:
ACCEPT_EULA: Y
MSSQL_PID: Standard
SA_PASSWORD: MwantsaSecurePassword1
- name: ldap
image: gitea/test-openldap:latest
pull: always
- name: elasticsearch
image: elasticsearch:7.5.0
pull: always
environment:
discovery.type: single-node
- name: minio
image: minio/minio:RELEASE.2021-03-12T00-00-47Z
pull: always
commands:
- minio server /data
environment:
MINIO_ACCESS_KEY: 123456
MINIO_SECRET_KEY: 12345678
- name: smtpimap
image: tabascoterrier/docker-imap-devel:latest
pull: always
@ -335,6 +257,12 @@ steps:
- name: deps
path: /go
- name: tag-pre-condition
image: drone/git
pull: always
commands:
- git update-ref refs/heads/tag_test ${DRONE_COMMIT_SHA}
- name: prepare-test-env
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
pull: always
@ -350,7 +278,7 @@ steps:
environment:
GOPROXY: https://goproxy.io # proxy.golang.org is blocked in China, this proxy is not
GOSUMDB: sum.golang.org
TAGS: bindata
TAGS: bindata sqlite sqlite_unlock_notify
depends_on: [deps-backend, prepare-test-env]
volumes:
- name: deps
@ -363,7 +291,7 @@ steps:
- make unit-test-coverage test-check
environment:
GOPROXY: https://goproxy.io
TAGS: bindata
TAGS: bindata sqlite sqlite_unlock_notify
RACE_ENABLED: true
GITHUB_READ_TOKEN:
from_secret: github_read_token
@ -379,7 +307,7 @@ steps:
- make unit-test-coverage test-check
environment:
GOPROXY: https://goproxy.io
TAGS: bindata gogit
TAGS: bindata gogit sqlite sqlite_unlock_notify
RACE_ENABLED: true
GITHUB_READ_TOKEN:
from_secret: github_read_token
@ -397,6 +325,7 @@ steps:
GOPROXY: https://goproxy.io
TAGS: bindata
RACE_ENABLED: true
TEST_LDAP: 1
USE_REPO_TEST_DIR: 1
TEST_INDEXER_CODE_ES_URL: "http://elastic:changeme@elasticsearch:9200"
depends_on: [build]
@ -404,6 +333,38 @@ steps:
- name: deps
path: /go
- name: test-mysql8
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- timeout -s ABRT 50m make test-mysql8-migration test-mysql8
environment:
GOPROXY: https://goproxy.io
TAGS: bindata
RACE_ENABLED: true
TEST_LDAP: 1
USE_REPO_TEST_DIR: 1
depends_on: [build]
volumes:
- name: deps
path: /go
- name: test-mssql
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- make test-mssql-migration test-mssql
environment:
GOPROXY: https://goproxy.io
TAGS: bindata
RACE_ENABLED: true
TEST_LDAP: 1
USE_REPO_TEST_DIR: 1
depends_on: [build]
volumes:
- name: deps
path: /go
- name: generate-coverage
image: golang:1.20
commands:
@ -437,186 +398,7 @@ steps:
---
kind: pipeline
type: docker
name: testing-mysql8
platform:
os: linux
arch: amd64
depends_on:
- compliance
trigger:
event:
- push
- tag
- pull_request
paths:
exclude:
- docs/**
volumes:
- name: deps
temp: {}
services:
- name: mysql8
image: mysql:8
pull: always
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: testgitea
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git config --global --add safe.directory /drone/src
- git fetch --tags --force
when:
event:
exclude:
- pull_request
- name: deps-backend
image: golang:1.20
pull: always
commands:
- make deps-backend
volumes:
- name: deps
path: /go
- name: prepare-test-env
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
pull: always
commands:
- ./build/test-env-prepare.sh
- name: build
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- ./build/test-env-check.sh
- make backend
environment:
GOPROXY: https://goproxy.io # proxy.golang.org is blocked in China, this proxy is not
GOSUMDB: sum.golang.org
TAGS: bindata
depends_on: [deps-backend, prepare-test-env]
volumes:
- name: deps
path: /go
- name: test-mysql8
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- timeout -s ABRT 50m make test-mysql8-migration test-mysql8
environment:
GOPROXY: https://goproxy.io
TAGS: bindata
USE_REPO_TEST_DIR: 1
depends_on: [build]
volumes:
- name: deps
path: /go
---
kind: pipeline
type: docker
name: testing-mssql
platform:
os: linux
arch: amd64
depends_on:
- compliance
trigger:
event:
- push
- tag
- pull_request
paths:
exclude:
- docs/**
volumes:
- name: deps
temp: {}
services:
- name: mssql
image: mcr.microsoft.com/mssql/server:latest
pull: always
environment:
ACCEPT_EULA: Y
MSSQL_PID: Standard
SA_PASSWORD: MwantsaSecurePassword1
steps:
- name: fetch-tags
image: docker:git
pull: always
commands:
- git config --global --add safe.directory /drone/src
- git fetch --tags --force
when:
event:
exclude:
- pull_request
- name: deps-backend
image: golang:1.20
pull: always
commands:
- make deps-backend
volumes:
- name: deps
path: /go
- name: prepare-test-env
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
pull: always
commands:
- ./build/test-env-prepare.sh
- name: build
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- ./build/test-env-check.sh
- make backend
environment:
GOPROXY: https://goproxy.io # proxy.golang.org is blocked in China, this proxy is not
GOSUMDB: sum.golang.org
TAGS: bindata
depends_on: [deps-backend, prepare-test-env]
volumes:
- name: deps
path: /go
- name: test-mssql
image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- make test-mssql-migration test-mssql
environment:
GOPROXY: https://goproxy.io
TAGS: bindata
USE_REPO_TEST_DIR: 1
depends_on: [build]
volumes:
- name: deps
path: /go
---
kind: pipeline
name: testing-sqlite
name: testing-arm64
platform:
os: linux
@ -638,6 +420,18 @@ volumes:
- name: deps
temp: {}
services:
- name: pgsql
pull: default
image: postgres:10
environment:
POSTGRES_DB: test
POSTGRES_PASSWORD: postgres
- name: ldap
pull: default
image: gitea/test-openldap:latest
steps:
- name: fetch-tags
image: docker:git
@ -696,6 +490,23 @@ steps:
- name: deps
path: /go
- name: test-pgsql
image: gitea/test_env:linux-arm64 # https://gitea.com/gitea/test-env
user: gitea
commands:
- timeout -s ABRT 50m make test-pgsql-migration test-pgsql
environment:
GOPROXY: https://goproxy.io
TAGS: bindata gogit
RACE_ENABLED: true
TEST_TAGS: gogit
TEST_LDAP: 1
USE_REPO_TEST_DIR: 1
depends_on: [build]
volumes:
- name: deps
path: /go
---
kind: pipeline
type: docker
@ -719,6 +530,15 @@ volumes:
- name: deps
temp: {}
services:
- name: pgsql
pull: default
image: postgres:10
environment:
POSTGRES_DB: testgitea-e2e
POSTGRES_PASSWORD: postgres
POSTGRES_INITDB_ARGS: --encoding=UTF8 --lc-collate='en_US.UTF-8' --lc-ctype='en_US.UTF-8'
steps:
- name: deps-frontend
image: node:18
@ -748,12 +568,14 @@ steps:
- curl -sLO https://go.dev/dl/go1.20.linux-amd64.tar.gz && tar -C /usr/local -xzf go1.20.linux-amd64.tar.gz
- groupadd --gid 1001 gitea && useradd -m --gid 1001 --uid 1001 gitea
- apt-get -qq update && apt-get -qqy install build-essential
- export TEST_PGSQL_SCHEMA=''
- ./build/test-env-prepare.sh
- su gitea bash -c "export PATH=$PATH:/usr/local/go/bin && timeout -s ABRT 40m make test-e2e-sqlite"
- su gitea bash -c "export PATH=$PATH:/usr/local/go/bin && timeout -s ABRT 40m make test-e2e-pgsql"
environment:
GOPROXY: https://goproxy.io
GOSUMDB: sum.golang.org
USE_REPO_TEST_DIR: 1
TEST_PGSQL_DBNAME: 'testgitea-e2e'
DEBIAN_FRONTEND: noninteractive
depends_on: [build-frontend, deps-backend]
volumes:
@ -887,11 +709,8 @@ trigger:
- docs/**
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
volumes:
- name: deps
@ -1023,11 +842,8 @@ trigger:
- tag
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-arm64
- testing-amd64
volumes:
- name: deps
@ -1178,11 +994,8 @@ platform:
arch: amd64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1206,7 +1019,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
auto_tag: true
@ -1218,17 +1031,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: true
@ -1240,10 +1049,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1259,11 +1064,8 @@ platform:
arch: amd64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1284,7 +1086,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
tags: ${DRONE_TAG##v}-linux-amd64
@ -1295,17 +1097,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
tags: ${DRONE_TAG##v}-linux-amd64-rootless
@ -1316,10 +1114,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1335,11 +1129,8 @@ platform:
arch: amd64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1357,7 +1148,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
auto_tag: false
@ -1369,17 +1160,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: false
@ -1391,10 +1178,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1409,11 +1192,8 @@ platform:
arch: amd64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1431,7 +1211,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
auto_tag: false
@ -1443,17 +1223,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: false
@ -1465,10 +1241,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1477,7 +1249,7 @@ steps:
---
kind: pipeline
type: docker
name: docker-linux-amd64-dry-run
name: docker-linux-arm64-dry-run
platform:
os: linux
@ -1495,7 +1267,7 @@ trigger:
steps:
- name: dryrun
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
dry_run: true
@ -1506,7 +1278,6 @@ steps:
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
- pull_request
@ -1521,11 +1292,8 @@ platform:
arch: arm64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1549,7 +1317,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
auto_tag: true
@ -1561,17 +1329,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: true
@ -1583,10 +1347,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1602,11 +1362,8 @@ platform:
arch: arm64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1627,7 +1384,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
tags: ${DRONE_TAG##v}-linux-arm64
@ -1638,17 +1395,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
tags: ${DRONE_TAG##v}-linux-arm64-rootless
@ -1659,10 +1412,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1678,11 +1427,8 @@ platform:
arch: arm64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1703,7 +1449,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
auto_tag: false
@ -1715,17 +1461,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: false
@ -1737,10 +1479,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1755,11 +1493,8 @@ platform:
arch: arm64
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
trigger:
ref:
@ -1777,7 +1512,7 @@ steps:
- git fetch --tags --force
- name: publish
image: plugins/docker:latest
image: techknowlogick/drone-docker:latest
pull: always
settings:
auto_tag: false
@ -1789,17 +1524,13 @@ steps:
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
image: techknowlogick/drone-docker:latest
settings:
dockerfile: Dockerfile.rootless
auto_tag: false
@ -1811,10 +1542,6 @@ steps:
from_secret: docker_password
username:
from_secret: docker_username
environment:
PLUGIN_MIRROR:
from_secret: plugin_mirror
DOCKER_BUILDKIT: 1
when:
event:
exclude:
@ -1880,6 +1607,7 @@ platform:
steps:
- name: manifest-rootless
pull: always
image: plugins/manifest
pull: always
settings:
@ -1943,11 +1671,8 @@ trigger:
- failure
depends_on:
- testing-mysql
- testing-mysql8
- testing-mssql
- testing-pgsql
- testing-sqlite
- testing-amd64
- testing-arm64
- release-version
- release-latest
- docker-linux-amd64-release

3
.gitignore vendored
View File

@ -115,6 +115,3 @@ prime/
# Manpage
/man
# Generated merged Forgejo+Gitea language files
/options/locale/locale_*

View File

@ -1,18 +1,12 @@
plugins:
- stylelint-declaration-strict-value
ignoreFiles:
- "**/*.go"
overrides:
- files: ["**/*.less"]
customSyntax: postcss-less
- files: ["**/chroma/*", "**/codemirror/*", "**/standalone/*", "**/console/*"]
rules:
scale-unlimited/declaration-strict-value: null
- files: ["**/chroma/*", "**/codemirror/*"]
rules:
block-no-empty: null
rules:
alpha-value-notation: null

View File

@ -75,14 +75,6 @@ pipeline:
commands:
- ./build/test-env-prepare.sh
environment-to-ini:
image: *golang_image
environment:
GOPROXY_OVERRIDE: *goproxy_override
commands:
- *goproxy_setup
- go test contrib/environment-to-ini/environment-to-ini.go contrib/environment-to-ini/environment-to-ini_test.go
build:
image: *test_image
environment:

View File

@ -1,96 +0,0 @@
# Gitea Community Code of Conduct
## About
Online communities include people from many different backgrounds. The Gitea contributors are committed to providing a friendly, safe and welcoming environment for all, regardless of gender identity and expression, sexual orientation, disabilities, neurodiversity, physical appearance, body size, ethnicity, nationality, race, age, religion, or similar personal characteristics.
The first goal of the Code of Conduct is to specify a baseline standard of behavior so that people with different social values and communication styles can talk about Gitea effectively, productively, and respectfully.
The second goal is to provide a mechanism for resolving conflicts in the community when they arise.
The third goal of the Code of Conduct is to make our community welcoming to people from different backgrounds. Diversity is critical to the project; for Gitea to be successful, it needs contributors and users from all backgrounds.
We believe that healthy debate and disagreement are essential to a healthy project and community. However, it is never ok to be disrespectful. We value diverse opinions, but we value respectful behavior more.
## Community values
These are the values to which people in the Gitea community should aspire.
- **Be friendly and welcoming.**
- **Be patient.**
- Remember that people have varying communication styles and that not everyone is using their native language. (Meaning and tone can be lost in translation.)
- **Be thoughtful.**
- Productive communication requires effort. Think about how your words will be interpreted.
- Remember that sometimes it is best to refrain entirely from commenting.
- **Be respectful.**
- In particular, respect differences of opinion.
- **Be charitable.**
- Interpret the arguments of others in good faith, do not seek to disagree.
- When we do disagree, try to understand why.
- **Be constructive.**
- Avoid derailing: stay on topic; if you want to talk about something else, start a new conversation.
- Avoid unconstructive criticism: don't merely decry the current state of affairs; offer—or at least solicit—suggestions as to how things may be improved.
- Avoid snarking (pithy, unproductive, sniping comments)
- Avoid discussing potentially offensive or sensitive issues; this all too often leads to unnecessary conflict.
- Avoid microaggressions (brief and commonplace verbal, behavioral and environmental indignities that communicate hostile, derogatory or negative slights and insults to a person or group).
- **Be responsible.**
- What you say and do matters. Take responsibility for your words and actions, including their consequences, whether intended or otherwise.
People are complicated. You should expect to be misunderstood and to misunderstand others; when this inevitably occurs, resist the urge to be defensive or assign blame. Try not to take offense where no offense was intended. Give people the benefit of the doubt. Even if the intent was to provoke, do not rise to it. It is the responsibility of all parties to de-escalate conflict when it arises.
## Code of Conduct
### Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject: comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, as well as to ban (temporarily or permanently) any contributor for behaviors that they deem inappropriate, threatening, offensive, or harmful.
### Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
This Code of Conduct also applies outside the project spaces when the Project Stewards have a reasonable belief that an individuals behavior may have a negative impact on the project or its community.
### Conflict Resolution
We do not believe that all conflict is bad; healthy debate and disagreement often yield positive results. However, it is never okay to be disrespectful or to engage in behavior that violates the projects code of conduct.
If you see someone violating the code of conduct, you are encouraged to address the behavior directly with those involved. Many issues can be resolved quickly and easily, and this gives people more control over the outcome of their dispute. If you are unable to resolve the matter for any reason, or if the behavior is threatening or harassing, report it. We are dedicated to providing an environment where participants feel welcome and safe.
Reports should be directed to the Gitea Project Stewards at conduct@gitea.com. It is the Project Stewards duty to receive and address reported violations of the code of conduct. They will then work with a committee consisting of representatives from the technical-oversight-committee.
We will investigate every complaint, but you may not receive a direct response. We will use our discretion in determining when and how to follow up on reported incidents, which may range from not taking action to permanent expulsion from the project and project-sponsored spaces. Under normal circumstances, we will notify the accused of the report and provide them an opportunity to discuss it before any action is taken. If there is a consensus between maintainers that such an endeavor would be useless (i.e. in case of an obvious spammer), we reserve the right to take action without notifying the accused first. The identity of the reporter will be omitted from the details of the report supplied to the accused. In potentially harmful situations, such as ongoing harassment or threats to anyones safety, we may take action without notice.
### Attribution
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
## Summary
- Treat everyone with respect and kindness.
- Be thoughtful in how you communicate.
- Dont be destructive or inflammatory.
- If you encounter an issue, please mail conduct@gitea.com.

View File

@ -62,7 +62,6 @@ ENTRYPOINT ["/usr/bin/entrypoint"]
CMD ["/bin/s6-svscan", "/etc/s6"]
COPY docker/root /
RUN cd /usr/local/bin ; ln -s gitea forgejo
COPY --from=build-env /go/src/code.gitea.io/gitea/gitea /app/gitea/gitea
COPY --from=build-env /go/src/code.gitea.io/gitea/environment-to-ini /usr/local/bin/environment-to-ini
COPY --from=build-env /go/src/code.gitea.io/gitea/contrib/autocompletion/bash_autocomplete /etc/profile.d/gitea_bash_autocomplete.sh

View File

@ -52,7 +52,6 @@ RUN mkdir -p /var/lib/gitea /etc/gitea
RUN chown git:git /var/lib/gitea /etc/gitea
COPY docker/rootless /
RUN cd /usr/local/bin ; ln -s gitea forgejo
COPY --from=build-env --chown=root:root /go/src/code.gitea.io/gitea/gitea /app/gitea/gitea
COPY --from=build-env --chown=root:root /go/src/code.gitea.io/gitea/environment-to-ini /usr/local/bin/environment-to-ini
COPY --from=build-env /go/src/code.gitea.io/gitea/contrib/autocompletion/bash_autocomplete /etc/profile.d/gitea_bash_autocomplete.sh

View File

@ -158,7 +158,6 @@ SWAGGER_SPEC_S_TMPL := s|"basePath": *"/api/v1"|"basePath": "{{AppSubUrl \| JSEs
SWAGGER_SPEC_S_JSON := s|"basePath": *"{{AppSubUrl \| JSEscape \| Safe}}/api/v1"|"basePath": "/api/v1"|g
SWAGGER_EXCLUDE := code.gitea.io/sdk
SWAGGER_NEWLINE_COMMAND := -e '$$a\'
SWAGGER_SPEC_BRANDING := s|Gitea API|Forgejo API|g
TEST_MYSQL_HOST ?= mysql:3306
TEST_MYSQL_DBNAME ?= testgitea
@ -196,7 +195,6 @@ help:
@echo " - deps install dependencies"
@echo " - deps-frontend install frontend dependencies"
@echo " - deps-backend install backend dependencies"
@echo " - deps-tools install tool dependencies"
@echo " - lint lint everything"
@echo " - lint-frontend lint frontend files"
@echo " - lint-backend lint backend files"
@ -334,7 +332,6 @@ $(SWAGGER_SPEC): $(GO_SOURCES_NO_BINDATA)
$(GO) run $(SWAGGER_PACKAGE) generate spec -x "$(SWAGGER_EXCLUDE)" -o './$(SWAGGER_SPEC)'
$(SED_INPLACE) '$(SWAGGER_SPEC_S_TMPL)' './$(SWAGGER_SPEC)'
$(SED_INPLACE) $(SWAGGER_NEWLINE_COMMAND) './$(SWAGGER_SPEC)'
$(SED_INPLACE) '$(SWAGGER_SPEC_BRANDING)' './$(SWAGGER_SPEC)'
.PHONY: swagger-check
swagger-check: generate-swagger
@ -769,14 +766,10 @@ generate: generate-backend
generate-backend: $(TAGS_PREREQ) generate-go
.PHONY: generate-go
generate-go: $(TAGS_PREREQ) merge-locales
generate-go: $(TAGS_PREREQ)
@echo "Running go generate..."
@CC= GOOS= GOARCH= $(GO) generate -tags '$(TAGS)' $(GO_PACKAGES)
.PHONY: merge-locales
merge-locales:
$(GO) run build/merge-forgejo-locales.go
.PHONY: security-check
security-check:
go run $(GOVULNCHECK_PACKAGE) -v ./...
@ -855,7 +848,7 @@ docs:
cd docs; make trans-copy clean build-offline;
.PHONY: deps
deps: deps-frontend deps-backend deps-tools
deps: deps-frontend deps-backend
.PHONY: deps-frontend
deps-frontend: node_modules
@ -863,9 +856,6 @@ deps-frontend: node_modules
.PHONY: deps-backend
deps-backend:
$(GO) mod download
.PHONY: deps-tools
deps-tools:
$(GO) install $(AIR_PACKAGE)
$(GO) install $(EDITORCONFIG_CHECKER_PACKAGE)
$(GO) install $(ERRCHECK_PACKAGE)
@ -938,7 +928,13 @@ lockfile-check:
.PHONY: update-translations
update-translations:
# noop to detect merge conflicts (potentially needs updating the scripts) and avoid breaking with Gitea
mkdir -p ./translations
cd ./translations && curl -L https://crowdin.com/download/project/gitea.zip > gitea.zip && unzip gitea.zip
rm ./translations/gitea.zip
$(SED_INPLACE) -e 's/="/=/g' -e 's/"$$//g' ./translations/*.ini
$(SED_INPLACE) -e 's/\\"/"/g' ./translations/*.ini
mv ./translations/*.ini ./options/locale/
rmdir ./translations
.PHONY: generate-license
generate-license:

View File

@ -1,5 +1,5 @@
<div align="center">
<img src="./assets/logo.svg" alt="" width="192" align="center" />
<img src="https://codeberg.org/forgejo/meta/raw/branch/readme/logo/forgejo.svg" alt="" width="192" align="center" />
<h1 align="center">Welcome to Forgejo</h1>
</div>

View File

@ -1,27 +1,31 @@
<svg viewBox="0 0 212 212" xmlns="http://www.w3.org/2000/svg">
<style type="text/css">
circle {
fill: none;
stroke: #000;
stroke-width: 15;
}
path {
fill: none;
stroke: #000;
stroke-width: 25;
}
.orange {
stroke:#ff6600;
}
.red {
stroke:#d40000;
}
</style>
<g transform="translate(6,6)">
<path d="M58 168 v-98 a50 50 0 0 1 50-50 h20" class="orange" />
<path d="M58 168 v-30 a50 50 0 0 1 50-50 h20" class="red" />
<circle cx="142" cy="20" r="18" class="orange" />
<circle cx="142" cy="88" r="18" class="red" />
<circle cx="58" cy="180" r="18" class="red" />
</g>
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="main_outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" viewBox="0 0 640 640" style="enable-background:new 0 0 640 640;" xml:space="preserve">
<g>
<path id="teabag" style="fill:#FFFFFF" d="M395.9,484.2l-126.9-61c-12.5-6-17.9-21.2-11.8-33.8l61-126.9c6-12.5,21.2-17.9,33.8-11.8
c17.2,8.3,27.1,13,27.1,13l-0.1-109.2l16.7-0.1l0.1,117.1c0,0,57.4,24.2,83.1,40.1c3.7,2.3,10.2,6.8,12.9,14.4
c2.1,6.1,2,13.1-1,19.3l-61,126.9C423.6,484.9,408.4,490.3,395.9,484.2z"/>
<g>
<g>
<path style="fill:#609926" d="M622.7,149.8c-4.1-4.1-9.6-4-9.6-4s-117.2,6.6-177.9,8c-13.3,0.3-26.5,0.6-39.6,0.7c0,39.1,0,78.2,0,117.2
c-5.5-2.6-11.1-5.3-16.6-7.9c0-36.4-0.1-109.2-0.1-109.2c-29,0.4-89.2-2.2-89.2-2.2s-141.4-7.1-156.8-8.5
c-9.8-0.6-22.5-2.1-39,1.5c-8.7,1.8-33.5,7.4-53.8,26.9C-4.9,212.4,6.6,276.2,8,285.8c1.7,11.7,6.9,44.2,31.7,72.5
c45.8,56.1,144.4,54.8,144.4,54.8s12.1,28.9,30.6,55.5c25,33.1,50.7,58.9,75.7,62c63,0,188.9-0.1,188.9-0.1s12,0.1,28.3-10.3
c14-8.5,26.5-23.4,26.5-23.4s12.9-13.8,30.9-45.3c5.5-9.7,10.1-19.1,14.1-28c0,0,55.2-117.1,55.2-231.1
C633.2,157.9,624.7,151.8,622.7,149.8z M125.6,353.9c-25.9-8.5-36.9-18.7-36.9-18.7S69.6,321.8,60,295.4
c-16.5-44.2-1.4-71.2-1.4-71.2s8.4-22.5,38.5-30c13.8-3.7,31-3.1,31-3.1s7.1,59.4,15.7,94.2c7.2,29.2,24.8,77.7,24.8,77.7
S142.5,359.9,125.6,353.9z M425.9,461.5c0,0-6.1,14.5-19.6,15.4c-5.8,0.4-10.3-1.2-10.3-1.2s-0.3-0.1-5.3-2.1l-112.9-55
c0,0-10.9-5.7-12.8-15.6c-2.2-8.1,2.7-18.1,2.7-18.1L322,273c0,0,4.8-9.7,12.2-13c0.6-0.3,2.3-1,4.5-1.5c8.1-2.1,18,2.8,18,2.8
l110.7,53.7c0,0,12.6,5.7,15.3,16.2c1.9,7.4-0.5,14-1.8,17.2C474.6,363.8,425.9,461.5,425.9,461.5z"/>
<path style="fill:#609926" d="M326.8,380.1c-8.2,0.1-15.4,5.8-17.3,13.8c-1.9,8,2,16.3,9.1,20c7.7,4,17.5,1.8,22.7-5.4
c5.1-7.1,4.3-16.9-1.8-23.1l24-49.1c1.5,0.1,3.7,0.2,6.2-0.5c4.1-0.9,7.1-3.6,7.1-3.6c4.2,1.8,8.6,3.8,13.2,6.1
c4.8,2.4,9.3,4.9,13.4,7.3c0.9,0.5,1.8,1.1,2.8,1.9c1.6,1.3,3.4,3.1,4.7,5.5c1.9,5.5-1.9,14.9-1.9,14.9
c-2.3,7.6-18.4,40.6-18.4,40.6c-8.1-0.2-15.3,5-17.7,12.5c-2.6,8.1,1.1,17.3,8.9,21.3c7.8,4,17.4,1.7,22.5-5.3
c5-6.8,4.6-16.3-1.1-22.6c1.9-3.7,3.7-7.4,5.6-11.3c5-10.4,13.5-30.4,13.5-30.4c0.9-1.7,5.7-10.3,2.7-21.3
c-2.5-11.4-12.6-16.7-12.6-16.7c-12.2-7.9-29.2-15.2-29.2-15.2s0-4.1-1.1-7.1c-1.1-3.1-2.8-5.1-3.9-6.3c4.7-9.7,9.4-19.3,14.1-29
c-4.1-2-8.1-4-12.2-6.1c-4.8,9.8-9.7,19.7-14.5,29.5c-6.7-0.1-12.9,3.5-16.1,9.4c-3.4,6.3-2.7,14.1,1.9,19.8
C343.2,346.5,335,363.3,326.8,380.1z"/>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 677 B

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -1,27 +1,31 @@
<svg viewBox="0 0 212 212" xmlns="http://www.w3.org/2000/svg">
<style type="text/css">
circle {
fill: none;
stroke: #000;
stroke-width: 15;
}
path {
fill: none;
stroke: #000;
stroke-width: 25;
}
.orange {
stroke:#ff6600;
}
.red {
stroke:#d40000;
}
</style>
<g transform="translate(6,6)">
<path d="M58 168 v-98 a50 50 0 0 1 50-50 h20" class="orange" />
<path d="M58 168 v-30 a50 50 0 0 1 50-50 h20" class="red" />
<circle cx="142" cy="20" r="18" class="orange" />
<circle cx="142" cy="88" r="18" class="red" />
<circle cx="58" cy="180" r="18" class="red" />
</g>
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="main_outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" viewBox="0 0 640 640" style="enable-background:new 0 0 640 640;" xml:space="preserve">
<g>
<path id="teabag" style="fill:#FFFFFF" d="M395.9,484.2l-126.9-61c-12.5-6-17.9-21.2-11.8-33.8l61-126.9c6-12.5,21.2-17.9,33.8-11.8
c17.2,8.3,27.1,13,27.1,13l-0.1-109.2l16.7-0.1l0.1,117.1c0,0,57.4,24.2,83.1,40.1c3.7,2.3,10.2,6.8,12.9,14.4
c2.1,6.1,2,13.1-1,19.3l-61,126.9C423.6,484.9,408.4,490.3,395.9,484.2z"/>
<g>
<g>
<path style="fill:#609926" d="M622.7,149.8c-4.1-4.1-9.6-4-9.6-4s-117.2,6.6-177.9,8c-13.3,0.3-26.5,0.6-39.6,0.7c0,39.1,0,78.2,0,117.2
c-5.5-2.6-11.1-5.3-16.6-7.9c0-36.4-0.1-109.2-0.1-109.2c-29,0.4-89.2-2.2-89.2-2.2s-141.4-7.1-156.8-8.5
c-9.8-0.6-22.5-2.1-39,1.5c-8.7,1.8-33.5,7.4-53.8,26.9C-4.9,212.4,6.6,276.2,8,285.8c1.7,11.7,6.9,44.2,31.7,72.5
c45.8,56.1,144.4,54.8,144.4,54.8s12.1,28.9,30.6,55.5c25,33.1,50.7,58.9,75.7,62c63,0,188.9-0.1,188.9-0.1s12,0.1,28.3-10.3
c14-8.5,26.5-23.4,26.5-23.4s12.9-13.8,30.9-45.3c5.5-9.7,10.1-19.1,14.1-28c0,0,55.2-117.1,55.2-231.1
C633.2,157.9,624.7,151.8,622.7,149.8z M125.6,353.9c-25.9-8.5-36.9-18.7-36.9-18.7S69.6,321.8,60,295.4
c-16.5-44.2-1.4-71.2-1.4-71.2s8.4-22.5,38.5-30c13.8-3.7,31-3.1,31-3.1s7.1,59.4,15.7,94.2c7.2,29.2,24.8,77.7,24.8,77.7
S142.5,359.9,125.6,353.9z M425.9,461.5c0,0-6.1,14.5-19.6,15.4c-5.8,0.4-10.3-1.2-10.3-1.2s-0.3-0.1-5.3-2.1l-112.9-55
c0,0-10.9-5.7-12.8-15.6c-2.2-8.1,2.7-18.1,2.7-18.1L322,273c0,0,4.8-9.7,12.2-13c0.6-0.3,2.3-1,4.5-1.5c8.1-2.1,18,2.8,18,2.8
l110.7,53.7c0,0,12.6,5.7,15.3,16.2c1.9,7.4-0.5,14-1.8,17.2C474.6,363.8,425.9,461.5,425.9,461.5z"/>
<path style="fill:#609926" d="M326.8,380.1c-8.2,0.1-15.4,5.8-17.3,13.8c-1.9,8,2,16.3,9.1,20c7.7,4,17.5,1.8,22.7-5.4
c5.1-7.1,4.3-16.9-1.8-23.1l24-49.1c1.5,0.1,3.7,0.2,6.2-0.5c4.1-0.9,7.1-3.6,7.1-3.6c4.2,1.8,8.6,3.8,13.2,6.1
c4.8,2.4,9.3,4.9,13.4,7.3c0.9,0.5,1.8,1.1,2.8,1.9c1.6,1.3,3.4,3.1,4.7,5.5c1.9,5.5-1.9,14.9-1.9,14.9
c-2.3,7.6-18.4,40.6-18.4,40.6c-8.1-0.2-15.3,5-17.7,12.5c-2.6,8.1,1.1,17.3,8.9,21.3c7.8,4,17.4,1.7,22.5-5.3
c5-6.8,4.6-16.3-1.1-22.6c1.9-3.7,3.7-7.4,5.6-11.3c5-10.4,13.5-30.4,13.5-30.4c0.9-1.7,5.7-10.3,2.7-21.3
c-2.5-11.4-12.6-16.7-12.6-16.7c-12.2-7.9-29.2-15.2-29.2-15.2s0-4.1-1.1-7.1c-1.1-3.1-2.8-5.1-3.9-6.3c4.7-9.7,9.4-19.3,14.1-29
c-4.1-2-8.1-4-12.2-6.1c-4.8,9.8-9.7,19.7-14.5,29.5c-6.7-0.1-12.9,3.5-16.1,9.4c-3.4,6.3-2.7,14.1,1.9,19.8
C343.2,346.5,335,363.3,326.8,380.1z"/>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 677 B

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -1,97 +0,0 @@
// Copyright 2022 The Forgejo Authors c/o Codeberg e.V.. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//go:build ignore
package main
import (
"bufio"
"os"
"regexp"
"strings"
"gopkg.in/ini.v1"
)
const (
trimPrefix = "gitea_"
sourceFolder = "options/locales/"
)
// returns list of locales, still containing the file extension!
func generate_locale_list() []string {
localeFiles, _ := os.ReadDir(sourceFolder)
locales := []string{}
for _, localeFile := range localeFiles {
if !localeFile.IsDir() && strings.HasPrefix(localeFile.Name(), trimPrefix) {
locales = append(locales, strings.TrimPrefix(localeFile.Name(), trimPrefix))
}
}
return locales
}
// replace all occurrences of Gitea with Forgejo
func renameGiteaForgejo(filename string) []byte {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
replacer := strings.NewReplacer(
"Gitea", "Forgejo",
"https://docs.gitea.io/en-us/install-from-binary/", "https://forgejo.org/download/#installation-from-binary",
"https://github.com/go-gitea/gitea/tree/master/docker", "https://forgejo.org/download/#container-image",
"https://docs.gitea.io/en-us/install-from-package/", "https://forgejo.org/download",
"https://code.gitea.io/gitea", "https://forgejo.org/download",
"code.gitea.io/gitea", "Forgejo",
`<a href="https://github.com/go-gitea/gitea/issues" target="_blank">GitHub</a>`, `<a href="https://codeberg.org/forgejo/forgejo/issues" target="_blank">Codeberg</a>`,
"https://github.com/go-gitea/gitea", "https://codeberg.org/forgejo/forgejo",
"https://blog.gitea.io", "https://forgejo.org/news",
)
out := make([]byte, 0, 1024)
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "license_desc=") {
line = strings.Replace(line, "GitHub", "Forgejo", 1)
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
out = append(out, []byte("\n"+line+"\n")...)
} else if strings.HasPrefix(line, "settings.web_hook_name_gitea") {
out = append(out, []byte("\n"+line+"\n")...)
out = append(out, []byte("settings.web_hook_name_forgejo = Forgejo\n")...)
} else if strings.HasPrefix(line, "migrate.gitea.description") {
re := regexp.MustCompile(`(.*Gitea)`)
out = append(out, []byte(re.ReplaceAllString(line, "${1}/Forgejo")+"\n")...)
} else {
out = append(out, []byte(replacer.Replace(line)+"\n")...)
}
}
file.Close()
return out
}
func main() {
locales := generate_locale_list()
var err error
var localeFile *ini.File
for _, locale := range locales {
giteaLocale := sourceFolder + "gitea_" + locale
localeFile, err = ini.LoadSources(ini.LoadOptions{
IgnoreInlineComment: true,
}, giteaLocale, renameGiteaForgejo(giteaLocale))
if err != nil {
panic(err)
}
err = localeFile.SaveTo("options/locale/locale_" + locale)
if err != nil {
panic(err)
}
}
}

View File

@ -7,7 +7,6 @@ package cmd
import (
"errors"
"fmt"
"net/url"
"os"
"strings"
"text/tabwriter"
@ -470,19 +469,11 @@ func runAddOauth(c *cli.Context) error {
return err
}
config := parseOAuth2Config(c)
if config.Provider == "openidConnect" {
discoveryURL, err := url.Parse(config.OpenIDConnectAutoDiscoveryURL)
if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") {
return fmt.Errorf("invalid Auto Discovery URL: %s (this must be a valid URL starting with http:// or https://)", config.OpenIDConnectAutoDiscoveryURL)
}
}
return auth_model.CreateSource(&auth_model.Source{
Type: auth_model.OAuth2,
Name: c.String("name"),
IsActive: true,
Cfg: config,
Cfg: parseOAuth2Config(c),
})
}

View File

@ -35,7 +35,7 @@ func runConvert(ctx *cli.Context) error {
log.Info("Log path: %s", setting.Log.RootPath)
log.Info("Configuration file: %s", setting.CustomConf)
if !setting.Database.Type.IsMySQL() {
if !setting.Database.UseMySQL {
fmt.Println("This command can only be used with a MySQL database")
return nil
}

View File

@ -98,14 +98,14 @@ var outputTypeEnum = &outputType{
// CmdDump represents the available dump sub-command.
var CmdDump = cli.Command{
Name: "dump",
Usage: "Dump Forgejo files and database",
Usage: "Dump Gitea files and database",
Description: `Dump compresses all related files and database into zip file.
It can be used for backup and capture Forgejo server image to send to maintainer`,
It can be used for backup and capture Gitea server image to send to maintainer`,
Action: runDump,
Flags: []cli.Flag{
cli.StringFlag{
Name: "file, f",
Value: fmt.Sprintf("forgejo-dump-%d.zip", time.Now().Unix()),
Value: fmt.Sprintf("gitea-dump-%d.zip", time.Now().Unix()),
Usage: "Name of the dump file which will be created. Supply '-' for stdout. See type for available types.",
},
cli.BoolFlag{
@ -194,7 +194,7 @@ func runDump(ctx *cli.Context) error {
}
if !setting.InstallLock {
log.Error("Is '%s' really the right config path?\n", setting.CustomConf)
return fmt.Errorf("forgejo is not initialized")
return fmt.Errorf("gitea is not initialized")
}
setting.LoadSettings() // cannot access session settings otherwise
@ -267,7 +267,7 @@ func runDump(ctx *cli.Context) error {
fatal("Path does not exist: %s", tmpDir)
}
dbDump, err := os.CreateTemp(tmpDir, "forgejo-db.sql")
dbDump, err := os.CreateTemp(tmpDir, "gitea-db.sql")
if err != nil {
fatal("Failed to create tmp file: %v", err)
}
@ -279,7 +279,7 @@ func runDump(ctx *cli.Context) error {
}()
targetDBType := ctx.String("database")
if len(targetDBType) > 0 && targetDBType != setting.Database.Type.String() {
if len(targetDBType) > 0 && targetDBType != setting.Database.Type {
log.Info("Dumping database %s => %s...", setting.Database.Type, targetDBType)
} else {
log.Info("Dumping database...")
@ -289,8 +289,8 @@ func runDump(ctx *cli.Context) error {
fatal("Failed to dump database: %v", err)
}
if err := addFile(w, "forgejo-db.sql", dbDump.Name(), verbose); err != nil {
fatal("Failed to include forgejo-db.sql: %v", err)
if err := addFile(w, "gitea-db.sql", dbDump.Name(), verbose); err != nil {
fatal("Failed to include gitea-db.sql: %v", err)
}
if len(setting.CustomConf) > 0 {

View File

@ -150,13 +150,13 @@ func runServ(c *cli.Context) error {
}
switch key.Type {
case asymkey_model.KeyTypeDeploy:
println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Forgejo does not provide shell access.")
println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Gitea does not provide shell access.")
case asymkey_model.KeyTypePrincipal:
println("Hi there! You've successfully authenticated with the principal " + key.Content + ", but Forgejo does not provide shell access.")
println("Hi there! You've successfully authenticated with the principal " + key.Content + ", but Gitea does not provide shell access.")
default:
println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Forgejo does not provide shell access.")
println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Gitea does not provide shell access.")
}
println("If this is unexpected, please log in with password and setup Forgejo under another user.")
println("If this is unexpected, please log in with password and setup Gitea under another user.")
return nil
} else if c.Bool("debug") {
log.Debug("SSH_ORIGINAL_COMMAND: %s", os.Getenv("SSH_ORIGINAL_COMMAND"))

View File

@ -1,4 +1,3 @@
// Copyright 2023 The Forgejo Authors. All rights reserved.
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
@ -19,17 +18,17 @@ import (
)
// EnvironmentPrefix environment variables prefixed with this represent ini values to write
const prefixRegexpString = "^(FORGEJO|GITEA)"
const EnvironmentPrefix = "GITEA"
func main() {
app := cli.NewApp()
app.Name = "environment-to-ini"
app.Usage = "Use provided environment to update configuration ini"
app.Description = `As a helper to allow docker users to update the forgejo configuration
app.Description = `As a helper to allow docker users to update the gitea configuration
through the environment, this command allows environment variables to
be mapped to values in the ini.
Environment variables of the form "FORGEJO__SECTION_NAME__KEY_NAME"
Environment variables of the form "GITEA__SECTION_NAME__KEY_NAME"
will be mapped to the ini section "[section_name]" and the key
"KEY_NAME" with the value as provided.
@ -47,8 +46,9 @@ func main() {
...
"""
You would set the environment variables: "FORGEJO__LOG_0x2E_CONSOLE__COLORIZE=false"
and "FORGEJO__LOG_0x2E_CONSOLE__STDERR=false".`
You would set the environment variables: "GITEA__LOG_0x2E_CONSOLE__COLORIZE=false"
and "GITEA__LOG_0x2E_CONSOLE__STDERR=false". Other examples can be found
on the configuration cheat sheet.`
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "custom-path, C",
@ -76,7 +76,7 @@ func main() {
},
cli.StringFlag{
Name: "prefix, p",
Value: prefixRegexpString,
Value: EnvironmentPrefix,
Usage: "Environment prefix to look for - will be suffixed by __ (2 underscores)",
},
}
@ -89,19 +89,6 @@ func main() {
}
}
func splitEnvironmentVariable(prefixRegexp *regexp.Regexp, kv string) (string, string) {
idx := strings.IndexByte(kv, '=')
if idx < 0 {
return "", ""
}
k := kv[:idx]
loc := prefixRegexp.FindStringIndex(k)
if loc == nil {
return "", ""
}
return k[loc[1]:], kv[idx+1:]
}
func runEnvironmentToIni(c *cli.Context) error {
providedCustom := c.String("custom-path")
providedConf := c.String("config")
@ -124,13 +111,19 @@ func runEnvironmentToIni(c *cli.Context) error {
changed := false
prefixRegexp := regexp.MustCompile(c.String("prefix") + "__")
prefix := c.String("prefix") + "__"
for _, kv := range os.Environ() {
eKey, value := splitEnvironmentVariable(prefixRegexp, kv)
if eKey == "" {
idx := strings.IndexByte(kv, '=')
if idx < 0 {
continue
}
eKey := kv[:idx]
value := kv[idx+1:]
if !strings.HasPrefix(eKey, prefix) {
continue
}
eKey = eKey[len(prefix):]
sectionName, keyName := DecodeSectionKey(eKey)
if len(keyName) == 0 {
continue
@ -170,11 +163,14 @@ func runEnvironmentToIni(c *cli.Context) error {
}
if c.Bool("clear") {
for _, kv := range os.Environ() {
eKey, _ := splitEnvironmentVariable(prefixRegexp, kv)
if eKey == "" {
idx := strings.IndexByte(kv, '=')
if idx < 0 {
continue
}
_ = os.Unsetenv(eKey)
eKey := kv[:idx]
if strings.HasPrefix(eKey, prefix) {
_ = os.Unsetenv(eKey)
}
}
}
return nil

View File

@ -1,21 +0,0 @@
// Copyright 2023 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package main
import (
"regexp"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_splitEnvironmentVariable(t *testing.T) {
prefixRegexp := regexp.MustCompile(prefixRegexpString + "__")
k, v := splitEnvironmentVariable(prefixRegexp, "FORGEJO__KEY=VALUE")
assert.Equal(t, k, "KEY")
assert.Equal(t, v, "VALUE")
k, v = splitEnvironmentVariable(prefixRegexp, "nothing=interesting")
assert.Equal(t, k, "")
assert.Equal(t, v, "")
}

View File

@ -1,84 +0,0 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: gitea
# Required-Start: $syslog $network
# Required-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: A self-hosted Git service written in Go.
# Description: A self-hosted Git service written in Go.
### END INIT INFO
# Do NOT "set -e"
# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
DESC="Gitea - Git with a cup of tea"
NAME=gitea
SERVICEVERBOSE=yes
PIDFILE=/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
WORKINGDIR=/var/lib/$NAME
DAEMON=/usr/local/bin/$NAME
DAEMON_ARGS="web -c /etc/$NAME/app.ini"
USER=git
STOP_SCHEDULE="${STOP_SCHEDULE:-QUIT/5/TERM/1/KILL/5}"
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0
do_start()
{
GITEA_ENVS="USER=$USER GITEA_WORK_DIR=$WORKINGDIR HOME=/home/$USER"
GITEA_EXEC="$DAEMON -- $DAEMON_ARGS"
sh -c "start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile \\
--background --chdir $WORKINGDIR --chuid $USER \\
--exec /bin/bash -- -c '/usr/bin/env $GITEA_ENVS $GITEA_EXEC'"
}
do_stop()
{
start-stop-daemon --stop --quiet --retry=$STOP_SCHEDULE --pidfile $PIDFILE --name $NAME --oknodo
rm -f $PIDFILE
}
do_status()
{
if [ -f $PIDFILE ]; then
if kill -0 $(cat "$PIDFILE"); then
echo "$NAME is running, PID is $(cat $PIDFILE)"
else
echo "$NAME process is dead, but pidfile exists"
fi
else
echo "$NAME is not running"
fi
}
case "$1" in
start)
echo "Starting $DESC" "$NAME"
do_start
;;
stop)
echo "Stopping $DESC" "$NAME"
do_stop
;;
status)
do_status
;;
restart)
echo "Restarting $DESC" "$NAME"
do_stop
do_start
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
exit 2
;;
esac
exit 0

View File

@ -1,5 +1,5 @@
[Unit]
Description=Forgejo (Beyond coding. We forge.)
Description=Gitea (Git with a cup of tea)
After=syslog.target
After=network.target
###
@ -25,21 +25,21 @@ After=network.target
# If using socket activation for main http/s
###
#
#After=forgejo.main.socket
#Requires=forgejo.main.socket
#After=gitea.main.socket
#Requires=gitea.main.socket
#
###
# (You can also provide forgejo an http fallback and/or ssh socket too)
# (You can also provide gitea an http fallback and/or ssh socket too)
#
# An example of /etc/systemd/system/forgejo.main.socket
# An example of /etc/systemd/system/gitea.main.socket
###
##
## [Unit]
## Description=Forgejo Web Socket
## PartOf=forgejo.service
## Description=Gitea Web Socket
## PartOf=gitea.service
##
## [Socket]
## Service=forgejo.service
## Service=gitea.service
## ListenStream=<some_port>
## NoDelay=true
##
@ -55,28 +55,28 @@ RestartSec=2s
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/forgejo/
# If using Unix socket: tells systemd to create the /run/forgejo folder, which will contain the forgejo.sock file
# (manually creating /run/forgejo doesn't work, because it would not persist across reboots)
#RuntimeDirectory=forgejo
ExecStart=/usr/local/bin/forgejo web --config /etc/forgejo/app.ini
WorkingDirectory=/var/lib/gitea/
# If using Unix socket: tells systemd to create the /run/gitea folder, which will contain the gitea.sock file
# (manually creating /run/gitea doesn't work, because it would not persist across reboots)
#RuntimeDirectory=gitea
ExecStart=/usr/local/bin/gitea web --config /etc/gitea/app.ini
Restart=always
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/forgejo
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea
# If you install Git to directory prefix other than default PATH (which happens
# for example if you install other versions of Git side-to-side with
# distribution version), uncomment below line and add that prefix to PATH
# Don't forget to place git-lfs binary on the PATH below if you want to enable
# Git LFS support
#Environment=PATH=/path/to/git/bin:/bin:/sbin:/usr/bin:/usr/sbin
# If you want to bind Forgejo to a port below 1024, uncomment
# the two values below, or use socket activation to pass Forgejo its ports as above
# If you want to bind Gitea to a port below 1024, uncomment
# the two values below, or use socket activation to pass Gitea its ports as above
###
#CapabilityBoundingSet=CAP_NET_BIND_SERVICE
#AmbientCapabilities=CAP_NET_BIND_SERVICE
###
# In some cases, when using CapabilityBoundingSet and AmbientCapabilities option, you may want to
# set the following value to false to allow capabilities to be applied on Forgejo process. The following
# value if set to true sandboxes Forgejo service and prevent any processes from running with privileges
# set the following value to false to allow capabilities to be applied on gitea process. The following
# value if set to true sandboxes gitea service and prevent any processes from running with privileges
# in the host user namespace.
###
#PrivateUsers=false

View File

@ -365,7 +365,7 @@ USER = root
;; SQLite Configuration
;;
;DB_TYPE = sqlite3
;PATH= ; defaults to data/forgejo.db
;PATH= ; defaults to data/gitea.db
;SQLITE_TIMEOUT = ; Query timeout defaults to: 500
;SQLITE_JOURNAL_MODE = ; defaults to sqlite database default (often DELETE), can be used to enable WAL mode. https://www.sqlite.org/pragma.html#pragma_journal_mode
;;
@ -576,22 +576,6 @@ ROUTER = console
;; The routing level will default to that of the system but individual router level can be set in
;; [log.<mode>.router] LEVEL
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Print request id which parsed from request headers in access log, when access log is enabled.
;; * E.g:
;; * In request Header: X-Request-ID: test-id-123
;; * Configuration in app.ini: REQUEST_ID_HEADERS = X-Request-ID
;; * Print in log: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "test-id-123"
;;
;; If you configure more than one in the .ini file, it will match in the order of configuration,
;; and the first match will be finally printed in the log.
;; * E.g:
;; * In reuqest Header: X-Trace-ID: trace-id-1q2w3e4r
;; * Configuration in app.ini: REQUEST_ID_HEADERS = X-Request-ID, X-Trace-ID, X-Req-ID
;; * Print in log: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "trace-id-1q2w3e4r"
;;
;; REQUEST_ID_HEADERS =
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
@ -2222,7 +2206,6 @@ ROUTER = console
;ENABLE_SUCCESS_NOTICE = false
;SCHEDULE = @every 168h
;HTTP_ENDPOINT = https://dl.gitea.io/gitea/version.json
;DOMAIN_ENDPOINT = release.forgejo.org
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -2587,8 +2570,8 @@ ROUTER = console
; [actions]
;; Enable/Disable actions capabilities
;ENABLED = false
;; Default address to get action plugins, e.g. the default value means downloading from "https://codeberg.org/actions/checkout" for "uses: actions/checkout@v3"
;DEFAULT_ACTIONS_URL = https://codeberg.org
;; Default address to get action plugins, e.g. the default value means downloading from "https://gitea.com/actions/checkout" for "uses: actions/checkout@v3"
;DEFAULT_ACTIONS_URL = https://gitea.com
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

View File

@ -24,7 +24,7 @@ if [ ! -f ${GITEA_CUSTOM}/conf/app.ini ]; then
fi
# Substitute the environment variables in the template
APP_NAME=${APP_NAME:-"Forgejo: Beyond coding. We forge."} \
APP_NAME=${APP_NAME:-"Gitea: Git with a cup of tea"} \
RUN_MODE=${RUN_MODE:-"prod"} \
DOMAIN=${DOMAIN:-"localhost"} \
SSH_DOMAIN=${SSH_DOMAIN:-"localhost"} \

View File

@ -26,7 +26,7 @@ if [ ! -f ${GITEA_APP_INI} ]; then
fi
# Substitute the environment variables in the template
APP_NAME=${APP_NAME:-"Forgejo: Beyond coding. We forge."} \
APP_NAME=${APP_NAME:-"Gitea: Git with a cup of tea"} \
RUN_MODE=${RUN_MODE:-"prod"} \
RUN_USER=${USER:-"git"} \
SSH_DOMAIN=${SSH_DOMAIN:-"localhost"} \

View File

@ -881,13 +881,7 @@ Default templates for project boards:
- `Identity`: the SignedUserName or `"-"` if not logged in.
- `Start`: the start time of the request.
- `ResponseWriter`: the responseWriter from the request.
- `RequestID`: the value matching REQUEST_ID_HEADERSdefault: `-`, if not matched.
- You must be very careful to ensure that this template does not throw errors or panics as this template runs outside of the panic/recovery script.
- `REQUEST_ID_HEADERS`: **\<empty\>**: You can configure multiple values that are splited by comma here. It will match in the order of configuration, and the first match will be finally printed in the access log.
- e.g.
- In the Request Header: X-Request-ID: **test-id-123**
- Configuration in app.ini: REQUEST_ID_HEADERS = X-Request-ID
- Print in log: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "**test-id-123**" ...
### Log subsections (`log.name`, `log.name.*`)
@ -1053,7 +1047,6 @@ Default templates for project boards:
- `ENABLE_SUCCESS_NOTICE`: **true**: Set to false to switch off success notices.
- `SCHEDULE`: **@every 168h**: Cron syntax for scheduling a work, e.g. `@every 168h`.
- `HTTP_ENDPOINT`: **https://dl.gitea.io/gitea/version.json**: the endpoint that Gitea will check for newer versions
- `DOMAIN_ENDPOINT`: **release.forgejo.org**: the domain that, if specified, Gitea will check for newer versions. This is preferred over `HTTP_ENDPOINT`.
#### Cron - Delete all old system notices from database ('cron.delete_old_system_notices')
@ -1349,7 +1342,7 @@ PROXY_HOSTS = *.github.com
## Actions (`actions`)
- `ENABLED`: **false**: Enable/Disable actions capabilities
- `DEFAULT_ACTIONS_URL`: **https://codeberg.org**: Default address to get action plugins, e.g. the default value means downloading from "<https://codeberg.org/actions/checkout>" for "uses: actions/checkout@v3"
- `DEFAULT_ACTIONS_URL`: **https://gitea.com**: Default address to get action plugins, e.g. the default value means downloading from "<https://gitea.com/actions/checkout>" for "uses: actions/checkout@v3"
`DEFAULT_ACTIONS_URL` indicates where should we find the relative path action plugin. i.e. when use an action in a workflow file like
@ -1369,14 +1362,14 @@ jobs:
Now we need to know how to get actions/checkout, this configuration is the default git server to get it. That means we will get the repository via git clone ${DEFAULT_ACTIONS_URL}/actions/checkout and fetch tag v3.
To help people who don't want to mirror these actions in their git instances, the default value is https://codeberg.org
To help people who don't want to mirror these actions in their git instances, the default value is https://gitea.com
To help people run actions totally in their network, they can change the value and copy all necessary action repositories into their git server.
Of course we should support the form in future PRs like
```yaml
steps:
- uses: codeberg.org/actions/checkout@v3
- uses: gitea.com/actions/checkout@v3
```
although Github don't support this form.

View File

@ -262,22 +262,7 @@ test01.xls: application/vnd.ms-excel; charset=binary
- `ROOT_PATH`: 日志文件根目录。
- `MODE`: 日志记录模式,默认是为 `console`。如果要写到多个通道,用逗号分隔
- `LEVEL`: 日志级别,默认为 `Trace`
- `DISABLE_ROUTER_LOG`: 关闭日志中的路由日志。
- `ENABLE_ACCESS_LOG`: 是否开启 Access Log, 默认为 false。
- `ACCESS_LOG_TEMPLATE`: `access.log` 输出内容的模板,默认模板:**`{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`**
模板支持以下参数:
- `Ctx`: 请求上下文。
- `Identity`: 登录用户名,默认: “`-`”。
- `Start`: 请求开始时间。
- `ResponseWriter`:
- `RequestID`: 从请求头中解析得到的与 `REQUEST_ID_HEADERS` 匹配的值,默认: “`-`”。
- 一定要谨慎配置该模板否则可能会引起panic.
- `REQUEST_ID_HEADERS`: 从 Request Header 中匹配指定 Key并将匹配到的值输出到 `access.log` 中(需要在 `ACCESS_LOG_TEMPLATE` 中指定输出位置)。如果在该参数中配置多个 Key 请用逗号分割,程序将按照配置的顺序进行匹配。
- 示例:
- 请求头: X-Request-ID: **test-id-123**
- 配置文件: REQUEST_ID_HEADERS = X-Request-ID
- 日志输出: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "**test-id-123**" ...
- `LEVEL`: 日志级别,默认为`Trace`。
## Cron (`cron`)

View File

@ -282,22 +282,9 @@ To add custom .gitignore, add a file with existing [.gitignore rules](https://gi
### Labels
Starting with Gitea 1.19, you can add a file that follows the [YAML label format](https://github.com/go-gitea/gitea/blob/main/options/label/Advanced.yaml) to `$GITEA_CUSTOM/options/label`:
```yaml
labels:
- name: "foo/bar" # name of the label that will appear in the dropdown
exclusive: true # whether to use the exclusive namespace for scoped labels. scoped delimiter is /
color: aabbcc # hex colour coding
description: Some label # long description of label intent
```
The [legacy file format](https://github.com/go-gitea/gitea/blob/main/options/label/Default) can still be used following the format below, however we strongly recommend using the newer YAML format instead.
To add a custom label set, add a file that follows the [label format](https://github.com/go-gitea/gitea/blob/main/options/label/Default) to `$GITEA_CUSTOM/options/label`
`#hex-color label name ; label description`
For more information, see the [labels documentation]({{< relref "doc/usage/labels.en-us.md" >}}).
### Licenses
To add a custom license, add a file with the license text to `$GITEA_CUSTOM/options/license`

View File

@ -1,6 +1,6 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "玩转 Gitea"
title: "加入 Gitea 开源"
slug: "hacking-on-gitea"
weight: 10
toc: false
@ -8,342 +8,36 @@ draft: false
menu:
sidebar:
parent: "developers"
name: "玩转 Gitea"
name: "加入 Gitea 开源"
weight: 10
identifier: "hacking-on-gitea"
---
# Hacking on Gitea
**目录**
首先你需要一些运行环境,这和 [从源代码安装]({{< relref "doc/installation/from-source.zh-cn.md" >}}) 相同,如果你还没有设置好,可以先阅读那个章节。
{{< toc >}}
如果你想为 Gitea 贡献代码,你需要 Fork 这个项目并且以 `master` 为开发分支。Gitea 使用 Govendor
来管理依赖,因此所有依赖项都被工具自动 copy 在 vendor 子目录下。用下面的命令来下载源码:
## 快速入门
要获得快速工作的开发环境,您可以使用 Gitpod。
[![在 Gitpod 中打开](/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/go-gitea/gitea)
## 安装 Golang
您需要 [安装 go]( https://golang.org/doc/install ) 并设置您的 go 环境。
接下来,[使用 npm 安装 Node.js](https://nodejs.org/en/download/) ,这是构建
JavaScript 和 CSS 文件的必要工具。最低支持的 Node.js 版本是 {{< min-node-version >}}
并且推荐使用最新的 LTS 版本。
**注意** :当执行需要外部工具的 make 任务时,比如
`make watch-backend`Gitea 会自动下载并构建这些必要的组件。为了能够使用这些,你必须
`"$GOPATH"/bin` 目录加入到可执行路径上。如果你不把go bin目录添加到可执行路径你必须手动
指定可执行程序路径。
**注意2** Go版本 {{< min-go-version >}} 或更高版本是必须的。Gitea 使用 `gofmt`
格式化源代码。然而,`gofmt` 的结果可能因 `go` 的版本而有差异。因此推荐安装我们持续集成使用
的 Go版本。截至上次更新Go 版本应该是 {{< go-version >}}。
## 安装 Make
Gitea 大量使用 `Make` 来自动化任务和改进开发。本指南涵盖了如何安装 Make。
### 在 Linux 上
使用包管理器安装。
在 Ubuntu/Debian 上:
```bash
sudo apt-get install make
```
go get -d code.gitea.io/gitea
```
在 Fedora/RHEL/CentOS 上
然后你可以在 Github 上 fork [Gitea 项目](https://github.com/go-gitea/gitea),之后可以通过下面的命令进入源码目录:
```bash
sudo yum install make
```
cd $GOPATH/src/code.gitea.io/gitea
```
### 在 Windows 上
要创建 pull requests 你还需要在源码中新增一个 remote 指向你 Fork 的地址,直接推送到 origin 的话会告诉你没有写权限:
Make 的这三个发行版都可以在 Windows 上运行:
- [单个二进制构建]( http://www.equation.com/servlet/equation.cmd?fa=make )。复制到某处并添加到 `PATH`
- [32 位版本](http://www.equation.com/ftpdir/make/32/make.exe)
- [64 位版本](http://www.equation.com/ftpdir/make/64/make.exe)
- [MinGW-w64](https://www.mingw-w64.org) / [MSYS2](https://www.msys2.org/)。
- MSYS2 是一个工具和库的集合,为您提供一个易于使用的环境来构建、安装和运行本机 Windows 软件,它包括 MinGW-w64。
- 在 MingGW-w64 中,二进制文件称为 `mingw32-make.exe` 而不是 `make.exe`。将 `bin` 文件夹添加到 `PATH`
- 在 MSYS2 中,您可以直接使用 `make`。请参阅 [MSYS2 移植](https://www.msys2.org/wiki/Porting/)。
- 要使用 CGO_ENABLED例如SQLite3编译 Gitea您可能需要使用 [tdm-gcc](https://jmeubank.github.io/tdm-gcc/) 而不是 MSYS2 gcc因为 MSYS2 gcc 标头缺少一些 Windows -只有 CRT 函数像 _beginthread 一样。
- [Chocolatey包管理器]( https://chocolatey.org/packages/make )。运行`choco install make`
**注意** :如果您尝试在 Windows 命令提示符下使用 make 进行构建您可能会遇到问题。建议使用上述提示Git bash 或 MinGW但是如果您只有命令提示符或可能是 PowerShell则可以使用 [set](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/set_1) 命令,例如 `set TAGS=bindata`
## 下载并克隆 Gitea 源代码
获取源代码的推荐方法是使用 `git clone`
```bash
git clone https://github.com/go-gitea/gitea
```
自从go modules出现后不再需要构建 go 项目从 `$GOPATH` 中获取,因此不再推荐使用 `go get` 方法。)
## 派生 Gitea
如上所述下载主要的 Gitea 源代码。然后,派生 [Gitea 仓库](https://github.com/go-gitea/gitea)
并为您的本地仓库切换 git 远程源,或添加另一个远程源:
```bash
# 将原来的 Gitea origin 重命名为 upstream
git remote rename origin upstream
git remote add origin "git@github.com:$GITHUB_USERNAME/gitea.git"
git remote add origin git@github.com:<USERNAME>/gitea.git
git fetch --all --prune
```
或者:
然后你就可以开始开发了。你可以看一下 `Makefile` 的内容。`make test` 可以运行测试程序, `make build` 将生成一个 `gitea` 可运行文件在根目录。如果你的提交比较复杂,尽量多写一些单元测试代码。
```bash
# 为我们的 fork 添加新的远程
git remote add "$FORK_NAME" "git@github.com:$GITHUB_USERNAME/gitea.git"
git fetch --all --prune
```
为了能够创建合并请求,应将分叉存储库添加为 Gitea 本地仓库的远程,否则无法推送更改。
## 构建 Gitea基本
看看我们的
<a href='{{ < relref "doc/installation/from-source.en-us.md" > }}'>说明</a>
关于如何 <a href='{{ < relref "doc/installation/from-source.en-us.md" > }}'>从源代码构建</a>
从源代码构建的最简单推荐方法是:
```bash
TAGS="bindata sqlite sqlite_unlock_notify" make build
```
`build` 目标将同时执行 `frontend``backend` 子目标。如果存在 `bindata` 标签,资源文件将被编译成二进制文件。建议在进行前端开发时省略 `bindata` 标签,以便实时反映更改。
有关所有可用的 `make` 目标,请参阅 `make help`。另请参阅 [`.drone.yml`](https://github.com/go-gitea/gitea/blob/main/.drone.yml) 以了解我们的持续集成是如何工作的。
## 持续构建
要在源文件更改时运行并持续构建:
```bash
# 对于前端和后端
make watch
# 或者只看前端文件html/js/css
make watch-frontend
# 或者:只看后端文件 (go)
make watch-backend
```
在 macOS 上,监视所有后端源文件可能会达到默认的打开文件限制,这可以通过当前 shell 的 `ulimit -n 12288` 或所有未来 shell 的 shell 启动文件来增加。
### 格式化、代码分析和拼写检查
我们的持续集成将拒绝未通过代码检查(包括格式检查、代码分析和拼写检查)的 PR。
你应该格式化你的代码:
```bash
make fmt
```
并检查源代码:
```bash
# lint 前端和后端代码
make lint
# 仅 lint 后端代码
make lint-backend
```
**注意** `gofmt` 的结果取决于 `go` 的版本。您应该运行与持续集成相同的 go 版本。
### 处理 JS 和 CSS
前端开发应遵循 [Guidelines for Frontend Development]({{ < 相关参考 "doc/developers/guidelines-frontend.en-us.md" > }})
要使用前端资源构建请使用上面提到的“watch-frontend”目标或只构建一次
```bash
make build && ./gitea
```
在提交之前,确保 linters 通过:
```bash
make lint-frontend
```
### 配置本地 ElasticSearch 实例
使用 docker 启动本地 ElasticSearch 实例:
```sh
mkdir -p $(pwd) /data/elasticsearch
sudo chown -R 1000:1000 $(pwd) /data/elasticsearch
docker run --rm --memory= "4g" -p 127.0.0.1:9200:9200 -p 127.0.0.1:9300:9300 -e "discovery.type=single-node" -v "$(pwd)/data /elasticsearch:/usr/share/elasticsearch/data" docker.elastic.co/elasticsearch/elasticsearch:7.16.3
```
配置`app.ini`
```ini
[indexer]
ISSUE_INDEXER_TYPE = elasticsearch
ISSUE_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200
REPO_INDEXER_ENABLED = true
REPO_INDEXER_TYPE = elasticsearch
REPO_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200
```
### 构建和添加 SVGs
SVG 图标是使用 `make svg` 目标构建的,该目标将 `build/generate-svg.js` 中定义的图标源编译到输出目录 `public/img/svg` 中。可以在 `web_src/svg` 目录中添加自定义图标。
### 构建 Logo
Gitea Logo的 PNG 和 SVG 版本是使用 `TAGS="gitea" make generate-images` 目标从单个 SVG 源文件 assets/logo.svg 构建的。要运行它Node.js 和 npm 必须可用。
通过更新 `assets/logo.svg` 并运行 `make generate-images`,同样的过程也可用于从 SVG 源文件生成自定义 Logo PNG。忽略 gitea 编译选项将仅更新用户指定的 LOGO 文件。
### 更新 API
创建新的 API 路由或修改现有的 API 路由时,您**必须**
更新和/或创建 [Swagger](https://swagger.io/docs/specification/2-0/what-is-swagger/)
这些使用 [go-swagger](https://goswagger.io/) 评论的文档。
[规范]( https://goswagger.io/use/spec.html#annotation-syntax )中描述了这些注释的结构。
如果您想了解更多有关 Swagger 结构的信息,可以查看
[Swagger 2.0 文档](https://swagger.io/docs/specification/2-0/basic-structure/)
或与添加新 API 端点的先前 PR 进行比较,例如 [PR #5483](https://github.com/go-gitea/gitea/pull/5843/files#diff-2e0a7b644cf31e1c8ef7d76b444fe3aaR20)
您应该注意不要破坏下游用户依赖的 API。在稳定的 API 上,一般来说添加是可以接受的,但删除
或对 API 进行根本性更改将会被拒绝。
创建或更改 API 端点后,请用以下命令重新生成 Swagger 文档:
```bash
make generate-swagger
```
您应该验证生成的 Swagger 文件并使用以下命令对其进行拼写检查:
```bash
make swagger-validate misspell-check
```
您应该提交更改后的 swagger JSON 文件。持续集成服务器将使用以下方法检查是否已完成:
```bash
make swagger-check
```
**注意** :请注意,您应该使用 Swagger 2.0 文档,而不是 OpenAPI 3 文档。
### 创建新的配置选项
创建新的配置选项时,将它们添加到 `modules/setting` 的对应文件。您应该将信息添加到 `custom/conf/app.ini`
并到 <a href = '{{ < relref "doc/advanced/config-cheat-sheet.en-us.md" > }}'>配置备忘单</a>
`docs/content/doc/advanced/config-cheat-sheet.en-us.md` 中找到
### 更改Logo
更改 Gitea Logo SVG 时,您将需要运行并提交结果的:
```bash
make generate-images
```
这将创建必要的 Gitea 图标和其他图标。
### 数据库迁移
如果您对数据库中的任何数据库持久结构进行重大更改
`models/` 目录,您将需要进行新的迁移。可以找到这些
`models/migrations/` 中。您可以确保您的迁移适用于主要
数据库类型使用:
```bash
make test-sqlite-migration # 将 SQLite 切换为适当的数据库
```
## 测试
Gitea 运行两种类型的测试:单元测试和集成测试。
### 单元测试
`go test` 系统中的`*_test.go` 涵盖了单元测试。
您可以设置环境变量 `GITEA_UNIT_TESTS_LOG_SQL=1` 以在详细模式下运行测试时显示所有 SQL 语句(即设置`GOTESTFLAGS=-v` 时)。
```bash
TAGS="bindata sqlite sqlite_unlock_notify" make test # Runs the unit tests
```
### 集成测试
单元测试不会也不能完全单独测试 Gitea。因此我们编写了集成测试但是这些依赖于数据库。
```bash
TAGS="bindata sqlite sqlite_unlock_notify" make build test-sqlite
```
将在 SQLite 环境中运行集成测试。集成测试需要安装 `git lfs`。其他数据库测试可用,但
可能需要适应当地环境。
看看 [`tests/integration/README.md`](https://github.com/go-gitea/gitea/blob/main/tests/integration/README.md) 有关更多信息以及如何运行单个测试。
### 测试 PR
我们的持续集成将测试代码是否通过了单元测试,并且所有支持的数据库都将在 Docker 环境中通过集成测试。
还将测试从几个最新版本的 Gitea 迁移。
请在PR中附带提交适当的单元测试和集成测试。
## 网站文档
该网站的文档位于 `docs/` 中。如果你改变了文档内容,你可以使用以下测试方法进行持续集成:
```bash
# 来自 Gitea 中的 docs 目录
make trans-copy clean build
```
运行此任务依赖于 [Hugo](https://gohugo.io/)。请注意:这可能会生成一些未跟踪的 Git 对象,
需要被清理干净。
## Visual Studio Code
`contrib/ide/vscode` 中为 Visual Studio Code 提供了 `launch.json``tasks.json`。查看
[`contrib/ide/README.md`](https://github.com/go-gitea/gitea/blob/main/contrib/ide/README.md) 了解更多信息。
## Goland
单击 `/main.go` 中函数 `func main()` 上的 `Run Application` 箭头
可以快速启动一个可调试的 Gitea 实例。
`Run/Debug Configuration` 中的 `Output Directory` 必须设置为
gitea 项目目录(包含 `main.go``go.mod`
否则,启动实例的工作目录是 GoLand 的临时目录
并防止 Gitea 在开发环境中加载动态资源(例如:模板)。
要在 GoLand 中使用 SQLite 运行单元测试,请设置 `-tags sqlite,sqlite_unlock_notify`
`运行/调试配置``Go 工具参数` 中。
## 提交 PR
对更改感到满意后,将它们推送并打开拉取请求。它建议您允许 Gitea Managers 和 Owners 修改您的 PR
分支,因为我们需要在合并之前将其更新为 main 和/或可能是能够直接帮助解决问题。
任何 PR 都需要 Gitea 维护者的两次批准,并且需要通过持续集成。看看我们的
[CONTRIBUTING.md](https://github.com/go-gitea/gitea/blob/main/CONTRIBUTING.md)
文档。
如果您需要更多帮助,请访问 [Discord](https://discord.gg/gitea) #Develop 频道
并在那里聊天。
现在,您已准备好 Hacking Gitea。
好了,到这里你已经设置好了所有的开发 Gitea 所需的环境。欢迎成为 Gitea 的 Contributor。

View File

@ -60,7 +60,6 @@ Gitea supports the following scopes for tokens:
| &nbsp;&nbsp;&nbsp; **write:public_key** | Grant read/write access to public keys |
| &nbsp;&nbsp;&nbsp; **read:public_key** | Grant read-only access to public keys |
| **admin:org_hook** | Grants full access to organizational-level hooks |
| **admin:user_hook** | Grants full access to user-level hooks |
| **notification** | Grants full access to notifications |
| **user** | Grants full access to user profile info |
| &nbsp;&nbsp;&nbsp; **read:user** | Grants read access to user's profile |

View File

@ -23,7 +23,7 @@ Publish [Maven](https://maven.apache.org) packages for your user or organization
## Requirements
To work with the Maven package registry, you can use [Maven](https://maven.apache.org/install.html) or [Gradle](https://gradle.org/install/).
The following examples use `Maven` and `Gradle Groovy`.
The following examples use `Maven`.
## Configuring the package registry
@ -73,40 +73,6 @@ Afterwards add the following sections to your project `pom.xml` file:
| `access_token` | Your [personal access token]({{< relref "doc/developers/api-usage.en-us.md#authentication" >}}). |
| `owner` | The owner of the package. |
### Gradle variant
When you plan to add some packages from Gitea instance in your project, you should add it in repositories section:
```groovy
repositories {
// other repositories
maven { url "https://gitea.example.com/api/packages/{owner}/maven" }
}
```
In Groovy gradle you may include next script in your publishing part:
```groovy
publishing {
// other settings of publication
repositories {
maven {
name = "Gitea"
url = uri("https://gitea.example.com/api/packages/{owner}/maven")
credentials(HttpHeaderCredentials) {
name = "Authorization"
value = "token {access_token}"
}
authentication {
header(HttpHeaderAuthentication)
}
}
}
}
```
## Publish a package
To publish a package simply run:
@ -115,12 +81,6 @@ To publish a package simply run:
mvn deploy
```
Or call `gradle` with task `publishAllPublicationsToGiteaRepository` in case you are using gradle:
```groovy
./gradlew publishAllPublicationsToGiteaRepository
```
If you want to publish a prebuild package to the registry, you can use [`mvn deploy:deploy-file`](https://maven.apache.org/plugins/maven-deploy-plugin/deploy-file-mojo.html):
```shell
@ -145,12 +105,6 @@ To install a Maven package from the package registry, add a new dependency to yo
</dependency>
```
And analog in gradle groovy:
```groovy
implementation "com.test.package:test_project:1.0.0"
```
Afterwards run:
```shell

18
main.go
View File

@ -50,20 +50,11 @@ func init() {
originalSubcommandHelpTemplate = cli.SubcommandHelpTemplate
}
func forgejoEnv() {
for _, k := range []string{"CUSTOM", "WORK_DIR"} {
if v, ok := os.LookupEnv("FORGEJO_" + k); ok {
os.Setenv("GITEA_"+k, v)
}
}
}
func main() {
forgejoEnv()
app := cli.NewApp()
app.Name = "Forgejo"
app.Usage = "Beyond coding. We forge."
app.Description = `By default, forgejo will start serving using the webserver with no
app.Name = "Gitea"
app.Usage = "A painless self-hosted Git service"
app.Description = `By default, gitea will start serving using the webserver with no
arguments - which can alternatively be run by running the subcommand web.`
app.Version = Version + formatBuiltWith()
app.Commands = []cli.Command{
@ -187,9 +178,6 @@ func adjustHelpTemplate(originalTemplate string) string {
if _, ok := os.LookupEnv("GITEA_CUSTOM"); ok {
overridden = "(GITEA_CUSTOM)"
}
if _, ok := os.LookupEnv("FORGEJO_CUSTOM"); ok {
overridden = "(FORGEJO_CUSTOM)"
}
return fmt.Sprintf(`%s
DEFAULT CONFIGURATION:

View File

@ -99,7 +99,7 @@ func (a *Action) TableIndices() []*schemas.Index {
actUserIndex.AddColumn("act_user_id", "repo_id", "created_unix", "user_id", "is_deleted")
indices := []*schemas.Index{actUserIndex, repoIndex}
if setting.Database.Type.IsPostgreSQL() {
if setting.Database.UsePostgreSQL {
cudIndex := schemas.NewIndex("c_u_d", schemas.IndexType)
cudIndex.AddColumn("created_unix", "user_id", "is_deleted")
indices = append(indices, cudIndex)
@ -640,7 +640,7 @@ func DeleteIssueActions(ctx context.Context, repoID, issueID int64) error {
// CountActionCreatedUnixString count actions where created_unix is an empty string
func CountActionCreatedUnixString(ctx context.Context) (int64, error) {
if setting.Database.Type.IsSQLite3() {
if setting.Database.UseSQLite3 {
return db.GetEngine(ctx).Where(`created_unix = ""`).Count(new(Action))
}
return 0, nil
@ -648,7 +648,7 @@ func CountActionCreatedUnixString(ctx context.Context) (int64, error) {
// FixActionCreatedUnixString set created_unix to zero if it is an empty string
func FixActionCreatedUnixString(ctx context.Context) (int64, error) {
if setting.Database.Type.IsSQLite3() {
if setting.Database.UseSQLite3 {
res, err := db.GetEngine(ctx).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`)
if err != nil {
return 0, err

View File

@ -243,7 +243,7 @@ func TestGetFeedsCorrupted(t *testing.T) {
}
func TestConsistencyUpdateAction(t *testing.T) {
if !setting.Database.Type.IsSQLite3() {
if !setting.Database.UseSQLite3 {
t.Skip("Test is only for SQLite database.")
}
assert.NoError(t, unittest.PrepareTestDatabase())

View File

@ -39,9 +39,9 @@ func getUserHeatmapData(user *user_model.User, team *organization.Team, doer *us
groupBy := "created_unix / 900 * 900"
groupByName := "timestamp" // We need this extra case because mssql doesn't allow grouping by alias
switch {
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
groupBy = "created_unix DIV 900 * 900"
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
groupByName = groupBy
}

View File

@ -32,8 +32,6 @@ const (
AccessTokenScopeAdminOrgHook AccessTokenScope = "admin:org_hook"
AccessTokenScopeAdminUserHook AccessTokenScope = "admin:user_hook"
AccessTokenScopeNotification AccessTokenScope = "notification"
AccessTokenScopeUser AccessTokenScope = "user"
@ -66,7 +64,7 @@ type AccessTokenScopeBitmap uint64
const (
// AccessTokenScopeAllBits is the bitmap of all access token scopes, except `sudo`.
AccessTokenScopeAllBits AccessTokenScopeBitmap = AccessTokenScopeRepoBits |
AccessTokenScopeAdminOrgBits | AccessTokenScopeAdminPublicKeyBits | AccessTokenScopeAdminOrgHookBits | AccessTokenScopeAdminUserHookBits |
AccessTokenScopeAdminOrgBits | AccessTokenScopeAdminPublicKeyBits | AccessTokenScopeAdminOrgHookBits |
AccessTokenScopeNotificationBits | AccessTokenScopeUserBits | AccessTokenScopeDeleteRepoBits |
AccessTokenScopePackageBits | AccessTokenScopeAdminGPGKeyBits | AccessTokenScopeAdminApplicationBits
@ -88,8 +86,6 @@ const (
AccessTokenScopeAdminOrgHookBits AccessTokenScopeBitmap = 1 << iota
AccessTokenScopeAdminUserHookBits AccessTokenScopeBitmap = 1 << iota
AccessTokenScopeNotificationBits AccessTokenScopeBitmap = 1 << iota
AccessTokenScopeUserBits AccessTokenScopeBitmap = 1<<iota | AccessTokenScopeReadUserBits | AccessTokenScopeUserEmailBits | AccessTokenScopeUserFollowBits
@ -127,7 +123,6 @@ var allAccessTokenScopes = []AccessTokenScope{
AccessTokenScopeAdminPublicKey, AccessTokenScopeWritePublicKey, AccessTokenScopeReadPublicKey,
AccessTokenScopeAdminRepoHook, AccessTokenScopeWriteRepoHook, AccessTokenScopeReadRepoHook,
AccessTokenScopeAdminOrgHook,
AccessTokenScopeAdminUserHook,
AccessTokenScopeNotification,
AccessTokenScopeUser, AccessTokenScopeReadUser, AccessTokenScopeUserEmail, AccessTokenScopeUserFollow,
AccessTokenScopeDeleteRepo,
@ -152,7 +147,6 @@ var allAccessTokenScopeBits = map[AccessTokenScope]AccessTokenScopeBitmap{
AccessTokenScopeWriteRepoHook: AccessTokenScopeWriteRepoHookBits,
AccessTokenScopeReadRepoHook: AccessTokenScopeReadRepoHookBits,
AccessTokenScopeAdminOrgHook: AccessTokenScopeAdminOrgHookBits,
AccessTokenScopeAdminUserHook: AccessTokenScopeAdminUserHookBits,
AccessTokenScopeNotification: AccessTokenScopeNotificationBits,
AccessTokenScopeUser: AccessTokenScopeUserBits,
AccessTokenScopeReadUser: AccessTokenScopeReadUserBits,
@ -269,7 +263,7 @@ func (bitmap AccessTokenScopeBitmap) ToScope() AccessTokenScope {
scope := AccessTokenScope(strings.Join(scopes, ","))
scope = AccessTokenScope(strings.ReplaceAll(
string(scope),
"repo,admin:org,admin:public_key,admin:org_hook,admin:user_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application",
"repo,admin:org,admin:public_key,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application",
"all",
))
return scope

View File

@ -40,8 +40,8 @@ func TestAccessTokenScope_Normalize(t *testing.T) {
{"admin:gpg_key,write:gpg_key,user", "user,admin:gpg_key", nil},
{"admin:application,write:application,user", "user,admin:application", nil},
{"all", "all", nil},
{"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,admin:user_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application", "all", nil},
{"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,admin:user_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application,sudo", "all,sudo", nil},
{"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application", "all", nil},
{"repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,notification,user,delete_repo,package,admin:gpg_key,admin:application,sudo", "all,sudo", nil},
}
for _, test := range tests {

View File

@ -15,7 +15,7 @@ import (
// BuildCaseInsensitiveLike returns a condition to check if the given value is like the given key case-insensitively.
// Handles especially SQLite correctly as UPPER there only transforms ASCII letters.
func BuildCaseInsensitiveLike(key, value string) builder.Cond {
if setting.Database.Type.IsSQLite3() {
if setting.Database.UseSQLite3 {
return builder.Like{"UPPER(" + key + ")", util.ToUpperASCII(value)}
}
return builder.Like{"UPPER(" + key + ")", strings.ToUpper(value)}

View File

@ -101,12 +101,12 @@ func newXORMEngine() (*xorm.Engine, error) {
var engine *xorm.Engine
if setting.Database.Type.IsPostgreSQL() && len(setting.Database.Schema) > 0 {
if setting.Database.UsePostgreSQL && len(setting.Database.Schema) > 0 {
// OK whilst we sort out our schema issues - create a schema aware postgres
registerPostgresSchemaDriver()
engine, err = xorm.NewEngine("postgresschema", connStr)
} else {
engine, err = xorm.NewEngine(setting.Database.Type.String(), connStr)
engine, err = xorm.NewEngine(setting.Database.Type, connStr)
}
if err != nil {

View File

@ -73,7 +73,7 @@ func postgresGetNextResourceIndex(ctx context.Context, tableName string, groupID
// GetNextResourceIndex generates a resource index, it must run in the same transaction where the resource is created
func GetNextResourceIndex(ctx context.Context, tableName string, groupID int64) (int64, error) {
if setting.Database.Type.IsPostgreSQL() {
if setting.Database.UsePostgreSQL {
return postgresGetNextResourceIndex(ctx, tableName, groupID)
}

View File

@ -25,7 +25,7 @@ func TestIterate(t *testing.T) {
return nil
})
assert.NoError(t, err)
assert.EqualValues(t, 84, repoCnt)
assert.EqualValues(t, 83, repoCnt)
err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repoUnit *repo_model.RepoUnit) error {
reopUnit2 := repo_model.RepoUnit{ID: repoUnit.ID}

View File

@ -35,11 +35,11 @@ func TestFind(t *testing.T) {
var repoUnits []repo_model.RepoUnit
err := db.Find(db.DefaultContext, &opts, &repoUnits)
assert.NoError(t, err)
assert.EqualValues(t, 84, len(repoUnits))
assert.EqualValues(t, 83, len(repoUnits))
cnt, err := db.Count(db.DefaultContext, &opts, new(repo_model.RepoUnit))
assert.NoError(t, err)
assert.EqualValues(t, 84, cnt)
assert.EqualValues(t, 83, cnt)
repoUnits = make([]repo_model.RepoUnit, 0, 10)
newCnt, err := db.FindAndCount(db.DefaultContext, &opts, &repoUnits)

View File

@ -13,7 +13,7 @@ import (
// CountBadSequences looks for broken sequences from recreate-table mistakes
func CountBadSequences(_ context.Context) (int64, error) {
if !setting.Database.Type.IsPostgreSQL() {
if !setting.Database.UsePostgreSQL {
return 0, nil
}
@ -34,7 +34,7 @@ func CountBadSequences(_ context.Context) (int64, error) {
// FixBadSequences fixes for broken sequences from recreate-table mistakes
func FixBadSequences(_ context.Context) error {
if !setting.Database.Type.IsPostgreSQL() {
if !setting.Database.UsePostgreSQL {
return nil
}

View File

@ -569,9 +569,3 @@
type: 3
config: "{\"IgnoreWhitespaceConflicts\":false,\"AllowMerge\":true,\"AllowRebase\":true,\"AllowRebaseMerge\":true,\"AllowSquash\":true}"
created_unix: 946684810
-
id: 84
repo_id: 56
type: 1
created_unix: 946684810

View File

@ -1634,16 +1634,3 @@
is_private: true
num_issues: 1
status: 0
-
id: 56
owner_id: 2
owner_name: user2
lower_name: readme-test
name: readme-test
default_branch: master
is_empty: false
is_archived: false
is_private: true
status: 0
num_issues: 0

View File

@ -66,7 +66,7 @@
num_followers: 2
num_following: 1
num_stars: 2
num_repos: 12
num_repos: 11
num_teams: 0
num_members: 0
visibility: 0

View File

@ -16,7 +16,7 @@
-
id: 3
owner_id: 3
org_id: 3
repo_id: 3
url: www.example.com/url3
content_type: 1 # json

View File

@ -65,7 +65,7 @@ func postgresGetCommitStatusIndex(ctx context.Context, repoID int64, sha string)
// GetNextCommitStatusIndex retried 3 times to generate a resource index
func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) {
if setting.Database.Type.IsPostgreSQL() {
if setting.Database.UsePostgreSQL {
return postgresGetCommitStatusIndex(ctx, repoID, sha)
}

View File

@ -6,6 +6,7 @@ package git
import (
"context"
"fmt"
"path"
"strings"
"time"
@ -16,7 +17,6 @@ import (
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
)
// LFSLock represents a git lfs lock of repository.
@ -34,7 +34,11 @@ func init() {
// BeforeInsert is invoked from XORM before inserting an object of this type.
func (l *LFSLock) BeforeInsert() {
l.Path = util.CleanPath(l.Path)
l.Path = cleanPath(l.Path)
}
func cleanPath(p string) string {
return path.Clean("/" + p)[1:]
}
// CreateLFSLock creates a new lock.
@ -49,7 +53,7 @@ func CreateLFSLock(ctx context.Context, repo *repo_model.Repository, lock *LFSLo
return nil, err
}
lock.Path = util.CleanPath(lock.Path)
lock.Path = cleanPath(lock.Path)
lock.RepoID = repo.ID
l, err := GetLFSLock(dbCtx, repo, lock.Path)
@ -69,7 +73,7 @@ func CreateLFSLock(ctx context.Context, repo *repo_model.Repository, lock *LFSLo
// GetLFSLock returns release by given path.
func GetLFSLock(ctx context.Context, repo *repo_model.Repository, path string) (*LFSLock, error) {
path = util.CleanPath(path)
path = cleanPath(path)
rel := &LFSLock{RepoID: repo.ID}
has, err := db.GetEngine(ctx).Where("lower(path) = ?", strings.ToLower(path)).Get(rel)
if err != nil {

View File

@ -89,7 +89,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
hasID = hasID || (column.IsPrimaryKey && column.IsAutoIncrement)
}
if hasID && setting.Database.Type.IsMSSQL() {
if hasID && setting.Database.UseMSSQL {
if _, err := sess.Exec(fmt.Sprintf("SET IDENTITY_INSERT `%s` ON", tempTableName)); err != nil {
log.Error("Unable to set identity insert for table %s. Error: %v", tempTableName, err)
return err
@ -143,7 +143,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
return err
}
if hasID && setting.Database.Type.IsMSSQL() {
if hasID && setting.Database.UseMSSQL {
if _, err := sess.Exec(fmt.Sprintf("SET IDENTITY_INSERT `%s` OFF", tempTableName)); err != nil {
log.Error("Unable to switch off identity insert for table %s. Error: %v", tempTableName, err)
return err
@ -151,7 +151,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
}
switch {
case setting.Database.Type.IsSQLite3():
case setting.Database.UseSQLite3:
// SQLite will drop all the constraints on the old table
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
log.Error("Unable to drop old table %s. Error: %v", tableName, err)
@ -178,7 +178,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
return err
}
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
// MySQL will drop all the constraints on the old table
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
log.Error("Unable to drop old table %s. Error: %v", tableName, err)
@ -205,7 +205,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
log.Error("Unable to recreate uniques on table %s. Error: %v", tableName, err)
return err
}
case setting.Database.Type.IsPostgreSQL():
case setting.Database.UsePostgreSQL:
var originalSequences []string
type sequenceData struct {
LastValue int `xorm:"'last_value'"`
@ -296,7 +296,7 @@ func RecreateTable(sess *xorm.Session, bean interface{}) error {
}
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
// MSSQL will drop all the constraints on the old table
if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
log.Error("Unable to drop old table %s. Error: %v", tableName, err)
@ -323,7 +323,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
// TODO: This will not work if there are foreign keys
switch {
case setting.Database.Type.IsSQLite3():
case setting.Database.UseSQLite3:
// First drop the indexes on the columns
res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
if errIndex != nil {
@ -405,7 +405,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
return err
}
case setting.Database.Type.IsPostgreSQL():
case setting.Database.UsePostgreSQL:
cols := ""
for _, col := range columnNames {
if cols != "" {
@ -416,7 +416,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
}
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
// Drop indexes on columns first
sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
res, err := sess.Query(sql)
@ -444,7 +444,7 @@ func DropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
}
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
cols := ""
for _, col := range columnNames {
if cols != "" {
@ -543,13 +543,13 @@ func newXORMEngine() (*xorm.Engine, error) {
func deleteDB() error {
switch {
case setting.Database.Type.IsSQLite3():
case setting.Database.UseSQLite3:
if err := util.Remove(setting.Database.Path); err != nil {
return err
}
return os.MkdirAll(path.Dir(setting.Database.Path), os.ModePerm)
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
setting.Database.User, setting.Database.Passwd, setting.Database.Host))
if err != nil {
@ -565,7 +565,7 @@ func deleteDB() error {
return err
}
return nil
case setting.Database.Type.IsPostgreSQL():
case setting.Database.UsePostgreSQL:
db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.SSLMode))
if err != nil {
@ -612,7 +612,7 @@ func deleteDB() error {
}
return nil
}
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
host, port := setting.ParseMSSQLHostPort(setting.Database.Host)
db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
host, port, "master", setting.Database.User, setting.Database.Passwd))

View File

@ -467,8 +467,6 @@ var migrations = []Migration{
// v244 -> v245
NewMigration("Add NeedApproval to actions tables", v1_20.AddNeedApprovalToActionRun),
// v245 -> v246
NewMigration("Rename Webhook org_id to owner_id", v1_20.RenameWebhookOrgToOwner),
}
// GetCurrentDBVersion returns the current db version

View File

@ -13,9 +13,9 @@ func PrependRefsHeadsToIssueRefs(x *xorm.Engine) error {
var query string
switch {
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
query = "UPDATE `issue` SET `ref` = 'refs/heads/' + `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
query = "UPDATE `issue` SET `ref` = CONCAT('refs/heads/', `ref`) WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%';"
default:
query = "UPDATE `issue` SET `ref` = 'refs/heads/' || `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"

View File

@ -41,7 +41,7 @@ func FixLanguageStatsToSaveSize(x *xorm.Engine) error {
// Delete language stat statuses
truncExpr := "TRUNCATE TABLE"
if setting.Database.Type.IsSQLite3() {
if setting.Database.UseSQLite3 {
truncExpr = "DELETE FROM"
}

View File

@ -21,7 +21,7 @@ func IncreaseLanguageField(x *xorm.Engine) error {
return err
}
if setting.Database.Type.IsSQLite3() {
if setting.Database.UseSQLite3 {
// SQLite maps VARCHAR to TEXT without size so we're done
return nil
}
@ -41,11 +41,11 @@ func IncreaseLanguageField(x *xorm.Engine) error {
}
switch {
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE language_stat MODIFY COLUMN language %s", sqlType)); err != nil {
return err
}
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
// Yet again MSSQL just has to be awkward.
// Here we have to drop the constraints first and then rebuild them
constraints := make([]string, 0)
@ -71,7 +71,7 @@ func IncreaseLanguageField(x *xorm.Engine) error {
if err := sess.CreateUniques(new(LanguageStat)); err != nil {
return err
}
case setting.Database.Type.IsPostgreSQL():
case setting.Database.UsePostgreSQL:
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE language_stat ALTER COLUMN language TYPE %s", sqlType)); err != nil {
return err
}

View File

@ -17,13 +17,13 @@ import (
func SetDefaultPasswordToArgon2(x *xorm.Engine) error {
switch {
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
_, err := x.Exec("ALTER TABLE `user` ALTER passwd_hash_algo SET DEFAULT 'argon2';")
return err
case setting.Database.Type.IsPostgreSQL():
case setting.Database.UsePostgreSQL:
_, err := x.Exec("ALTER TABLE `user` ALTER COLUMN passwd_hash_algo SET DEFAULT 'argon2';")
return err
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
// need to find the constraint and drop it, then recreate it.
sess := x.NewSession()
defer sess.Close()
@ -53,7 +53,7 @@ func SetDefaultPasswordToArgon2(x *xorm.Engine) error {
}
return sess.Commit()
case setting.Database.Type.IsSQLite3():
case setting.Database.UseSQLite3:
// drop through
default:
log.Fatal("Unrecognized DB")

View File

@ -62,7 +62,7 @@ func UpdateCodeCommentReplies(x *xorm.Engine) error {
return err
}
if setting.Database.Type.IsMSSQL() {
if setting.Database.UseMSSQL {
if _, err := sess.Exec(sqlSelect + " INTO #temp_comments" + sqlTail); err != nil {
log.Error("unable to create temporary table")
return err
@ -72,13 +72,13 @@ func UpdateCodeCommentReplies(x *xorm.Engine) error {
comments := make([]*Comment, 0, batchSize)
switch {
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
sqlCmd = sqlSelect + sqlTail + " LIMIT " + strconv.Itoa(batchSize) + ", " + strconv.Itoa(start)
case setting.Database.Type.IsPostgreSQL():
case setting.Database.UsePostgreSQL:
fallthrough
case setting.Database.Type.IsSQLite3():
case setting.Database.UseSQLite3:
sqlCmd = sqlSelect + sqlTail + " LIMIT " + strconv.Itoa(batchSize) + " OFFSET " + strconv.Itoa(start)
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
sqlCmd = "SELECT TOP " + strconv.Itoa(batchSize) + " * FROM #temp_comments WHERE " +
"(id NOT IN ( SELECT TOP " + strconv.Itoa(start) + " id FROM #temp_comments ORDER BY id )) ORDER BY id"
default:

View File

@ -14,7 +14,7 @@ import (
)
func FixPostgresIDSequences(x *xorm.Engine) error {
if !setting.Database.Type.IsPostgreSQL() {
if !setting.Database.UsePostgreSQL {
return nil
}

View File

@ -54,11 +54,11 @@ func RenameTaskErrorsToMessage(x *xorm.Engine) error {
}
switch {
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
if _, err := sess.Exec("ALTER TABLE `task` CHANGE errors message text"); err != nil {
return err
}
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
if _, err := sess.Exec("sp_rename 'task.errors', 'message', 'COLUMN'"); err != nil {
return err
}

View File

@ -16,7 +16,7 @@ func AlterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error {
return err
}
if setting.Database.Type.IsMySQL() {
if setting.Database.UseMySQL {
if _, err := sess.Exec("ALTER TABLE `issue` CHANGE `content` `content` LONGTEXT"); err != nil {
return err
}

View File

@ -16,7 +16,7 @@ func AlterHookTaskTextFieldsToLongText(x *xorm.Engine) error {
return err
}
if setting.Database.Type.IsMySQL() {
if setting.Database.UseMySQL {
if _, err := sess.Exec("ALTER TABLE `hook_task` CHANGE `payload_content` `payload_content` LONGTEXT, CHANGE `request_content` `request_content` LONGTEXT, change `response_content` `response_content` LONGTEXT"); err != nil {
return err
}

View File

@ -38,7 +38,7 @@ func (*improveActionTableIndicesAction) TableIndices() []*schemas.Index {
actUserIndex := schemas.NewIndex("au_r_c_u_d", schemas.IndexType)
actUserIndex.AddColumn("act_user_id", "repo_id", "created_unix", "user_id", "is_deleted")
indices := []*schemas.Index{actUserIndex, repoIndex}
if setting.Database.Type.IsPostgreSQL() {
if setting.Database.UsePostgreSQL {
cudIndex := schemas.NewIndex("c_u_d", schemas.IndexType)
cudIndex.AddColumn("created_unix", "user_id", "is_deleted")
indices = append(indices, cudIndex)

View File

@ -65,11 +65,11 @@ func RenameCredentialIDBytes(x *xorm.Engine) error {
}
switch {
case setting.Database.Type.IsMySQL():
case setting.Database.UseMySQL:
if _, err := sess.Exec("ALTER TABLE `webauthn_credential` CHANGE credential_id_bytes credential_id VARBINARY(1024)"); err != nil {
return err
}
case setting.Database.Type.IsMSSQL():
case setting.Database.UseMSSQL:
if _, err := sess.Exec("sp_rename 'webauthn_credential.credential_id_bytes', 'credential_id', 'COLUMN'"); err != nil {
return err
}

View File

@ -16,7 +16,7 @@ func AlterPublicGPGKeyContentFieldsToMediumText(x *xorm.Engine) error {
return err
}
if setting.Database.Type.IsMySQL() {
if setting.Database.UseMySQL {
if _, err := sess.Exec("ALTER TABLE `gpg_key` CHANGE `content` `content` MEDIUMTEXT"); err != nil {
return err
}

View File

@ -16,7 +16,7 @@ func AlterPackageVersionMetadataToLongText(x *xorm.Engine) error {
return err
}
if setting.Database.Type.IsMySQL() {
if setting.Database.UseMySQL {
if _, err := sess.Exec("ALTER TABLE `package_version` MODIFY COLUMN `metadata_json` LONGTEXT"); err != nil {
return err
}

View File

@ -17,7 +17,7 @@ func AlterPublicGPGKeyImportContentFieldToMediumText(x *xorm.Engine) error {
return err
}
if setting.Database.Type.IsMySQL() {
if setting.Database.UseMySQL {
if _, err := sess.Exec("ALTER TABLE `gpg_key_import` CHANGE `content` `content` MEDIUMTEXT"); err != nil {
return err
}

View File

@ -1,74 +0,0 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package v1_20 //nolint
import (
"context"
"fmt"
"code.gitea.io/gitea/models/migrations/base"
"code.gitea.io/gitea/modules/setting"
"xorm.io/xorm"
)
func RenameWebhookOrgToOwner(x *xorm.Engine) error {
type Webhook struct {
OrgID int64 `xorm:"INDEX"`
}
// This migration maybe rerun so that we should check if it has been run
ownerExist, err := x.Dialect().IsColumnExist(x.DB(), context.Background(), "webhook", "owner_id")
if err != nil {
return err
}
if ownerExist {
orgExist, err := x.Dialect().IsColumnExist(x.DB(), context.Background(), "webhook", "org_id")
if err != nil {
return err
}
if !orgExist {
return nil
}
}
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if err := sess.Sync2(new(Webhook)); err != nil {
return err
}
if ownerExist {
if err := base.DropTableColumns(sess, "webhook", "owner_id"); err != nil {
return err
}
}
switch {
case setting.Database.Type.IsMySQL():
inferredTable, err := x.TableInfo(new(Webhook))
if err != nil {
return err
}
sqlType := x.Dialect().SQLType(inferredTable.GetColumn("org_id"))
if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `webhook` CHANGE org_id owner_id %s", sqlType)); err != nil {
return err
}
case setting.Database.Type.IsMSSQL():
if _, err := sess.Exec("sp_rename 'webhook.org_id', 'owner_id', 'COLUMN'"); err != nil {
return err
}
default:
if _, err := sess.Exec("ALTER TABLE `webhook` RENAME COLUMN org_id TO owner_id"); err != nil {
return err
}
}
return sess.Commit()
}

View File

@ -239,32 +239,6 @@ func (org *Organization) CustomAvatarRelativePath() string {
return org.Avatar
}
// UnitPermission returns unit permission
func (org *Organization) UnitPermission(ctx context.Context, doer *user_model.User, unitType unit.Type) perm.AccessMode {
if doer != nil {
teams, err := GetUserOrgTeams(ctx, org.ID, doer.ID)
if err != nil {
log.Error("GetUserOrgTeams: %v", err)
return perm.AccessModeNone
}
if err := teams.LoadUnits(ctx); err != nil {
log.Error("LoadUnits: %v", err)
return perm.AccessModeNone
}
if len(teams) > 0 {
return teams.UnitMaxAccess(unitType)
}
}
if org.Visibility.IsPublic() {
return perm.AccessModeRead
}
return perm.AccessModeNone
}
// CreateOrganization creates record of a new organization.
func CreateOrganization(org *Organization, owner *user_model.User) (err error) {
if !owner.CanCreateOrganization() {

View File

@ -409,7 +409,7 @@ func DeleteProjectByID(ctx context.Context, id int64) error {
func DeleteProjectByRepoID(ctx context.Context, repoID int64) error {
switch {
case setting.Database.Type.IsSQLite3():
case setting.Database.UseSQLite3:
if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue WHERE project_issue.id IN (SELECT project_issue.id FROM project_issue INNER JOIN project WHERE project.id = project_issue.project_id AND project.repo_id = ?)", repoID); err != nil {
return err
}
@ -419,7 +419,7 @@ func DeleteProjectByRepoID(ctx context.Context, repoID int64) error {
if _, err := db.GetEngine(ctx).Table("project").Where("repo_id = ? ", repoID).Delete(&Project{}); err != nil {
return err
}
case setting.Database.Type.IsPostgreSQL():
case setting.Database.UsePostgreSQL:
if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue USING project WHERE project.id = project_issue.project_id AND project.repo_id = ? ", repoID); err != nil {
return err
}

View File

@ -498,7 +498,7 @@ func SearchRepositoryCondition(opts *SearchRepoOptions) builder.Cond {
subQueryCond := builder.NewCond()
// Topic checking. Topics are present.
if setting.Database.Type.IsPostgreSQL() { // postgres stores the topics as json and not as text
if setting.Database.UsePostgreSQL { // postgres stores the topics as json and not as text
subQueryCond = subQueryCond.Or(builder.And(builder.NotNull{"topics"}, builder.Neq{"(topics)::text": "[]"}))
} else {
subQueryCond = subQueryCond.Or(builder.And(builder.Neq{"topics": "null"}, builder.Neq{"topics": "[]"}))

View File

@ -76,7 +76,7 @@ func MainTest(m *testing.M, testOpts *TestOptions) {
setting.SSH.BuiltinServerUser = "builtinuser"
setting.SSH.Port = 3000
setting.SSH.Domain = "try.gitea.io"
setting.Database.Type = "sqlite3"
setting.Database.UseSQLite3 = true
setting.Repository.DefaultBranch = "master" // many test code still assume that default branch is called "master"
repoRootPath, err := os.MkdirTemp(os.TempDir(), "repos")
if err != nil {

View File

@ -393,11 +393,6 @@ func (u *User) IsOrganization() bool {
return u.Type == UserTypeOrganization
}
// IsIndividual returns true if user is actually a individual user.
func (u *User) IsIndividual() bool {
return u.Type == UserTypeIndividual
}
// DisplayName returns full name if it's not empty,
// returns username otherwise.
func (u *User) DisplayName() string {
@ -535,7 +530,6 @@ var (
"user",
"v2",
"gitea-actions",
"forgejo-actions",
}
reservedUserPatterns = []string{"*.keys", "*.gpg", "*.rss", "*.atom"}

View File

@ -37,9 +37,9 @@ func NewReplaceUser(name string) *User {
const (
ActionsUserID = -2
ActionsUserName = "forgejo-actions"
ActionsFullName = "Forgejo Actions"
ActionsEmail = "noreply@forgejo.org"
ActionsUserName = "gitea-actions"
ActionsFullName = "Gitea Actions"
ActionsEmail = "teabot@gitea.io"
)
// NewActionsUser creates and returns a fake user for running the actions.

View File

@ -122,7 +122,7 @@ func IsValidHookContentType(name string) bool {
type Webhook struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX"` // An ID of 0 indicates either a default or system webhook
OwnerID int64 `xorm:"INDEX"`
OrgID int64 `xorm:"INDEX"`
IsSystemWebhook bool
URL string `xorm:"url TEXT"`
HTTPMethod string `xorm:"http_method"`
@ -412,11 +412,11 @@ func GetWebhookByRepoID(repoID, id int64) (*Webhook, error) {
})
}
// GetWebhookByOwnerID returns webhook of a user or organization by given ID.
func GetWebhookByOwnerID(ownerID, id int64) (*Webhook, error) {
// GetWebhookByOrgID returns webhook of organization by given ID.
func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
return getWebhook(&Webhook{
ID: id,
OwnerID: ownerID,
ID: id,
OrgID: orgID,
})
}
@ -424,7 +424,7 @@ func GetWebhookByOwnerID(ownerID, id int64) (*Webhook, error) {
type ListWebhookOptions struct {
db.ListOptions
RepoID int64
OwnerID int64
OrgID int64
IsActive util.OptionalBool
}
@ -433,8 +433,8 @@ func (opts *ListWebhookOptions) toCond() builder.Cond {
if opts.RepoID != 0 {
cond = cond.And(builder.Eq{"webhook.repo_id": opts.RepoID})
}
if opts.OwnerID != 0 {
cond = cond.And(builder.Eq{"webhook.owner_id": opts.OwnerID})
if opts.OrgID != 0 {
cond = cond.And(builder.Eq{"webhook.org_id": opts.OrgID})
}
if !opts.IsActive.IsNone() {
cond = cond.And(builder.Eq{"webhook.is_active": opts.IsActive.IsTrue()})
@ -503,10 +503,10 @@ func DeleteWebhookByRepoID(repoID, id int64) error {
})
}
// DeleteWebhookByOwnerID deletes webhook of a user or organization by given ID.
func DeleteWebhookByOwnerID(ownerID, id int64) error {
// DeleteWebhookByOrgID deletes webhook of organization by given ID.
func DeleteWebhookByOrgID(orgID, id int64) error {
return deleteWebhook(&Webhook{
ID: id,
OwnerID: ownerID,
ID: id,
OrgID: orgID,
})
}

View File

@ -15,7 +15,7 @@ import (
func GetDefaultWebhooks(ctx context.Context) ([]*Webhook, error) {
webhooks := make([]*Webhook, 0, 5)
return webhooks, db.GetEngine(ctx).
Where("repo_id=? AND owner_id=? AND is_system_webhook=?", 0, 0, false).
Where("repo_id=? AND org_id=? AND is_system_webhook=?", 0, 0, false).
Find(&webhooks)
}
@ -23,7 +23,7 @@ func GetDefaultWebhooks(ctx context.Context) ([]*Webhook, error) {
func GetSystemOrDefaultWebhook(ctx context.Context, id int64) (*Webhook, error) {
webhook := &Webhook{ID: id}
has, err := db.GetEngine(ctx).
Where("repo_id=? AND owner_id=?", 0, 0).
Where("repo_id=? AND org_id=?", 0, 0).
Get(webhook)
if err != nil {
return nil, err
@ -38,11 +38,11 @@ func GetSystemWebhooks(ctx context.Context, isActive util.OptionalBool) ([]*Webh
webhooks := make([]*Webhook, 0, 5)
if isActive.IsNone() {
return webhooks, db.GetEngine(ctx).
Where("repo_id=? AND owner_id=? AND is_system_webhook=?", 0, 0, true).
Where("repo_id=? AND org_id=? AND is_system_webhook=?", 0, 0, true).
Find(&webhooks)
}
return webhooks, db.GetEngine(ctx).
Where("repo_id=? AND owner_id=? AND is_system_webhook=? AND is_active = ?", 0, 0, true, isActive.IsTrue()).
Where("repo_id=? AND org_id=? AND is_system_webhook=? AND is_active = ?", 0, 0, true, isActive.IsTrue()).
Find(&webhooks)
}
@ -50,7 +50,7 @@ func GetSystemWebhooks(ctx context.Context, isActive util.OptionalBool) ([]*Webh
func DeleteDefaultSystemWebhook(ctx context.Context, id int64) error {
return db.WithTx(ctx, func(ctx context.Context) error {
count, err := db.GetEngine(ctx).
Where("repo_id=? AND owner_id=?", 0, 0).
Where("repo_id=? AND org_id=?", 0, 0).
Delete(&Webhook{ID: id})
if err != nil {
return err

View File

@ -109,13 +109,13 @@ func TestGetWebhookByRepoID(t *testing.T) {
assert.True(t, IsErrWebhookNotExist(err))
}
func TestGetWebhookByOwnerID(t *testing.T) {
func TestGetWebhookByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hook, err := GetWebhookByOwnerID(3, 3)
hook, err := GetWebhookByOrgID(3, 3)
assert.NoError(t, err)
assert.Equal(t, int64(3), hook.ID)
_, err = GetWebhookByOwnerID(unittest.NonexistentID, unittest.NonexistentID)
_, err = GetWebhookByOrgID(unittest.NonexistentID, unittest.NonexistentID)
assert.Error(t, err)
assert.True(t, IsErrWebhookNotExist(err))
}
@ -140,9 +140,9 @@ func TestGetWebhooksByRepoID(t *testing.T) {
}
}
func TestGetActiveWebhooksByOwnerID(t *testing.T) {
func TestGetActiveWebhooksByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hooks, err := ListWebhooksByOpts(db.DefaultContext, &ListWebhookOptions{OwnerID: 3, IsActive: util.OptionalBoolTrue})
hooks, err := ListWebhooksByOpts(db.DefaultContext, &ListWebhookOptions{OrgID: 3, IsActive: util.OptionalBoolTrue})
assert.NoError(t, err)
if assert.Len(t, hooks, 1) {
assert.Equal(t, int64(3), hooks[0].ID)
@ -150,9 +150,9 @@ func TestGetActiveWebhooksByOwnerID(t *testing.T) {
}
}
func TestGetWebhooksByOwnerID(t *testing.T) {
func TestGetWebhooksByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hooks, err := ListWebhooksByOpts(db.DefaultContext, &ListWebhookOptions{OwnerID: 3})
hooks, err := ListWebhooksByOpts(db.DefaultContext, &ListWebhookOptions{OrgID: 3})
assert.NoError(t, err)
if assert.Len(t, hooks, 1) {
assert.Equal(t, int64(3), hooks[0].ID)
@ -181,13 +181,13 @@ func TestDeleteWebhookByRepoID(t *testing.T) {
assert.True(t, IsErrWebhookNotExist(err))
}
func TestDeleteWebhookByOwnerID(t *testing.T) {
func TestDeleteWebhookByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OwnerID: 3})
assert.NoError(t, DeleteWebhookByOwnerID(3, 3))
unittest.AssertNotExistsBean(t, &Webhook{ID: 3, OwnerID: 3})
unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OrgID: 3})
assert.NoError(t, DeleteWebhookByOrgID(3, 3))
unittest.AssertNotExistsBean(t, &Webhook{ID: 3, OrgID: 3})
err := DeleteWebhookByOwnerID(unittest.NonexistentID, unittest.NonexistentID)
err := DeleteWebhookByOrgID(unittest.NonexistentID, unittest.NonexistentID)
assert.Error(t, err)
assert.True(t, IsErrWebhookNotExist(err))
}

View File

@ -19,10 +19,7 @@ import (
)
func ListWorkflows(commit *git.Commit) (git.Entries, error) {
tree, err := commit.SubTree(".forgejo/workflows")
if _, ok := err.(git.ErrNotExist); ok {
tree, err = commit.SubTree(".gitea/workflows")
}
tree, err := commit.SubTree(".gitea/workflows")
if _, ok := err.(git.ErrNotExist); ok {
tree, err = commit.SubTree(".github/workflows")
}

View File

@ -6,7 +6,6 @@ package cache
import (
"context"
"sync"
"time"
"code.gitea.io/gitea/modules/log"
)
@ -15,151 +14,65 @@ import (
// This is useful for caching data that is expensive to calculate and is likely to be
// used multiple times in a request.
type cacheContext struct {
data map[any]map[any]any
lock sync.RWMutex
created time.Time
discard bool
ctx context.Context
data map[any]map[any]any
lock sync.RWMutex
}
func (cc *cacheContext) Get(tp, key any) any {
cc.lock.RLock()
defer cc.lock.RUnlock()
if cc.data[tp] == nil {
return nil
}
return cc.data[tp][key]
}
func (cc *cacheContext) Put(tp, key, value any) {
cc.lock.Lock()
defer cc.lock.Unlock()
if cc.discard {
return
if cc.data[tp] == nil {
cc.data[tp] = make(map[any]any)
}
d := cc.data[tp]
if d == nil {
d = make(map[any]any)
cc.data[tp] = d
}
d[key] = value
cc.data[tp][key] = value
}
func (cc *cacheContext) Delete(tp, key any) {
cc.lock.Lock()
defer cc.lock.Unlock()
if cc.data[tp] == nil {
return
}
delete(cc.data[tp], key)
}
func (cc *cacheContext) Discard() {
cc.lock.Lock()
defer cc.lock.Unlock()
cc.data = nil
cc.discard = true
}
func (cc *cacheContext) isDiscard() bool {
cc.lock.RLock()
defer cc.lock.RUnlock()
return cc.discard
}
// cacheContextLifetime is the max lifetime of cacheContext.
// Since cacheContext is used to cache data in a request level context, 10s is enough.
// If a cacheContext is used more than 10s, it's probably misuse.
const cacheContextLifetime = 10 * time.Second
var timeNow = time.Now
func (cc *cacheContext) Expired() bool {
return timeNow().Sub(cc.created) > cacheContextLifetime
}
var cacheContextKey = struct{}{}
/*
Since there are both WithCacheContext and WithNoCacheContext,
it may be confusing when there is nesting.
Some cases to explain the design:
When:
- A, B or C means a cache context.
- A', B' or C' means a discard cache context.
- ctx means context.Backgrand().
- A(ctx) means a cache context with ctx as the parent context.
- B(A(ctx)) means a cache context with A(ctx) as the parent context.
- With is alias of WithCacheContext.
- WithNo is alias of WithNoCacheContext.
So:
- With(ctx) -> A(ctx)
- With(With(ctx)) -> A(ctx), not B(A(ctx)), always reuse parent cache context if possible.
- With(With(With(ctx))) -> A(ctx), not C(B(A(ctx))), ditto.
- WithNo(ctx) -> ctx, not A'(ctx), don't create new cache context if we don't have to.
- WithNo(With(ctx)) -> A'(ctx)
- WithNo(WithNo(With(ctx))) -> A'(ctx), not B'(A'(ctx)), don't create new cache context if we don't have to.
- With(WithNo(With(ctx))) -> B(A'(ctx)), not A(ctx), never reuse a discard cache context.
- WithNo(With(WithNo(With(ctx)))) -> B'(A'(ctx))
- With(WithNo(With(WithNo(With(ctx))))) -> C(B'(A'(ctx))), so there's always only one not-discard cache context.
*/
func WithCacheContext(ctx context.Context) context.Context {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
if !c.isDiscard() {
// reuse parent context
return ctx
}
}
return context.WithValue(ctx, cacheContextKey, &cacheContext{
data: make(map[any]map[any]any),
created: timeNow(),
ctx: ctx,
data: make(map[any]map[any]any),
})
}
func WithNoCacheContext(ctx context.Context) context.Context {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
// The caller want to run long-life tasks, but the parent context is a cache context.
// So we should disable and clean the cache data, or it will be kept in memory for a long time.
c.Discard()
return ctx
}
return ctx
}
func GetContextData(ctx context.Context, tp, key any) any {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
if c.Expired() {
// The warning means that the cache context is misused for long-life task,
// it can be resolved with WithNoCacheContext(ctx).
log.Warn("cache context is expired, may be misused for long-life tasks: %v", c)
return nil
}
return c.Get(tp, key)
}
log.Warn("cannot get cache context when getting data: %v", ctx)
return nil
}
func SetContextData(ctx context.Context, tp, key, value any) {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
if c.Expired() {
// The warning means that the cache context is misused for long-life task,
// it can be resolved with WithNoCacheContext(ctx).
log.Warn("cache context is expired, may be misused for long-life tasks: %v", c)
return
}
c.Put(tp, key, value)
return
}
log.Warn("cannot get cache context when setting data: %v", ctx)
}
func RemoveContextData(ctx context.Context, tp, key any) {
if c, ok := ctx.Value(cacheContextKey).(*cacheContext); ok {
if c.Expired() {
// The warning means that the cache context is misused for long-life task,
// it can be resolved with WithNoCacheContext(ctx).
log.Warn("cache context is expired, may be misused for long-life tasks: %v", c)
return
}
c.Delete(tp, key)
}
}

View File

@ -6,7 +6,6 @@ package cache
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
@ -26,7 +25,7 @@ func TestWithCacheContext(t *testing.T) {
assert.EqualValues(t, 1, v.(int))
RemoveContextData(ctx, field, "my_config1")
RemoveContextData(ctx, field, "my_config2") // remove a non-exist key
RemoveContextData(ctx, field, "my_config2") // remove an non-exist key
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v)
@ -39,40 +38,4 @@ func TestWithCacheContext(t *testing.T) {
v = GetContextData(ctx, field, "my_config1")
assert.EqualValues(t, 1, v)
now := timeNow
defer func() {
timeNow = now
}()
timeNow = func() time.Time {
return now().Add(10 * time.Second)
}
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v)
}
func TestWithNoCacheContext(t *testing.T) {
ctx := context.Background()
const field = "system_setting"
v := GetContextData(ctx, field, "my_config1")
assert.Nil(t, v)
SetContextData(ctx, field, "my_config1", 1)
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v) // still no cache
ctx = WithCacheContext(ctx)
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v)
SetContextData(ctx, field, "my_config1", 1)
v = GetContextData(ctx, field, "my_config1")
assert.NotNil(t, v)
ctx = WithNoCacheContext(ctx)
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v)
SetContextData(ctx, field, "my_config1", 1)
v = GetContextData(ctx, field, "my_config1")
assert.Nil(t, v) // still no cache
}

View File

@ -6,9 +6,7 @@ package context
import (
"bytes"
"context"
"fmt"
"net/http"
"strings"
"text/template"
"time"
@ -22,39 +20,13 @@ type routerLoggerOptions struct {
Start *time.Time
ResponseWriter http.ResponseWriter
Ctx map[string]interface{}
RequestID *string
}
var signedUserNameStringPointerKey interface{} = "signedUserNameStringPointerKey"
const keyOfRequestIDInTemplate = ".RequestID"
// According to:
// TraceId: A valid trace identifier is a 16-byte array with at least one non-zero byte
// MD5 output is 16 or 32 bytes: md5-bytes is 16, md5-hex is 32
// SHA1: similar, SHA1-bytes is 20, SHA1-hex is 40.
// UUID is 128-bit, 32 hex chars, 36 ASCII chars with 4 dashes
// So, we accept a Request ID with a maximum character length of 40
const maxRequestIDByteLength = 40
func parseRequestIDFromRequestHeader(req *http.Request) string {
requestID := "-"
for _, key := range setting.Log.RequestIDHeaders {
if req.Header.Get(key) != "" {
requestID = req.Header.Get(key)
break
}
}
if len(requestID) > maxRequestIDByteLength {
requestID = fmt.Sprintf("%s...", requestID[:maxRequestIDByteLength])
}
return requestID
}
// AccessLogger returns a middleware to log access logger
func AccessLogger() func(http.Handler) http.Handler {
logger := log.GetLogger("access")
needRequestID := len(setting.Log.RequestIDHeaders) > 0 && strings.Contains(setting.Log.AccessLogTemplate, keyOfRequestIDInTemplate)
logTemplate, _ := template.New("log").Parse(setting.Log.AccessLogTemplate)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
@ -62,11 +34,6 @@ func AccessLogger() func(http.Handler) http.Handler {
identity := "-"
r := req.WithContext(context.WithValue(req.Context(), signedUserNameStringPointerKey, &identity))
var requestID string
if needRequestID {
requestID = parseRequestIDFromRequestHeader(req)
}
next.ServeHTTP(w, r)
rw := w.(ResponseWriter)
@ -80,7 +47,6 @@ func AccessLogger() func(http.Handler) http.Handler {
"RemoteAddr": req.RemoteAddr,
"Req": req,
},
RequestID: &requestID,
})
if err != nil {
log.Error("Could not set up chi access logger: %v", err.Error())

View File

@ -188,20 +188,13 @@ func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
}
}
func getOtpHeader(header http.Header) string {
otpHeader := header.Get("X-Gitea-OTP")
if forgejoHeader := header.Get("X-Forgejo-OTP"); forgejoHeader != "" {
otpHeader = forgejoHeader
}
return otpHeader
}
// CheckForOTP validates OTP
func (ctx *APIContext) CheckForOTP() {
if skip, ok := ctx.Data["SkipLocalTwoFA"]; ok && skip.(bool) {
return // Skip 2FA
}
otpHeader := ctx.Req.Header.Get("X-Gitea-OTP")
twofa, err := auth.GetTwoFactorByUID(ctx.Context.Doer.ID)
if err != nil {
if auth.IsErrTwoFactorNotEnrolled(err) {
@ -210,7 +203,7 @@ func (ctx *APIContext) CheckForOTP() {
ctx.Context.Error(http.StatusInternalServerError)
return
}
ok, err := twofa.ValidateTOTP(getOtpHeader(ctx.Req.Header))
ok, err := twofa.ValidateTOTP(otpHeader)
if err != nil {
ctx.Context.Error(http.StatusInternalServerError)
return
@ -251,7 +244,7 @@ func APIContexter() func(http.Handler) http.Handler {
}
}
httpcache.SetCacheControlInHeader(ctx.Resp.Header(), 0, "no-transform")
httpcache.AddCacheControlToHeader(ctx.Resp.Header(), 0, "no-transform")
ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
ctx.Data["Context"] = &ctx

View File

@ -1,23 +0,0 @@
// SPDX-License-Identifier: MIT
package context
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetOtpHeader(t *testing.T) {
header := http.Header{}
assert.EqualValues(t, "", getOtpHeader(header))
// Gitea
giteaOtp := "123456"
header.Set("X-Gitea-OTP", giteaOtp)
assert.EqualValues(t, giteaOtp, getOtpHeader(header))
// Forgejo has precedence
forgejoOtp := "abcdef"
header.Set("X-Forgejo-OTP", forgejoOtp)
assert.EqualValues(t, forgejoOtp, getOtpHeader(header))
}

View File

@ -388,7 +388,7 @@ func (ctx *Context) SetServeHeaders(opts *ServeHeaderOptions) {
if duration == 0 {
duration = 5 * time.Minute
}
httpcache.SetCacheControlInHeader(header, duration)
httpcache.AddCacheControlToHeader(header, duration)
if !opts.LastModified.IsZero() {
header.Set("Last-Modified", opts.LastModified.UTC().Format(http.TimeFormat))
@ -753,7 +753,7 @@ func Contexter(ctx context.Context) func(next http.Handler) http.Handler {
}
}
httpcache.SetCacheControlInHeader(ctx.Resp.Header(), 0, "no-transform")
httpcache.AddCacheControlToHeader(ctx.Resp.Header(), 0, "no-transform")
ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
ctx.Data["CsrfToken"] = ctx.csrf.GetToken()

View File

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/models/perm"
"code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
)
@ -30,34 +31,29 @@ type Organization struct {
}
func (org *Organization) CanWriteUnit(ctx *Context, unitType unit.Type) bool {
return org.Organization.UnitPermission(ctx, ctx.Doer, unitType) >= perm.AccessModeWrite
}
func (org *Organization) CanReadUnit(ctx *Context, unitType unit.Type) bool {
return org.Organization.UnitPermission(ctx, ctx.Doer, unitType) >= perm.AccessModeRead
}
func GetOrganizationByParams(ctx *Context) {
orgName := ctx.Params(":org")
var err error
ctx.Org.Organization, err = organization.GetOrgByName(ctx, orgName)
if err != nil {
if organization.IsErrOrgNotExist(err) {
redirectUserID, err := user_model.LookupUserRedirect(orgName)
if err == nil {
RedirectToUser(ctx, orgName, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {
ctx.NotFound("GetUserByName", err)
} else {
ctx.ServerError("LookupUserRedirect", err)
}
} else {
ctx.ServerError("GetUserByName", err)
}
return
if ctx.Doer == nil {
return false
}
return org.UnitPermission(ctx, ctx.Doer.ID, unitType) >= perm.AccessModeWrite
}
func (org *Organization) UnitPermission(ctx *Context, doerID int64, unitType unit.Type) perm.AccessMode {
if doerID > 0 {
teams, err := organization.GetUserOrgTeams(ctx, org.Organization.ID, doerID)
if err != nil {
log.Error("GetUserOrgTeams: %v", err)
return perm.AccessModeNone
}
if len(teams) > 0 {
return teams.UnitMaxAccess(unitType)
}
}
if org.Organization.Visibility == structs.VisibleTypePublic {
return perm.AccessModeRead
}
return perm.AccessModeNone
}
// HandleOrgAssignment handles organization assignment
@ -81,26 +77,25 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
requireTeamAdmin = args[3]
}
var err error
orgName := ctx.Params(":org")
if ctx.ContextUser == nil {
// if Organization is not defined, get it from params
if ctx.Org.Organization == nil {
GetOrganizationByParams(ctx)
if ctx.Written() {
return
var err error
ctx.Org.Organization, err = organization.GetOrgByName(ctx, orgName)
if err != nil {
if organization.IsErrOrgNotExist(err) {
redirectUserID, err := user_model.LookupUserRedirect(orgName)
if err == nil {
RedirectToUser(ctx, orgName, redirectUserID)
} else if user_model.IsErrUserRedirectNotExist(err) {
ctx.NotFound("GetUserByName", err)
} else {
ctx.ServerError("LookupUserRedirect", err)
}
} else {
ctx.ServerError("GetUserByName", err)
}
} else if ctx.ContextUser.IsOrganization() {
if ctx.Org == nil {
ctx.Org = &Organization{}
}
ctx.Org.Organization = (*organization.Organization)(ctx.ContextUser)
} else {
// ContextUser is an individual User
return
}
org := ctx.Org.Organization
// Handle Visibility
@ -161,7 +156,6 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
}
ctx.Data["IsOrganizationOwner"] = ctx.Org.IsOwner
ctx.Data["IsOrganizationMember"] = ctx.Org.IsMember
ctx.Data["IsProjectEnabled"] = true
ctx.Data["IsPackageEnabled"] = setting.Packages.Enabled
ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
ctx.Data["IsPublicMember"] = func(uid int64) bool {
@ -237,10 +231,6 @@ func HandleOrgAssignment(ctx *Context, args ...bool) {
return
}
}
ctx.Data["CanReadProjects"] = ctx.Org.CanReadUnit(ctx, unit.TypeProjects)
ctx.Data["CanReadPackages"] = ctx.Org.CanReadUnit(ctx, unit.TypePackages)
ctx.Data["CanReadCode"] = ctx.Org.CanReadUnit(ctx, unit.TypeCode)
}
// OrgAssignment returns a middleware to handle organization assignment

View File

@ -11,7 +11,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/markup"
"github.com/stretchr/testify/assert"
@ -230,10 +229,7 @@ John Doe john@doe.com This,note,had,a,lot,of,commas,to,test,delimiters`,
}
for n, c := range cases {
delimiter := determineDelimiter(&markup.RenderContext{
Ctx: git.DefaultContext,
RelativePath: c.filename,
}, []byte(decodeSlashes(t, c.csv)))
delimiter := determineDelimiter(&markup.RenderContext{RelativePath: c.filename}, []byte(decodeSlashes(t, c.csv)))
assert.EqualValues(t, c.expectedDelimiter, delimiter, "case %d: delimiter should be equal, expected '%c' got '%c'", n, c.expectedDelimiter, delimiter)
}
}

View File

@ -155,7 +155,7 @@ func checkDBConsistency(ctx context.Context, logger log.Logger, autofix bool) er
// TODO: function to recalc all counters
if setting.Database.Type.IsPostgreSQL() {
if setting.Database.UsePostgreSQL {
consistencyChecks = append(consistencyChecks, consistencyCheck{
Name: "Sequence values",
Counter: db.CountBadSequences,

View File

@ -179,7 +179,7 @@ func (c *Command) AddDashesAndList(list ...string) *Command {
}
// ToTrustedCmdArgs converts a list of strings (trusted as argument) to TrustedCmdArgs
// In most cases, it shouldn't be used. Use NewCommand().AddXxx() function instead
// In most cases, it shouldn't be used. Use AddXxx function instead
func ToTrustedCmdArgs(args []string) TrustedCmdArgs {
ret := make(TrustedCmdArgs, len(args))
for i, arg := range args {

View File

@ -218,19 +218,6 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) {
return false, err
}
// IsForcePush returns true if a push from oldCommitHash to this is a force push
func (c *Commit) IsForcePush(oldCommitID string) (bool, error) {
if oldCommitID == EmptySHA {
return false, nil
}
oldCommit, err := c.repo.GetCommit(oldCommitID)
if err != nil {
return false, err
}
hasPreviousCommit, err := c.HasPreviousCommit(oldCommit.ID)
return !hasPreviousCommit, err
}
// CommitsBeforeLimit returns num commits before current revision
func (c *Commit) CommitsBeforeLimit(num int) ([]*Commit, error) {
return c.repo.getCommitsBeforeLimit(c.ID, num)

View File

@ -42,10 +42,7 @@ func RevListObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sync.
defer revListWriter.Close()
stderr := new(bytes.Buffer)
var errbuf strings.Builder
cmd := git.NewCommand(ctx, "rev-list", "--objects").AddDynamicArguments(headSHA)
if baseSHA != "" {
cmd = cmd.AddArguments("--not").AddDynamicArguments(baseSHA)
}
cmd := git.NewCommand(ctx, "rev-list", "--objects").AddDynamicArguments(headSHA).AddArguments("--not").AddDynamicArguments(baseSHA)
if err := cmd.Run(&git.RunOpts{
Dir: tmpBasePath,
Stdout: revListWriter,

View File

@ -323,27 +323,6 @@ func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip in
return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
}
// CommitsBetweenNotBase returns a list that contains commits between [before, last), excluding commits in baseBranch.
// If before is detached (removed by reset + push) it is not included.
func (repo *Repository) CommitsBetweenNotBase(last, before *Commit, baseBranch string) ([]*Commit, error) {
var stdout []byte
var err error
if before == nil {
stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
} else {
stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String()+".."+last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
if err != nil && strings.Contains(err.Error(), "no merge base") {
// future versions of git >= 2.28 are likely to return an error if before and last have become unrelated.
// previously it would return the results of git rev-list before last so let's try that...
stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String(), last.ID.String()).AddOptionValues("--not", baseBranch).RunStdBytes(&RunOpts{Dir: repo.Path})
}
}
if err != nil {
return nil, err
}
return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout))
}
// CommitsBetweenIDs return commits between twoe commits
func (repo *Repository) CommitsBetweenIDs(last, before string) ([]*Commit, error) {
lastCommit, err := repo.GetCommit(last)

View File

@ -15,8 +15,8 @@ import (
"code.gitea.io/gitea/modules/setting"
)
// SetCacheControlInHeader sets suitable cache-control headers in the response
func SetCacheControlInHeader(h http.Header, maxAge time.Duration, additionalDirectives ...string) {
// AddCacheControlToHeader adds suitable cache-control headers to response
func AddCacheControlToHeader(h http.Header, maxAge time.Duration, additionalDirectives ...string) {
directives := make([]string, 0, 2+len(additionalDirectives))
// "max-age=0 + must-revalidate" (aka "no-cache") is preferred instead of "no-store"
@ -31,8 +31,7 @@ func SetCacheControlInHeader(h http.Header, maxAge time.Duration, additionalDire
directives = append(directives, "max-age=0", "private", "must-revalidate")
// to remind users they are using non-prod setting.
h.Set("X-Gitea-Debug", "RUN_MODE="+setting.RunMode)
h.Set("X-Forgejo-Debug", "RUN_MODE="+setting.RunMode)
h.Add("X-Gitea-Debug", "RUN_MODE="+setting.RunMode)
}
h.Set("Cache-Control", strings.Join(append(directives, additionalDirectives...), ", "))
@ -51,7 +50,7 @@ func HandleTimeCache(req *http.Request, w http.ResponseWriter, fi os.FileInfo) (
// HandleGenericTimeCache handles time-based caching for a HTTP request
func HandleGenericTimeCache(req *http.Request, w http.ResponseWriter, lastModified time.Time) (handled bool) {
SetCacheControlInHeader(w.Header(), setting.StaticCacheTime)
AddCacheControlToHeader(w.Header(), setting.StaticCacheTime)
ifModifiedSince := req.Header.Get("If-Modified-Since")
if ifModifiedSince != "" {
@ -82,7 +81,7 @@ func HandleGenericETagCache(req *http.Request, w http.ResponseWriter, etag strin
return true
}
}
SetCacheControlInHeader(w.Header(), setting.StaticCacheTime)
AddCacheControlToHeader(w.Header(), setting.StaticCacheTime)
return false
}
@ -126,6 +125,6 @@ func HandleGenericETagTimeCache(req *http.Request, w http.ResponseWriter, etag s
}
}
}
SetCacheControlInHeader(w.Header(), setting.StaticCacheTime)
AddCacheControlToHeader(w.Header(), setting.StaticCacheTime)
return false
}

View File

@ -29,9 +29,6 @@ func countFormalHeaders(h http.Header) (c int) {
if strings.HasPrefix(k, "X-Gitea-") {
continue
}
if strings.HasPrefix(k, "X-Forgejo-") {
continue
}
c++
}
return c

View File

@ -36,17 +36,17 @@ func (err ErrTemplateLoad) Error() string {
// GetTemplateFile loads the label template file by given name,
// then parses and returns a list of name-color pairs and optionally description.
func GetTemplateFile(name string) ([]*Label, error) {
data, err := options.Labels(name + ".yaml")
data, err := options.GetRepoInitFile("label", name+".yaml")
if err == nil && len(data) > 0 {
return parseYamlFormat(name+".yaml", data)
}
data, err = options.Labels(name + ".yml")
data, err = options.GetRepoInitFile("label", name+".yml")
if err == nil && len(data) > 0 {
return parseYamlFormat(name+".yml", data)
}
data, err = options.Labels(name)
data, err = options.GetRepoInitFile("label", name)
if err != nil {
return nil, ErrTemplateLoad{name, fmt.Errorf("GetRepoInitFile: %w", err)}
}

View File

@ -7,7 +7,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/markup"
"github.com/stretchr/testify/assert"
@ -24,8 +23,7 @@ func TestRenderConsole(t *testing.T) {
canRender := render.CanRender("test", strings.NewReader(k))
assert.True(t, canRender)
err := render.Render(&markup.RenderContext{Ctx: git.DefaultContext},
strings.NewReader(k), &buf)
err := render.Render(&markup.RenderContext{}, strings.NewReader(k), &buf)
assert.NoError(t, err)
assert.EqualValues(t, v, buf.String())
}

View File

@ -7,7 +7,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/markup"
"github.com/stretchr/testify/assert"
@ -24,8 +23,7 @@ func TestRenderCSV(t *testing.T) {
for k, v := range kases {
var buf strings.Builder
err := render.Render(&markup.RenderContext{Ctx: git.DefaultContext},
strings.NewReader(k), &buf)
err := render.Render(&markup.RenderContext{}, strings.NewReader(k), &buf)
assert.NoError(t, err)
assert.EqualValues(t, v, buf.String())
}

View File

@ -291,10 +291,9 @@ func RenderDescriptionHTML(
// RenderEmoji for when we want to just process emoji and shortcodes
// in various places it isn't already run through the normal markdown processor
func RenderEmoji(
ctx *RenderContext,
content string,
) (string, error) {
return renderProcessString(ctx, emojiProcessors, content)
return renderProcessString(&RenderContext{}, emojiProcessors, content)
}
var (

View File

@ -9,7 +9,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
@ -71,13 +70,8 @@ var localMetas = map[string]string{
func TestRender_IssueIndexPattern(t *testing.T) {
// numeric: render inputs without valid mentions
test := func(s string) {
testRenderIssueIndexPattern(t, s, s, &RenderContext{
Ctx: git.DefaultContext,
})
testRenderIssueIndexPattern(t, s, s, &RenderContext{
Ctx: git.DefaultContext,
Metas: numericMetas,
})
testRenderIssueIndexPattern(t, s, s, &RenderContext{})
testRenderIssueIndexPattern(t, s, s, &RenderContext{Metas: numericMetas})
}
// should not render anything when there are no mentions
@ -125,10 +119,7 @@ func TestRender_IssueIndexPattern2(t *testing.T) {
links[i] = numericIssueLink(util.URLJoin(TestRepoURL, path), "ref-issue", index, marker)
}
expectedNil := fmt.Sprintf(expectedFmt, links...)
testRenderIssueIndexPattern(t, s, expectedNil, &RenderContext{
Ctx: git.DefaultContext,
Metas: localMetas,
})
testRenderIssueIndexPattern(t, s, expectedNil, &RenderContext{Metas: localMetas})
class := "ref-issue"
if isExternal {
@ -139,10 +130,7 @@ func TestRender_IssueIndexPattern2(t *testing.T) {
links[i] = numericIssueLink(prefix, class, index, marker)
}
expectedNum := fmt.Sprintf(expectedFmt, links...)
testRenderIssueIndexPattern(t, s, expectedNum, &RenderContext{
Ctx: git.DefaultContext,
Metas: numericMetas,
})
testRenderIssueIndexPattern(t, s, expectedNum, &RenderContext{Metas: numericMetas})
}
// should render freestanding mentions
@ -176,10 +164,7 @@ func TestRender_IssueIndexPattern3(t *testing.T) {
// alphanumeric: render inputs without valid mentions
test := func(s string) {
testRenderIssueIndexPattern(t, s, s, &RenderContext{
Ctx: git.DefaultContext,
Metas: alphanumericMetas,
})
testRenderIssueIndexPattern(t, s, s, &RenderContext{Metas: alphanumericMetas})
}
test("")
test("this is a test")
@ -209,10 +194,7 @@ func TestRender_IssueIndexPattern4(t *testing.T) {
links[i] = externalIssueLink("https://someurl.com/someUser/someRepo/", "ref-issue ref-external-issue", name)
}
expected := fmt.Sprintf(expectedFmt, links...)
testRenderIssueIndexPattern(t, s, expected, &RenderContext{
Ctx: git.DefaultContext,
Metas: alphanumericMetas,
})
testRenderIssueIndexPattern(t, s, expected, &RenderContext{Metas: alphanumericMetas})
}
test("OTT-1234 test", "%s test", "OTT-1234")
test("test T-12 issue", "test %s issue", "T-12")
@ -232,10 +214,7 @@ func TestRender_IssueIndexPattern5(t *testing.T) {
}
expected := fmt.Sprintf(expectedFmt, links...)
testRenderIssueIndexPattern(t, s, expected, &RenderContext{
Ctx: git.DefaultContext,
Metas: metas,
})
testRenderIssueIndexPattern(t, s, expected, &RenderContext{Metas: metas})
}
test("abc ISSUE-123 def", "abc %s def",
@ -256,10 +235,7 @@ func TestRender_IssueIndexPattern5(t *testing.T) {
[]string{"ISSUE-123"},
)
testRenderIssueIndexPattern(t, "will not match", "will not match", &RenderContext{
Ctx: git.DefaultContext,
Metas: regexpMetas,
})
testRenderIssueIndexPattern(t, "will not match", "will not match", &RenderContext{Metas: regexpMetas})
}
func testRenderIssueIndexPattern(t *testing.T, input, expected string, ctx *RenderContext) {
@ -279,7 +255,6 @@ func TestRender_AutoLink(t *testing.T) {
test := func(input, expected string) {
var buffer strings.Builder
err := PostProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: TestRepoURL,
Metas: localMetas,
}, strings.NewReader(input), &buffer)
@ -288,7 +263,6 @@ func TestRender_AutoLink(t *testing.T) {
buffer.Reset()
err = PostProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: TestRepoURL,
Metas: localMetas,
IsWiki: true,
@ -318,7 +292,6 @@ func TestRender_FullIssueURLs(t *testing.T) {
test := func(input, expected string) {
var result strings.Builder
err := postProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: TestRepoURL,
Metas: localMetas,
}, []processor{fullIssuePatternProcessor}, strings.NewReader(input), &result)

View File

@ -91,7 +91,6 @@ func TestRender_CrossReferences(t *testing.T) {
test := func(input, expected string) {
buffer, err := RenderString(&RenderContext{
Ctx: git.DefaultContext,
RelativePath: "a.md",
URLPrefix: setting.AppSubURL,
Metas: localMetas,
@ -136,7 +135,6 @@ func TestRender_links(t *testing.T) {
test := func(input, expected string) {
buffer, err := RenderString(&RenderContext{
Ctx: git.DefaultContext,
RelativePath: "a.md",
URLPrefix: TestRepoURL,
}, input)
@ -236,7 +234,6 @@ func TestRender_email(t *testing.T) {
test := func(input, expected string) {
res, err := RenderString(&RenderContext{
Ctx: git.DefaultContext,
RelativePath: "a.md",
URLPrefix: TestRepoURL,
}, input)
@ -295,7 +292,6 @@ func TestRender_emoji(t *testing.T) {
test := func(input, expected string) {
expected = strings.ReplaceAll(expected, "&", "&amp;")
buffer, err := RenderString(&RenderContext{
Ctx: git.DefaultContext,
RelativePath: "a.md",
URLPrefix: TestRepoURL,
}, input)
@ -359,13 +355,11 @@ func TestRender_ShortLinks(t *testing.T) {
test := func(input, expected, expectedWiki string) {
buffer, err := markdown.RenderString(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: tree,
}, input)
assert.NoError(t, err)
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
buffer, err = markdown.RenderString(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: TestRepoURL,
Metas: localMetas,
IsWiki: true,
@ -467,14 +461,12 @@ func TestRender_RelativeImages(t *testing.T) {
test := func(input, expected, expectedWiki string) {
buffer, err := markdown.RenderString(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: tree,
Metas: localMetas,
}, input)
assert.NoError(t, err)
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
buffer, err = markdown.RenderString(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: TestRepoURL,
Metas: localMetas,
IsWiki: true,
@ -509,7 +501,6 @@ func Test_ParseClusterFuzz(t *testing.T) {
var res strings.Builder
err := PostProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: "https://example.com",
Metas: localMetas,
}, strings.NewReader(data), &res)
@ -520,7 +511,6 @@ func Test_ParseClusterFuzz(t *testing.T) {
res.Reset()
err = PostProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: "https://example.com",
Metas: localMetas,
}, strings.NewReader(data), &res)
@ -541,7 +531,6 @@ func TestIssue16020(t *testing.T) {
var res strings.Builder
err := PostProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: "https://example.com",
Metas: localMetas,
}, strings.NewReader(data), &res)
@ -558,7 +547,6 @@ func BenchmarkEmojiPostprocess(b *testing.B) {
for i := 0; i < b.N; i++ {
var res strings.Builder
err := PostProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: "https://example.com",
Metas: localMetas,
}, strings.NewReader(data), &res)
@ -569,7 +557,6 @@ func BenchmarkEmojiPostprocess(b *testing.B) {
func TestFuzz(t *testing.T) {
s := "t/l/issues/8#/../../a"
renderContext := RenderContext{
Ctx: git.DefaultContext,
URLPrefix: "https://example.com/go-gitea/gitea",
Metas: map[string]string{
"user": "go-gitea",
@ -587,7 +574,6 @@ func TestIssue18471(t *testing.T) {
var res strings.Builder
err := PostProcess(&RenderContext{
Ctx: git.DefaultContext,
URLPrefix: "https://example.com",
Metas: localMetas,
}, strings.NewReader(data), &res)

View File

@ -52,14 +52,12 @@ func TestRender_StandardLinks(t *testing.T) {
test := func(input, expected, expectedWiki string) {
buffer, err := RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: setting.AppSubURL,
}, input)
assert.NoError(t, err)
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
buffer, err = RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: setting.AppSubURL,
IsWiki: true,
}, input)
@ -83,7 +81,6 @@ func TestRender_Images(t *testing.T) {
test := func(input, expected string) {
buffer, err := RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: setting.AppSubURL,
}, input)
assert.NoError(t, err)
@ -314,7 +311,6 @@ func TestTotal_RenderWiki(t *testing.T) {
for i := 0; i < len(testCases); i += 2 {
line, err := RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: AppSubURL,
IsWiki: true,
}, testCases[i])
@ -343,7 +339,6 @@ func TestTotal_RenderString(t *testing.T) {
for i := 0; i < len(testCases); i += 2 {
line, err := RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: AppSubURL,
}, testCases[i])
assert.NoError(t, err)
@ -353,17 +348,17 @@ func TestTotal_RenderString(t *testing.T) {
func TestRender_RenderParagraphs(t *testing.T) {
test := func(t *testing.T, str string, cnt int) {
res, err := RenderRawString(&markup.RenderContext{Ctx: git.DefaultContext}, str)
res, err := RenderRawString(&markup.RenderContext{}, str)
assert.NoError(t, err)
assert.Equal(t, cnt, strings.Count(res, "<p"), "Rendered result for unix should have %d paragraph(s) but has %d:\n%s\n", cnt, strings.Count(res, "<p"), res)
mac := strings.ReplaceAll(str, "\n", "\r")
res, err = RenderRawString(&markup.RenderContext{Ctx: git.DefaultContext}, mac)
res, err = RenderRawString(&markup.RenderContext{}, mac)
assert.NoError(t, err)
assert.Equal(t, cnt, strings.Count(res, "<p"), "Rendered result for mac should have %d paragraph(s) but has %d:\n%s\n", cnt, strings.Count(res, "<p"), res)
dos := strings.ReplaceAll(str, "\n", "\r\n")
res, err = RenderRawString(&markup.RenderContext{Ctx: git.DefaultContext}, dos)
res, err = RenderRawString(&markup.RenderContext{}, dos)
assert.NoError(t, err)
assert.Equal(t, cnt, strings.Count(res, "<p"), "Rendered result for windows should have %d paragraph(s) but has %d:\n%s\n", cnt, strings.Count(res, "<p"), res)
}
@ -391,7 +386,7 @@ func TestMarkdownRenderRaw(t *testing.T) {
for _, testcase := range testcases {
log.Info("Test markdown render error with fuzzy data: %x, the following errors can be recovered", testcase)
_, err := RenderRawString(&markup.RenderContext{Ctx: git.DefaultContext}, string(testcase))
_, err := RenderRawString(&markup.RenderContext{}, string(testcase))
assert.NoError(t, err)
}
}
@ -403,7 +398,7 @@ func TestRenderSiblingImages_Issue12925(t *testing.T) {
expected := `<p><a href="/image1" target="_blank" rel="nofollow noopener"><img src="/image1" alt="image1"></a><br>
<a href="/image2" target="_blank" rel="nofollow noopener"><img src="/image2" alt="image2"></a></p>
`
res, err := RenderRawString(&markup.RenderContext{Ctx: git.DefaultContext}, testcase)
res, err := RenderRawString(&markup.RenderContext{}, testcase)
assert.NoError(t, err)
assert.Equal(t, expected, res)
}
@ -412,7 +407,7 @@ func TestRenderEmojiInLinks_Issue12331(t *testing.T) {
testcase := `[Link with emoji :moon: in text](https://gitea.io)`
expected := `<p><a href="https://gitea.io" rel="nofollow">Link with emoji <span class="emoji" aria-label="waxing gibbous moon">🌔</span> in text</a></p>
`
res, err := RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, testcase)
res, err := RenderString(&markup.RenderContext{}, testcase)
assert.NoError(t, err)
assert.Equal(t, expected, res)
}
@ -446,7 +441,7 @@ func TestColorPreview(t *testing.T) {
}
for _, test := range positiveTests {
res, err := RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, test.testcase)
res, err := RenderString(&markup.RenderContext{}, test.testcase)
assert.NoError(t, err, "Unexpected error in testcase: %q", test.testcase)
assert.Equal(t, test.expected, res, "Unexpected result in testcase %q", test.testcase)
@ -466,7 +461,7 @@ func TestColorPreview(t *testing.T) {
}
for _, test := range negativeTests {
res, err := RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, test)
res, err := RenderString(&markup.RenderContext{}, test)
assert.NoError(t, err, "Unexpected error in testcase: %q", test)
assert.NotContains(t, res, `<span class="color-preview" style="background-color: `, "Unexpected result in testcase %q", test)
}
@ -513,7 +508,7 @@ func TestMathBlock(t *testing.T) {
}
for _, test := range testcases {
res, err := RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, test.testcase)
res, err := RenderString(&markup.RenderContext{}, test.testcase)
assert.NoError(t, err, "Unexpected error in testcase: %q", test.testcase)
assert.Equal(t, test.expected, res, "Unexpected result in testcase %q", test.testcase)

View File

@ -7,7 +7,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
@ -27,7 +26,6 @@ func TestRender_StandardLinks(t *testing.T) {
test := func(input, expected string) {
buffer, err := RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: setting.AppSubURL,
}, input)
assert.NoError(t, err)
@ -48,7 +46,6 @@ func TestRender_Images(t *testing.T) {
test := func(input, expected string) {
buffer, err := RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: setting.AppSubURL,
}, input)
assert.NoError(t, err)
@ -68,7 +65,6 @@ func TestRender_Source(t *testing.T) {
test := func(input, expected string) {
buffer, err := RenderString(&markup.RenderContext{
Ctx: git.DefaultContext,
URLPrefix: setting.AppSubURL,
}, input)
assert.NoError(t, err)

View File

@ -7,52 +7,11 @@ import (
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
)
// Locale reads the content of a specific locale from static/bindata or custom path.
func Locale(name string) ([]byte, error) {
return fileFromDir(path.Join("locale", util.CleanPath(name)))
}
// Readme reads the content of a specific readme from static/bindata or custom path.
func Readme(name string) ([]byte, error) {
return fileFromDir(path.Join("readme", util.CleanPath(name)))
}
// Gitignore reads the content of a gitignore locale from static/bindata or custom path.
func Gitignore(name string) ([]byte, error) {
return fileFromDir(path.Join("gitignore", util.CleanPath(name)))
}
// License reads the content of a specific license from static/bindata or custom path.
func License(name string) ([]byte, error) {
return fileFromDir(path.Join("license", util.CleanPath(name)))
}
// Labels reads the content of a specific labels from static/bindata or custom path.
func Labels(name string) ([]byte, error) {
return fileFromDir(path.Join("label", util.CleanPath(name)))
}
// WalkLocales reads the content of a specific locale
func WalkLocales(callback func(path, name string, d fs.DirEntry, err error) error) error {
if IsDynamic() {
if err := walkAssetDir(filepath.Join(setting.StaticRootPath, "options", "locale"), callback); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to walk locales. Error: %w", err)
}
}
if err := walkAssetDir(filepath.Join(setting.CustomPath, "options", "locale"), callback); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to walk locales. Error: %w", err)
}
return nil
}
func walkAssetDir(root string, callback func(path, name string, d fs.DirEntry, err error) error) error {
if err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
// name is the path relative to the root
@ -78,18 +37,3 @@ func walkAssetDir(root string, callback func(path, name string, d fs.DirEntry, e
}
return nil
}
func statDirIfExist(dir string) ([]string, error) {
isDir, err := util.IsDir(dir)
if err != nil {
return nil, fmt.Errorf("unable to check if static directory %s is a directory. %w", dir, err)
}
if !isDir {
return nil, nil
}
files, err := util.StatDir(dir, true)
if err != nil {
return nil, fmt.Errorf("unable to read directory %q. %w", dir, err)
}
return files, nil
}

View File

@ -7,8 +7,10 @@ package options
import (
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@ -25,20 +27,76 @@ func Dir(name string) ([]string, error) {
var result []string
for _, dir := range []string{
path.Join(setting.CustomPath, "options", name), // custom dir
path.Join(setting.StaticRootPath, "options", name), // static dir
} {
files, err := statDirIfExist(dir)
customDir := path.Join(setting.CustomPath, "options", name)
isDir, err := util.IsDir(customDir)
if err != nil {
return []string{}, fmt.Errorf("Unabe to check if custom directory %s is a directory. %w", customDir, err)
}
if isDir {
files, err := util.StatDir(customDir, true)
if err != nil {
return nil, err
return []string{}, fmt.Errorf("Failed to read custom directory. %w", err)
}
result = append(result, files...)
}
staticDir := path.Join(setting.StaticRootPath, "options", name)
isDir, err = util.IsDir(staticDir)
if err != nil {
return []string{}, fmt.Errorf("unable to check if static directory %s is a directory. %w", staticDir, err)
}
if isDir {
files, err := util.StatDir(staticDir, true)
if err != nil {
return []string{}, fmt.Errorf("Failed to read static directory. %w", err)
}
result = append(result, files...)
}
return directories.AddAndGet(name, result), nil
}
// Locale reads the content of a specific locale from static or custom path.
func Locale(name string) ([]byte, error) {
return fileFromDir(path.Join("locale", name))
}
// WalkLocales reads the content of a specific locale from static or custom path.
func WalkLocales(callback func(path, name string, d fs.DirEntry, err error) error) error {
if err := walkAssetDir(filepath.Join(setting.StaticRootPath, "options", "locale"), callback); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to walk locales. Error: %w", err)
}
if err := walkAssetDir(filepath.Join(setting.CustomPath, "options", "locale"), callback); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to walk locales. Error: %w", err)
}
return nil
}
// Readme reads the content of a specific readme from static or custom path.
func Readme(name string) ([]byte, error) {
return fileFromDir(path.Join("readme", name))
}
// Gitignore reads the content of a specific gitignore from static or custom path.
func Gitignore(name string) ([]byte, error) {
return fileFromDir(path.Join("gitignore", name))
}
// License reads the content of a specific license from static or custom path.
func License(name string) ([]byte, error) {
return fileFromDir(path.Join("license", name))
}
// Labels reads the content of a specific labels from static or custom path.
func Labels(name string) ([]byte, error) {
return fileFromDir(path.Join("label", name))
}
// fileFromDir is a helper to read files from static or custom path.
func fileFromDir(name string) ([]byte, error) {
customPath := path.Join(setting.CustomPath, "options", name)

44
modules/options/repo.go Normal file
View File

@ -0,0 +1,44 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package options
import (
"fmt"
"os"
"path"
"strings"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
)
// GetRepoInitFile returns repository init files
func GetRepoInitFile(tp, name string) ([]byte, error) {
cleanedName := strings.TrimLeft(path.Clean("/"+name), "/")
relPath := path.Join("options", tp, cleanedName)
// Use custom file when available.
customPath := path.Join(setting.CustomPath, relPath)
isFile, err := util.IsFile(customPath)
if err != nil {
log.Error("Unable to check if %s is a file. Error: %v", customPath, err)
}
if isFile {
return os.ReadFile(customPath)
}
switch tp {
case "readme":
return Readme(cleanedName)
case "gitignore":
return Gitignore(cleanedName)
case "license":
return License(cleanedName)
case "label":
return Labels(cleanedName)
default:
return []byte{}, fmt.Errorf("Invalid init file type")
}
}

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