Merge branch 'main' into add-issue-planned-time

This commit is contained in:
stuzer05 2023-06-03 19:28:20 +03:00
commit bf4fa112d0
No known key found for this signature in database
GPG Key ID: A6ABAAA9268F9F4F
1934 changed files with 61052 additions and 169638 deletions

View File

@ -2,9 +2,12 @@ root = "."
tmp_dir = ".air"
[build]
cmd = "make backend"
cmd = "make --no-print-directory backend"
bin = "gitea"
delay = 1000
include_ext = ["go", "tmpl"]
exclude_dir = ["modules/git/tests", "services/gitdiff/testdata", "modules/avatar/testdata", "models/fixtures", "models/migrations/fixtures", "modules/migration/file_format_testdata", "modules/avatar/identicon/testdata"]
include_file = ["main.go"]
include_dir = ["cmd", "models", "modules", "options", "routers", "services"]
exclude_dir = ["modules/git/tests", "services/gitdiff/testdata", "modules/avatar/testdata", "models/fixtures", "models/migrations/fixtures", "modules/migration/file_format_testdata", "modules/avatar/identicon/testdata"]
exclude_regex = ["_test.go$", "_gen.go$"]
stop_on_error = true

View File

@ -76,7 +76,6 @@ cpu.out
/yarn-error.log
/npm-debug.log*
/public/js
/public/serviceworker.js
/public/css
/public/fonts
/public/img/webpack

1136
.drone.yml

File diff suppressed because it is too large Load Diff

View File

@ -9,11 +9,17 @@ parserOptions:
ecmaVersion: latest
plugins:
- eslint-plugin-unicorn
- "@eslint-community/eslint-plugin-eslint-comments"
- eslint-plugin-array-func
- eslint-plugin-custom-elements
- eslint-plugin-import
- eslint-plugin-jquery
- eslint-plugin-no-jquery
- eslint-plugin-no-use-extend-native
- eslint-plugin-regexp
- eslint-plugin-sonarjs
- eslint-plugin-custom-elements
- eslint-plugin-unicorn
- eslint-plugin-wc
env:
es2022: true
@ -41,11 +47,26 @@ overrides:
import/no-unused-modules: [0]
rules:
"@eslint-community/eslint-comments/disable-enable-pair": [2]
"@eslint-community/eslint-comments/no-aggregating-enable": [2]
"@eslint-community/eslint-comments/no-duplicate-disable": [2]
"@eslint-community/eslint-comments/no-restricted-disable": [0]
"@eslint-community/eslint-comments/no-unlimited-disable": [2]
"@eslint-community/eslint-comments/no-unused-disable": [2]
"@eslint-community/eslint-comments/no-unused-enable": [2]
"@eslint-community/eslint-comments/no-use": [0]
"@eslint-community/eslint-comments/require-description": [0]
accessor-pairs: [2]
array-bracket-newline: [0]
array-bracket-spacing: [2, never]
array-callback-return: [2, {checkForEach: true}]
array-element-newline: [0]
array-func/avoid-reverse: [2]
array-func/from-map: [2]
array-func/no-unnecessary-this-arg: [2]
array-func/prefer-array-from: [2]
array-func/prefer-flat-map: [0] # handled by unicorn/prefer-array-flat-map
array-func/prefer-flat: [0] # handled by unicorn/prefer-array-flat
arrow-body-style: [0]
arrow-parens: [2, always]
arrow-spacing: [2, {before: true, after: true}]
@ -65,7 +86,7 @@ rules:
curly: [0]
custom-elements/expose-class-on-global: [0]
custom-elements/extends-correct-class: [2]
custom-elements/file-name-matches-element: [0]
custom-elements/file-name-matches-element: [2]
custom-elements/no-constructor: [2]
custom-elements/no-customized-built-in-elements: [2]
custom-elements/no-dom-traversal-in-attributechangedcallback: [2]
@ -111,9 +132,9 @@ rules:
import/namespace: [0]
import/newline-after-import: [0]
import/no-absolute-path: [0]
import/no-amd: [0]
import/no-amd: [2]
import/no-anonymous-default-export: [0]
import/no-commonjs: [0]
import/no-commonjs: [2]
import/no-cycle: [2, {ignoreExternal: true, maxDepth: 1}]
import/no-default-export: [0]
import/no-deprecated: [0]
@ -270,6 +291,99 @@ rules:
no-invalid-this: [0]
no-irregular-whitespace: [2]
no-iterator: [2]
no-jquery/no-ajax-events: [2]
no-jquery/no-ajax: [0]
no-jquery/no-and-self: [2]
no-jquery/no-animate-toggle: [2]
no-jquery/no-animate: [2]
no-jquery/no-append-html: [0]
no-jquery/no-attr: [0]
no-jquery/no-bind: [2]
no-jquery/no-box-model: [2]
no-jquery/no-browser: [2]
no-jquery/no-camel-case: [2]
no-jquery/no-class-state: [0]
no-jquery/no-class: [0]
no-jquery/no-clone: [2]
no-jquery/no-closest: [0]
no-jquery/no-constructor-attributes: [2]
no-jquery/no-contains: [2]
no-jquery/no-context-prop: [2]
no-jquery/no-css: [0]
no-jquery/no-data: [0]
no-jquery/no-deferred: [2]
no-jquery/no-delegate: [2]
no-jquery/no-each-collection: [0]
no-jquery/no-each-util: [0]
no-jquery/no-each: [0]
no-jquery/no-error-shorthand: [2]
no-jquery/no-error: [2]
no-jquery/no-escape-selector: [2]
no-jquery/no-event-shorthand: [2]
no-jquery/no-extend: [2]
no-jquery/no-fade: [2]
no-jquery/no-filter: [0]
no-jquery/no-find-collection: [0]
no-jquery/no-find-util: [2]
no-jquery/no-find: [0]
no-jquery/no-fx-interval: [2]
no-jquery/no-global-eval: [2]
no-jquery/no-global-selector: [0]
no-jquery/no-grep: [2]
no-jquery/no-has: [2]
no-jquery/no-hold-ready: [2]
no-jquery/no-html: [0]
no-jquery/no-in-array: [2]
no-jquery/no-is-array: [2]
no-jquery/no-is-empty-object: [2]
no-jquery/no-is-function: [2]
no-jquery/no-is-numeric: [2]
no-jquery/no-is-plain-object: [2]
no-jquery/no-is-window: [2]
no-jquery/no-is: [0]
no-jquery/no-jquery-constructor: [0]
no-jquery/no-live: [2]
no-jquery/no-load-shorthand: [2]
no-jquery/no-load: [2]
no-jquery/no-map-collection: [0]
no-jquery/no-map-util: [2]
no-jquery/no-map: [0]
no-jquery/no-merge: [2]
no-jquery/no-node-name: [2]
no-jquery/no-noop: [2]
no-jquery/no-now: [2]
no-jquery/no-on-ready: [2]
no-jquery/no-other-methods: [0]
no-jquery/no-other-utils: [2]
no-jquery/no-param: [2]
no-jquery/no-parent: [0]
no-jquery/no-parents: [0]
no-jquery/no-parse-html-literal: [0]
no-jquery/no-parse-html: [2]
no-jquery/no-parse-json: [2]
no-jquery/no-parse-xml: [2]
no-jquery/no-prop: [0]
no-jquery/no-proxy: [2]
no-jquery/no-ready-shorthand: [2]
no-jquery/no-ready: [2]
no-jquery/no-selector-prop: [2]
no-jquery/no-serialize: [2]
no-jquery/no-size: [2]
no-jquery/no-sizzle: [0]
no-jquery/no-slide: [2]
no-jquery/no-sub: [2]
no-jquery/no-support: [2]
no-jquery/no-text: [0]
no-jquery/no-trigger: [0]
no-jquery/no-trim: [2]
no-jquery/no-type: [2]
no-jquery/no-unique: [2]
no-jquery/no-unload-shorthand: [2]
no-jquery/no-val: [0]
no-jquery/no-visibility: [2]
no-jquery/no-when: [2]
no-jquery/no-wrap: [2]
no-jquery/variable-pattern: [0]
no-label-var: [2]
no-labels: [0] # handled by no-restricted-syntax
no-lone-blocks: [2]
@ -338,6 +452,7 @@ rules:
no-unused-private-class-members: [2]
no-unused-vars: [2, {args: all, argsIgnorePattern: ^_, varsIgnorePattern: ^_, caughtErrorsIgnorePattern: ^_, destructuredArrayIgnorePattern: ^_, ignoreRestSiblings: false}]
no-use-before-define: [2, {functions: false, classes: true, variables: true, allowNamedExports: true}]
no-use-extend-native/no-use-extend-native: [2]
no-useless-backreference: [2]
no-useless-call: [2]
no-useless-catch: [2]
@ -378,6 +493,80 @@ rules:
quote-props: [0]
quotes: [2, single, {avoidEscape: true, allowTemplateLiterals: true}]
radix: [2, as-needed]
regexp/confusing-quantifier: [2]
regexp/control-character-escape: [2]
regexp/hexadecimal-escape: [0]
regexp/letter-case: [0]
regexp/match-any: [2]
regexp/negation: [2]
regexp/no-contradiction-with-assertion: [0]
regexp/no-control-character: [0]
regexp/no-dupe-characters-character-class: [2]
regexp/no-dupe-disjunctions: [2]
regexp/no-empty-alternative: [2]
regexp/no-empty-capturing-group: [2]
regexp/no-empty-character-class: [0]
regexp/no-empty-group: [2]
regexp/no-empty-lookarounds-assertion: [2]
regexp/no-escape-backspace: [2]
regexp/no-extra-lookaround-assertions: [0]
regexp/no-invalid-regexp: [2]
regexp/no-invisible-character: [2]
regexp/no-lazy-ends: [2]
regexp/no-legacy-features: [2]
regexp/no-misleading-capturing-group: [0]
regexp/no-misleading-unicode-character: [0]
regexp/no-missing-g-flag: [2]
regexp/no-non-standard-flag: [2]
regexp/no-obscure-range: [2]
regexp/no-octal: [2]
regexp/no-optional-assertion: [2]
regexp/no-potentially-useless-backreference: [2]
regexp/no-standalone-backslash: [2]
regexp/no-super-linear-backtracking: [0]
regexp/no-super-linear-move: [0]
regexp/no-trivially-nested-assertion: [2]
regexp/no-trivially-nested-quantifier: [2]
regexp/no-unused-capturing-group: [0]
regexp/no-useless-assertions: [2]
regexp/no-useless-backreference: [2]
regexp/no-useless-character-class: [2]
regexp/no-useless-dollar-replacements: [2]
regexp/no-useless-escape: [2]
regexp/no-useless-flag: [2]
regexp/no-useless-lazy: [2]
regexp/no-useless-non-capturing-group: [2]
regexp/no-useless-quantifier: [2]
regexp/no-useless-range: [2]
regexp/no-useless-two-nums-quantifier: [2]
regexp/no-zero-quantifier: [2]
regexp/optimal-lookaround-quantifier: [2]
regexp/optimal-quantifier-concatenation: [0]
regexp/prefer-character-class: [0]
regexp/prefer-d: [0]
regexp/prefer-escape-replacement-dollar-char: [0]
regexp/prefer-lookaround: [0]
regexp/prefer-named-backreference: [0]
regexp/prefer-named-capture-group: [0]
regexp/prefer-named-replacement: [0]
regexp/prefer-plus-quantifier: [2]
regexp/prefer-predefined-assertion: [2]
regexp/prefer-quantifier: [0]
regexp/prefer-question-quantifier: [2]
regexp/prefer-range: [2]
regexp/prefer-regexp-exec: [2]
regexp/prefer-regexp-test: [2]
regexp/prefer-result-array-groups: [0]
regexp/prefer-star-quantifier: [2]
regexp/prefer-unicode-codepoint-escapes: [2]
regexp/prefer-w: [0]
regexp/require-unicode-regexp: [0]
regexp/sort-alternatives: [0]
regexp/sort-character-class-elements: [0]
regexp/sort-flags: [0]
regexp/strict: [2]
regexp/unicode-escape: [0]
regexp/use-ignore-case: [0]
require-atomic-updates: [0]
require-await: [0]
require-unicode-regexp: [0]
@ -407,7 +596,7 @@ rules:
sonarjs/no-nested-template-literals: [0]
sonarjs/no-one-iteration-loop: [2]
sonarjs/no-redundant-boolean: [2]
sonarjs/no-redundant-jump: [0]
sonarjs/no-redundant-jump: [2]
sonarjs/no-same-line-conditional: [2]
sonarjs/no-small-switch: [0]
sonarjs/no-unused-collection: [2]
@ -447,17 +636,18 @@ rules:
unicorn/import-style: [0]
unicorn/new-for-builtins: [2]
unicorn/no-abusive-eslint-disable: [0]
unicorn/no-array-callback-reference: [0]
unicorn/no-array-for-each: [2]
unicorn/no-array-instanceof: [0]
unicorn/no-array-method-this-argument: [2]
unicorn/no-array-push-push: [2]
unicorn/no-array-reduce: [2]
unicorn/no-await-expression-member: [0]
unicorn/no-console-spaces: [0]
unicorn/no-document-cookie: [2]
unicorn/no-empty-file: [2]
unicorn/no-fn-reference-in-iterator: [0]
unicorn/no-for-loop: [0]
unicorn/no-hex-escape: [0]
unicorn/no-instanceof-array: [0]
unicorn/no-invalid-remove-event-listener: [2]
unicorn/no-keyword-prefix: [0]
unicorn/no-lonely-if: [2]
@ -468,7 +658,6 @@ rules:
unicorn/no-null: [0]
unicorn/no-object-as-default-parameter: [0]
unicorn/no-process-exit: [0]
unicorn/no-reduce: [2]
unicorn/no-static-only-class: [2]
unicorn/no-thenable: [2]
unicorn/no-this-assignment: [2]
@ -494,15 +683,19 @@ rules:
unicorn/prefer-array-index-of: [2]
unicorn/prefer-array-some: [2]
unicorn/prefer-at: [0]
unicorn/prefer-blob-reading-methods: [2]
unicorn/prefer-code-point: [0]
unicorn/prefer-dataset: [2]
unicorn/prefer-date-now: [2]
unicorn/prefer-default-parameters: [0]
unicorn/prefer-event-key: [2]
unicorn/prefer-dom-node-append: [2]
unicorn/prefer-dom-node-dataset: [0]
unicorn/prefer-dom-node-remove: [2]
unicorn/prefer-dom-node-text-content: [2]
unicorn/prefer-event-target: [2]
unicorn/prefer-export-from: [2]
unicorn/prefer-export-from: [2, {ignoreUsedVariables: true}]
unicorn/prefer-includes: [2]
unicorn/prefer-json-parse-buffer: [0]
unicorn/prefer-keyboard-event-key: [2]
unicorn/prefer-logical-operator-over-ternary: [2]
unicorn/prefer-math-trunc: [2]
unicorn/prefer-modern-dom-apis: [0]
@ -510,9 +703,7 @@ rules:
unicorn/prefer-module: [2]
unicorn/prefer-native-coercion-functions: [2]
unicorn/prefer-negative-index: [2]
unicorn/prefer-node-append: [0]
unicorn/prefer-node-protocol: [2]
unicorn/prefer-node-remove: [0]
unicorn/prefer-number-properties: [0]
unicorn/prefer-object-from-entries: [2]
unicorn/prefer-object-has-own: [0]
@ -521,17 +712,17 @@ rules:
unicorn/prefer-query-selector: [0]
unicorn/prefer-reflect-apply: [0]
unicorn/prefer-regexp-test: [2]
unicorn/prefer-replace-all: [0]
unicorn/prefer-set-has: [0]
unicorn/prefer-set-size: [2]
unicorn/prefer-spread: [0]
unicorn/prefer-starts-ends-with: [2]
unicorn/prefer-string-replace-all: [0]
unicorn/prefer-string-slice: [0]
unicorn/prefer-string-starts-ends-with: [2]
unicorn/prefer-string-trim-start-end: [2]
unicorn/prefer-switch: [0]
unicorn/prefer-ternary: [0]
unicorn/prefer-text-content: [2]
unicorn/prefer-top-level-await: [0]
unicorn/prefer-trim-start-end: [2]
unicorn/prefer-type-error: [0]
unicorn/prevent-abbreviations: [0]
unicorn/relative-url-style: [2]
@ -546,6 +737,15 @@ rules:
use-isnan: [2]
valid-typeof: [2, {requireStringLiterals: true}]
vars-on-top: [0]
wc/attach-shadow-constructor: [2]
wc/guard-super-call: [2]
wc/no-closed-shadow-root: [2]
wc/no-constructor-attributes: [2]
wc/no-constructor-params: [2]
wc/no-invalid-element-name: [0] # covered by custom-elements/valid-tag-name
wc/no-self-class: [2]
wc/no-typos: [2]
wc/require-listener-teardown: [2]
wrap-iife: [2, inside]
wrap-regex: [0]
yield-star-spacing: [2, after]

3
.gitattributes vendored
View File

@ -1,7 +1,8 @@
* text=auto eol=lf
*.tmpl linguist-language=Handlebars
/assets/*.json linguist-generated
/public/vendor/** -text -eol linguist-vendored
/public/img/svg/*.svg linguist-generated
/templates/swagger/v1_json.tmpl linguist-generated
/vendor/** -text -eol linguist-vendored
/web_src/fomantic/build/** linguist-generated
/web_src/js/vendor/** -text -eol linguist-vendored

23
.github/lock.yml vendored
View File

@ -1,23 +0,0 @@
# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app
# Number of days of inactivity before a closed issue or pull request is locked
daysUntilLock: 60
# Skip issues and pull requests created before a given timestamp. Timestamp must
# follow ISO 8601 (`YYYY-MM-DD`). `false` is disabled
skipCreatedBefore: false
# Issues and pull requests with these labels will be ignored.
exemptLabels: []
# Label to add before locking, such as `outdated`. `false` is disabled
lockLabel: false
# Comment to post before locking.
lockComment: >
This thread has been automatically locked since there has not been
any recent activity after it was closed. Please open a new issue for
related bugs and link to relevant comments in this thread.
# Assign `resolved` as the reason for locking. Set to `false` to disable
setLockReason: true

27
.github/workflows/cron-licenses.yml vendored Normal file
View File

@ -0,0 +1,27 @@
name: cron-licenses
on:
schedule:
- cron: "7 0 * * 1" # every Monday at 00:07 UTC
jobs:
cron-licenses:
runs-on: ubuntu-latest
if: github.repository == 'go-gitea/gitea'
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
with:
go-version: ">=1.20.1"
- run: make generate-license generate-gitignore
timeout-minutes: 40
- name: push translations to repo
uses: appleboy/git-push-action@v0.0.2
with:
author_email: "teabot@gitea.io"
author_name: GiteaBot
branch: main
commit: true
commit_message: "[skip ci] Updated licenses and gitignores"
remote: "git@github.com:go-gitea/gitea.git"
ssh_key: ${{ secrets.DEPLOY_KEY }}

22
.github/workflows/cron-lock.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: cron-lock
on:
schedule:
- cron: "0 0 * * *" # every day at 00:00 UTC
workflow_dispatch:
permissions:
issues: write
pull-requests: write
concurrency:
group: lock
jobs:
action:
runs-on: ubuntu-latest
if: github.repository == 'go-gitea/gitea'
steps:
- uses: dessant/lock-threads@v4
with:
issue-inactive-days: 45

48
.github/workflows/cron-translations.yml vendored Normal file
View File

@ -0,0 +1,48 @@
name: cron-translations
on:
schedule:
- cron: "7 0 * * *" # every day at 00:07 UTC
jobs:
crowdin-pull:
runs-on: ubuntu-latest
if: github.repository == 'go-gitea/gitea'
steps:
- uses: actions/checkout@v3
- name: download from crowdin
uses: docker://jonasfranz/crowdin
env:
CROWDIN_KEY: ${{ secrets.CROWDIN_KEY }}
PLUGIN_DOWNLOAD: true
PLUGIN_EXPORT_DIR: options/locale/
PLUGIN_IGNORE_BRANCH: true
PLUGIN_PROJECT_IDENTIFIER: gitea
- name: update locales
run: ./build/update-locales.sh
- name: push translations to repo
uses: appleboy/git-push-action@v0.0.2
with:
author_email: "teabot@gitea.io"
author_name: GiteaBot
branch: main
commit: true
commit_message: "[skip ci] Updated translations via Crowdin"
remote: "git@github.com:go-gitea/gitea.git"
ssh_key: ${{ secrets.DEPLOY_KEY }}
crowdin-push:
runs-on: ubuntu-latest
if: github.repository == 'go-gitea/gitea'
steps:
- uses: actions/checkout@v3
- name: push translations to crowdin
uses: docker://jonasfranz/crowdin
env:
CROWDIN_KEY: ${{ secrets.CROWDIN_KEY }}
PLUGIN_UPLOAD: true
PLUGIN_EXPORT_DIR: options/locale/
PLUGIN_IGNORE_BRANCH: true
PLUGIN_PROJECT_IDENTIFIER: gitea
PLUGIN_FILES: |
locale_en-US.ini: options/locale/locale_en-US.ini
PLUGIN_BRANCH: main

53
.github/workflows/files-changed.yml vendored Normal file
View File

@ -0,0 +1,53 @@
name: files-changed
on:
workflow_call:
outputs:
backend:
description: "whether backend files changed"
value: ${{ jobs.detect.outputs.backend }}
frontend:
description: "whether frontend files changed"
value: ${{ jobs.detect.outputs.frontend }}
docs:
description: "whether docs files changed"
value: ${{ jobs.detect.outputs.docs }}
actions:
description: "whether actions files changed"
value: ${{ jobs.detect.outputs.actions }}
jobs:
detect:
name: detect which files changed
runs-on: ubuntu-latest
timeout-minutes: 3
# Map a step output to a job output
outputs:
backend: ${{ steps.changes.outputs.backend }}
frontend: ${{ steps.changes.outputs.frontend }}
docs: ${{ steps.changes.outputs.docs }}
actions: ${{ steps.changes.outputs.actions }}
steps:
- uses: actions/checkout@v3
- uses: dorny/paths-filter@v2
id: changes
with:
filters: |
backend:
- "**/*.go"
- "**/*.tmpl"
- "go.mod"
- "go.sum"
frontend:
- "**/*.js"
- "web_src/**"
- "package.json"
- "package-lock.json"
docs:
- "**/*.md"
- "docs/**"
actions:
- ".github/workflows/*"

142
.github/workflows/pull-compliance.yml vendored Normal file
View File

@ -0,0 +1,142 @@
name: compliance
on:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
files-changed:
uses: ./.github/workflows/files-changed.yml
lint-backend:
if: needs.files-changed.outputs.backend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20"
check-latest: true
- run: make deps-backend deps-tools
- run: make lint-backend
env:
TAGS: bindata sqlite sqlite_unlock_notify
lint-go-windows:
if: needs.files-changed.outputs.backend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20"
check-latest: true
- run: make deps-backend deps-tools
- run: make lint-go-windows lint-go-vet
env:
TAGS: bindata sqlite sqlite_unlock_notify
GOOS: windows
GOARCH: amd64
lint-go-gogit:
if: needs.files-changed.outputs.backend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20"
check-latest: true
- run: make deps-backend deps-tools
- run: make lint-go
env:
TAGS: bindata gogit sqlite sqlite_unlock_notify
checks-backend:
if: needs.files-changed.outputs.backend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20"
check-latest: true
- run: make deps-backend deps-tools
- run: make --always-make checks-backend # ensure the "go-licenses" make target runs
frontend:
if: needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 20
- run: make deps-frontend
- run: make lint-frontend
- run: make checks-frontend
backend:
if: needs.files-changed.outputs.backend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20"
check-latest: true
- uses: actions/setup-node@v3
with:
node-version: 20
- run: make deps-backend deps-tools
- run: make deps-frontend
- run: make frontend
- run: go build -o gitea_no_gcc # test if build succeeds without the sqlite tag
- name: build-backend-arm64
run: make backend # test cross compile
env:
GOOS: linux
GOARCH: arm64
TAGS: bindata gogit
- name: build-backend-windows
run: go build -o gitea_windows
env:
GOOS: windows
GOARCH: amd64
TAGS: bindata gogit
- name: build-backend-386
run: go build -o gitea_linux_386 # test if compatible with 32 bit
env:
GOOS: linux
GOARCH: 386
docs:
if: needs.files-changed.outputs.docs == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 20
- run: make deps-frontend
- run: make lint-md
- run: make docs # test if build could succeed
actions:
if: needs.files-changed.outputs.actions == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
- run: make lint-actions

247
.github/workflows/pull-db-tests.yml vendored Normal file
View File

@ -0,0 +1,247 @@
name: db-tests
on:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
files-changed:
uses: ./.github/workflows/files-changed.yml
test-pgsql:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
services:
pgsql:
image: postgres:15
env:
POSTGRES_DB: test
POSTGRES_PASSWORD: postgres
ports:
- "5432:5432"
ldap:
image: gitea/test-openldap:latest
ports:
- "389:389"
- "636:636"
minio:
# as github actions doesn't support "entrypoint", we need to use a non-official image
# that has a custom entrypoint set to "minio server /data"
image: bitnami/minio:2021.3.17
env:
MINIO_ACCESS_KEY: 123456
MINIO_SECRET_KEY: 12345678
ports:
- "9000:9000"
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20.0"
- name: Add hosts to /etc/hosts
run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 pgsql ldap minio" | sudo tee -a /etc/hosts'
- run: make deps-backend
- run: make backend
env:
TAGS: bindata
- run: make test-pgsql-migration test-pgsql
timeout-minutes: 50
env:
TAGS: bindata gogit
RACE_ENABLED: true
TEST_TAGS: gogit
TEST_LDAP: 1
USE_REPO_TEST_DIR: 1
test-sqlite:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20.0"
- run: make deps-backend
- run: make backend
env:
TAGS: bindata gogit sqlite sqlite_unlock_notify
- run: make test-sqlite-migration test-sqlite
timeout-minutes: 50
env:
TAGS: bindata gogit sqlite sqlite_unlock_notify
RACE_ENABLED: true
TEST_TAGS: gogit sqlite sqlite_unlock_notify
USE_REPO_TEST_DIR: 1
test-unit:
if: needs.files-changed.outputs.backend == 'true'
needs: files-changed
runs-on: ubuntu-latest
services:
mysql:
image: mysql:5.7
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: test
ports:
- "3306:3306"
elasticsearch:
image: elasticsearch:7.5.0
env:
discovery.type: single-node
ports:
- "9200:9200"
smtpimap:
image: tabascoterrier/docker-imap-devel:latest
ports:
- "25:25"
- "143:143"
- "587:587"
- "993:993"
redis:
image: redis
options: >- # wait until redis has started
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 3s
--health-retries 10
ports:
- 6379:6379
minio:
image: bitnami/minio:2021.3.17
env:
MINIO_ACCESS_KEY: 123456
MINIO_SECRET_KEY: 12345678
ports:
- "9000:9000"
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20.0"
- name: Add hosts to /etc/hosts
run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mysql elasticsearch smtpimap" | sudo tee -a /etc/hosts'
- run: make deps-backend
- run: make backend
env:
TAGS: bindata
- name: unit-tests
run: make unit-test-coverage test-check
env:
TAGS: bindata
RACE_ENABLED: true
GITHUB_READ_TOKEN: ${{ secrets.GITHUB_READ_TOKEN }}
- name: unit-tests-gogit
run: make unit-test-coverage test-check
env:
TAGS: bindata gogit
RACE_ENABLED: true
GITHUB_READ_TOKEN: ${{ secrets.GITHUB_READ_TOKEN }}
test-mysql5:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
services:
mysql:
image: mysql:5.7
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: test
ports:
- "3306:3306"
elasticsearch:
image: elasticsearch:7.5.0
env:
discovery.type: single-node
ports:
- "9200:9200"
smtpimap:
image: tabascoterrier/docker-imap-devel:latest
ports:
- "25:25"
- "143:143"
- "587:587"
- "993:993"
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20.0"
- name: Add hosts to /etc/hosts
run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mysql elasticsearch smtpimap" | sudo tee -a /etc/hosts'
- run: make deps-backend
- run: make backend
env:
TAGS: bindata
- name: run tests
run: make test-mysql-migration integration-test-coverage
env:
TAGS: bindata
RACE_ENABLED: true
USE_REPO_TEST_DIR: 1
TEST_INDEXER_CODE_ES_URL: "http://elastic:changeme@elasticsearch:9200"
test-mysql8:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
services:
mysql8:
image: mysql:8
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: testgitea
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20.0"
- name: Add hosts to /etc/hosts
run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mysql8" | sudo tee -a /etc/hosts'
- run: make deps-backend
- run: make backend
env:
TAGS: bindata
- run: make test-mysql8-migration test-mysql8
timeout-minutes: 50
env:
TAGS: bindata
USE_REPO_TEST_DIR: 1
test-mssql:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
services:
mssql:
image: mcr.microsoft.com/mssql/server:latest
env:
ACCEPT_EULA: Y
MSSQL_PID: Standard
SA_PASSWORD: MwantsaSecurePassword1
ports:
- "1433:1433"
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20.0"
- name: Add hosts to /etc/hosts
run: '[ -e "/.dockerenv" ] || [ -e "/run/.containerenv" ] || echo "127.0.0.1 mssql" | sudo tee -a /etc/hosts'
- run: make deps-backend
- run: make backend
env:
TAGS: bindata
- run: make test-mssql-migration test-mssql
timeout-minutes: 50
env:
TAGS: bindata
USE_REPO_TEST_DIR: 1

View File

@ -0,0 +1,23 @@
name: docker-dryrun
on:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
files-changed:
uses: ./.github/workflows/files-changed.yml
docker-dryrun:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: docker/setup-buildx-action@v2
- uses: docker/build-push-action@v4
with:
push: false
tags: gitea/gitea:linux-amd64

32
.github/workflows/pull-e2e-tests.yml vendored Normal file
View File

@ -0,0 +1,32 @@
name: e2e-tests
on:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
files-changed:
uses: ./.github/workflows/files-changed.yml
test-e2e:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.frontend == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ">=1.20"
check-latest: true
- uses: actions/setup-node@v3
with:
node-version: 20
- run: make deps-frontend frontend deps-backend
- run: npx playwright install --with-deps
- run: make test-e2e-sqlite
timeout-minutes: 40
env:
USE_REPO_TEST_DIR: 1

3
.gitignore vendored
View File

@ -47,6 +47,7 @@ cpu.out
*.db
*.log
*.log.*.gz
/gitea
/gitea-vet
@ -71,12 +72,12 @@ cpu.out
/tests/e2e/test-artifacts
/tests/e2e/test-snapshots
/tests/*.ini
/tests/**/*.git/**/*.sample
/node_modules
/yarn.lock
/yarn-error.log
/npm-debug.log*
/public/js
/public/serviceworker.js
/public/css
/public/fonts
/public/img/webpack

View File

@ -31,7 +31,7 @@ vscode:
- golang.go
- stylelint.vscode-stylelint
- DavidAnson.vscode-markdownlint
- johnsoncodehk.volar
- Vue.volar
- ms-azuretools.vscode-docker
- zixuanchen.vitest-explorer
- alexcvzz.vscode-sqlite

View File

@ -5,6 +5,7 @@ linters:
- depguard
- dupl
- errcheck
- forbidigo
- gocritic
# - gocyclo # The cyclomatic complexety of a lot of functions is too high, we should refactor those another time.
- gofmt
@ -22,7 +23,7 @@ linters:
- unconvert
- unused
# - varcheck # deprecated - https://github.com/golangci/golangci-lint/issues/1841
# - wastedassign # disabled - https://github.com/golangci/golangci-lint/issues/2649
- wastedassign
enable-all: false
disable-all: true
fast: false
@ -85,6 +86,7 @@ linters-settings:
- io/ioutil: "use os or io instead"
- golang.org/x/exp: "it's experimental and unreliable."
- code.gitea.io/gitea/modules/git/internal: "do not use the internal package, use AddXxx function instead"
- gopkg.in/ini.v1: "do not use the ini package, use gitea's config system instead"
issues:
max-issues-per-linter: 0
@ -105,73 +107,25 @@ issues:
- errcheck
- dupl
- gosec
- path: cmd
linters:
- forbidigo
- linters:
- dupl
text: "webhook"
- linters:
- gocritic
text: "`ID' should not be capitalized"
- path: modules/templates/helper.go
linters:
- gocritic
- linters:
- unused
- deadcode
text: "swagger"
- path: contrib/pr/checkout.go
linters:
- errcheck
- path: models/issue.go
linters:
- errcheck
- path: models/migrations/
linters:
- errcheck
- path: modules/log/
linters:
- errcheck
- path: routers/api/v1/repo/issue_subscription.go
linters:
- dupl
- path: routers/repo/view.go
linters:
- dupl
- path: models/migrations/
linters:
- unused
- linters:
- staticcheck
text: "argument x is overwritten before first use"
- path: modules/httplib/httplib.go
linters:
- staticcheck
# Enabling this would require refactoring the methods and how they are called.
- path: models/issue_comment_list.go
linters:
- dupl
- path: models/update.go
linters:
- unused
- path: cmd/dump.go
linters:
- dupl
- path: services/webhook/webhook.go
linters:
- structcheck
- text: "commentFormatting: put a space between `//` and comment text"
linters:
- gocritic
- text: "exitAfterDefer:"
linters:
- gocritic
- path: modules/graceful/manager_windows.go
linters:
- staticcheck
text: "svc.IsAnInteractiveSession is deprecated: Use IsWindowsService instead."
- path: models/user/openid.go
linters:
- golint
- path: models/user/badge.go
linters:
- revive
text: "exported: type name will be used as user.UserBadge by other packages, and that stutters; consider calling this Badge"

View File

@ -1,8 +1,8 @@
*.min.css
*.min.js
/assets/*.json
/modules/options/bindata.go
/modules/public/bindata.go
/modules/templates/bindata.go
/public/vendor/plugins
/vendor
node_modules

3
.lgtm
View File

@ -1,3 +0,0 @@
pattern = "(?)LGTM"
self_approval_off = true
ignore_maintainers_file = true

View File

@ -5,12 +5,14 @@ ignoreFiles:
- "**/*.go"
overrides:
- files: ["**/chroma/*", "**/codemirror/*", "**/standalone/*", "**/console/*"]
- files: ["**/chroma/*", "**/codemirror/*", "**/standalone/*", "**/console.css", "font_i18n.css"]
rules:
scale-unlimited/declaration-strict-value: null
- files: ["**/chroma/*", "**/codemirror/*"]
rules:
block-no-empty: null
- files: ["**/*.vue"]
customSyntax: postcss-html
rules:
alpha-value-notation: null
@ -96,7 +98,7 @@ rules:
property-no-vendor-prefix: null
rule-empty-line-before: null
rule-selector-property-disallowed-list: null
scale-unlimited/declaration-strict-value: [color, {ignoreValues: /^(inherit|transparent|unset|initial|currentcolor)$/}]
scale-unlimited/declaration-strict-value: [[color, background-color, border-color, font-weight], {ignoreValues: /^(inherit|transparent|unset|initial|currentcolor|none)$/, ignoreFunctions: false, disableFix: true}]
selector-attribute-name-disallowed-list: null
selector-attribute-operator-allowed-list: null
selector-attribute-operator-disallowed-list: null

View File

@ -4,6 +4,66 @@ This changelog goes through all the changes that have been made in each release
without substantial changes to our git log; to see the highlights of what has
been added to each release, please refer to the [blog](https://blog.gitea.io).
## [1.19.3](https://github.com/go-gitea/gitea/releases/tag/1.19.3) - 2023-05-03
* SECURITY
* Use golang 1.20.4 to fix CVE-2023-24539, CVE-2023-24540, and CVE-2023-29400
* ENHANCEMENTS
* Enable whitespace rendering on selection in Monaco (#24444) (#24485)
* Improve milestone filter on issues page (#22423) (#24440)
* BUGFIXES
* Fix api error message if fork exists (#24487) (#24493)
* Fix user-cards format (#24428) (#24431)
* Fix incorrect CurrentUser check for docker rootless (#24435)
* Getting the tag list does not require being signed in (#24413) (#24416)
## [1.19.2](https://github.com/go-gitea/gitea/releases/tag/1.19.2) - 2023-04-26
* SECURITY
* Require repo scope for PATs for private repos and basic authentication (#24362) (#24364)
* Only delete secrets belonging to its owner (#24284) (#24286)
* API
* Fix typo in API route (#24310) (#24332)
* Fix access token issue on some public endpoints (#24194) (#24259)
* ENHANCEMENTS
* Fix broken clone script on an empty archived repo (#24339) (#24348)
* Fix Monaco IOS keyboard button (#24341) (#24347)
* Don't set meta `theme-color` by default (#24340) (#24346)
* Wrap too long push mirror addresses (#21120) (#24334)
* Add --font-weight-bold and set previous bold to 601 (#24307) (#24331)
* Unify nightly naming across binaries and docker images (#24116) (#24308)
* Fix footer display (#24251) (#24269)
* Fix label color, fix divider in dropdown (#24215) (#24244)
* Vertical widths of containers removed (#24184) (#24211)
* Use correct locale key for forks page (#24172) (#24175)
* Sort repo topic labels by name (#24123) (#24153)
* Highlight selected file in the PR file tree (#23947) (#24126)
* BUGFIXES
* Fix auth check bug (#24382) (#24387)
* Add tags list for repos whose release setting is disabled (#23465) (#24369)
* Fix wrong error info in RepoRefForAPI (#24344) (#24351)
* Fix no edit/close/delete button in org repo project view page (#24349)
* Respect the REGISTER_MANUAL_CONFIRM setting when registering via OIDC (#24035) (#24333)
* Remove org users who belong to no teams (#24247) (#24313)
* Fix bug when deleting wiki with no code write permission (#24274) (#24295)
* Handle canceled workflow as a warning instead of a fail (#24282) (#24292)
* Load reviewer for comments when dismissing a review (#24281) (#24288)
* Show commit history for closed/merged PRs (#24238) (#24261)
* Fix owner team access mode value in team_unit table (#24224)
* Fix issue attachment handling (#24202) (#24221)
* Fix incorrect CORS default values (#24206) (#24217)
* Fix template error in pull request with deleted head repo (#24192) (#24216)
* Don't list root repository on compare page if pulls not allowed (#24183) (#24210)
* Fix calReleaseNumCommitsBehind (#24148) (#24197)
* Fix Org edit page bugs: renaming detection, maxlength (#24161) (#24171)
* Update redis library to support redis v7 (#24114) (#24156)
* Use 1.18's aria role for dropdown menus (#24144) (#24155)
* Fix 2-dot direct compare to use the right base commit (#24133) (#24150)
* Fix incorrect server error content in RunnersList (#24118) (#24121)
* Fix mismatch between hook events and github event types (#24048) (#24091)
* BUILD
* Support converting varchar to nvarchar for mssql database (#24105) (#24168)
## [1.19.1](https://github.com/go-gitea/gitea/releases/tag/v1.19.1) - 2023-04-12
* BREAKING

View File

@ -1,75 +1,157 @@
# Contribution Guidelines
## Table of Contents
<details><summary>Table of Contents</summary>
- [Contribution Guidelines](#contribution-guidelines)
- [Table of Contents](#table-of-contents)
- [Introduction](#introduction)
- [Bug reports](#bug-reports)
- [Discuss your design](#discuss-your-design)
- [Testing redux](#testing-redux)
- [Vendoring](#vendoring)
- [Translation](#translation)
- [Issues](#issues)
- [How to report issues](#how-to-report-issues)
- [Types of issues](#types-of-issues)
- [Discuss your design before the implementation](#discuss-your-design-before-the-implementation)
- [Building Gitea](#building-gitea)
- [Code review](#code-review)
- [Styleguide](#styleguide)
- [Dependencies](#dependencies)
- [Backend](#backend)
- [Frontend](#frontend)
- [Design guideline](#design-guideline)
- [Styleguide](#styleguide)
- [Copyright](#copyright)
- [Testing](#testing)
- [Translation](#translation)
- [Code review](#code-review)
- [Pull request format](#pull-request-format)
- [PR title and summary](#pr-title-and-summary)
- [Milestone](#milestone)
- [Labels](#labels)
- [Breaking PRs](#breaking-prs)
- [What is a breaking PR?](#what-is-a-breaking-pr)
- [How to handle breaking PRs?](#how-to-handle-breaking-prs)
- [Maintaining open PRs](#maintaining-open-prs)
- [Getting PRs merged](#getting-prs-merged)
- [Final call](#final-call)
- [Commit messages](#commit-messages)
- [PR Co-authors](#pr-co-authors)
- [PRs targeting `main`](#prs-targeting-main)
- [Backport PRs](#backport-prs)
- [Documentation](#documentation)
- [API v1](#api-v1)
- [GitHub API compatability](#github-api-compatability)
- [Adding/Maintaining API routes](#addingmaintaining-api-routes)
- [When to use what HTTP method](#when-to-use-what-http-method)
- [Requirements for API routes](#requirements-for-api-routes)
- [Backports and Frontports](#backports-and-frontports)
- [What is backported?](#what-is-backported)
- [How to backport?](#how-to-backport)
- [Format of backport PRs](#format-of-backport-prs)
- [Frontports](#frontports)
- [Developer Certificate of Origin (DCO)](#developer-certificate-of-origin-dco)
- [Release Cycle](#release-cycle)
- [Maintainers](#maintainers)
- [Owners](#owners)
- [Technical Oversight Committee (TOC)](#technical-oversight-committee-toc)
- [Current TOC members](#current-toc-members)
- [Previous TOC/owners members](#previous-tocowners-members)
- [Governance Compensation](#governance-compensation)
- [TOC \& Working groups](#toc--working-groups)
- [Roadmap](#roadmap)
- [Versions](#versions)
- [Releasing Gitea](#releasing-gitea)
- [Copyright](#copyright)
</details>
## Introduction
This document explains how to contribute changes to the Gitea project.
It assumes you have followed the
[installation instructions](https://docs.gitea.io/en-us/).
Sensitive security-related issues should be reported to
[security@gitea.io](mailto:security@gitea.io).
This document explains how to contribute changes to the Gitea project. \
It assumes you have followed the [installation instructions](https://docs.gitea.io/en-us/). \
Sensitive security-related issues should be reported to [security@gitea.io](mailto:security@gitea.io).
For configuring IDE or code editor to develop Gitea see [IDE and code editor configuration](contrib/ide/)
For configuring IDEs for Gitea development, see the [contributed IDE configurations](contrib/ide/).
## Bug reports
## Issues
Please search the issues on the issue tracker with a variety of keywords
to ensure your bug is not already reported.
### How to report issues
If unique, [open an issue](https://github.com/go-gitea/gitea/issues/new)
and answer the questions so we can understand and reproduce the
problematic behavior.
Please search the issues on the issue tracker with a variety of related keywords to ensure that your issue has not already been reported.
To show us that the issue you are having is in Gitea itself, please
write clear, concise instructions so we can reproduce the behavior—
even if it seems obvious. The more detailed and specific you are,
the faster we can fix the issue. Check out [How to Report Bugs
Effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html).
If your issue has not been reported yet, [open an issue](https://github.com/go-gitea/gitea/issues/new)
and answer the questions so we can understand and reproduce the problematic behavior. \
Please write clear and concise instructions so that we can reproduce the behavior — even if it seems obvious. \
The more detailed and specific you are, the faster we can fix the issue. \
It is really helpful if you can reproduce your problem on a site running on the latest commits, i.e. <https://try.gitea.io>, as perhaps your problem has already been fixed on a current version. \
Please follow the guidelines described in [How to Report Bugs Effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html) for your report.
Please be kind, remember that Gitea comes at no cost to you, and you're
getting free help.
Please be kind, remember that Gitea comes at no cost to you, and you're getting free help.
## Discuss your design
### Types of issues
The project welcomes submissions. If you want to change or add something,
please let everyone know what you're working on—[file an issue](https://github.com/go-gitea/gitea/issues/new)!
Significant changes must go through the change proposal process
before they can be accepted. To create a proposal, file an issue with
your proposed changes documented, and make sure to note in the title
of the issue that it is a proposal.
Typically, issues fall in one of the following categories:
This process gives everyone a chance to validate the design, helps
prevent duplication of effort, and ensures that the idea fits inside
the goals for the project and tools. It also checks that the design is
sound before code is written; the code review tool is not the place for
high-level discussions.
- `bug`: Something in the frontend or backend behaves unexpectedly
- `security issue`: bug that has serious implications such as leaking another users data. Please do not file such issues on the public tracker and send a mail to security@gitea.io instead
- `feature`: Completely new functionality. You should describe this feature in enough detail that anyone who reads the issue can understand how it is supposed to be implemented
- `enhancement`: An existing feature should get an upgrade
- `refactoring`: Parts of the code base don't conform with other parts and should be changed to improve Gitea's maintainability
## Testing redux
### Discuss your design before the implementation
Before submitting a pull request, run all the tests for the whole tree
to make sure your changes don't cause regression elsewhere.
We welcome submissions. \
If you want to change or add something, please let everyone know what you're working on — [file an issue](https://github.com/go-gitea/gitea/issues/new) or comment on an existing one before starting your work!
Significant changes such as new features must go through the change proposal process before they can be accepted. \
This is mainly to save yourself the trouble of implementing it, only to find out that your proposed implementation has some potential problems. \
Furthermore, this process gives everyone a chance to validate the design, helps prevent duplication of effort, and ensures that the idea fits inside
the goals for the project and tools.
Pull requests should not be the place for architecture discussions.
## Building Gitea
See the [development setup instructions](https://docs.gitea.com/development/hacking-on-gitea).
## Dependencies
### Backend
Go dependencies are managed using [Go Modules](https://golang.org/cmd/go/#hdr-Module_maintenance). \
You can find more details in the [go mod documentation](https://go.dev/ref/mod) and the [Go Modules Wiki](https://github.com/golang/go/wiki/Modules).
Pull requests should only modify `go.mod` and `go.sum` where it is related to your change, be it a bugfix or a new feature. \
Apart from that, these files should only be modified by Pull Requests whose only purpose is to update dependencies.
The `go.mod`, `go.sum` update needs to be justified as part of the PR description,
and must be verified by the reviewers and/or merger to always reference
an existing upstream commit.
### Frontend
For the frontend, we use [npm](https://www.npmjs.com/).
The same restrictions apply for frontend dependencies as for backend dependencies, with the exceptions that the files for it are `package.json` and `package-lock.json`, and that new versions must always reference an existing version.
## Design guideline
Depending on your change, please read the
- [backend development guideline](https://docs.gitea.com/contributing/guidelines-backend)
- [frontend development guideline](https://docs.gitea.com/contributing/guidelines-frontend)
- [refactoring guideline](https://docs.gitea.com/contributing/guidelines-refactoring)
## Styleguide
You should always run `make fmt` before committing to conform to Gitea's styleguide.
## Copyright
New code files that you contribute should use the standard copyright header:
```
// Copyright <current year> The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
```
Afterwards, copyright should only be modified when the copyright author changes.
## Testing
Before submitting a pull request, run all tests to make sure your changes don't cause a regression elsewhere.
Here's how to run the test suite:
@ -77,257 +159,304 @@ Here's how to run the test suite:
| | |
| :-------------------- | :---------------------------------------------------------------- |
|``make lint`` | lint everything (not suggest if you only change one type code) |
|``make lint`` | lint everything (not needed if you only change the front- **or** backend) |
|``make lint-frontend`` | lint frontend files |
|``make lint-backend`` | lint backend files |
- run test code (Suggest run in Linux)
- run tests (we suggest running them on Linux)
| | |
| :------------------------------------- | :----------------------------------------------- |
|``make test[\#TestSpecificName]`` | run unit test |
|``make test-sqlite[\#TestSpecificName]``| run [integration](tests/integration) test for SQLite |
|[More details about integration tests](tests/integration/README.md) |
|``make test-e2e-sqlite[\#TestSpecificFileName]``| run [end-to-end](tests/e2e) test for SQLite |
|[More details about e2e tests](tests/e2e/README.md) |
## Vendoring
We manage dependencies via [Go Modules](https://golang.org/cmd/go/#hdr-Module_maintenance), more details: [go mod](https://go.dev/ref/mod).
Pull requests should only include `go.mod`, `go.sum` updates if they are part of
the same change, be it a bugfix or a feature addition.
The `go.mod`, `go.sum` update needs to be justified as part of the PR description,
and must be verified by the reviewers and/or merger to always reference
an existing upstream commit.
You can find more information on how to get started with it on the [Modules Wiki](https://github.com/golang/go/wiki/Modules).
| Command | Action | |
| :------------------------------------- | :----------------------------------------------- | ------------ |
|``make test[\#SpecificTestName]`` | run unit test(s) |
|``make test-sqlite[\#SpecificTestName]``| run [integration](tests/integration) test(s) for SQLite |[More details](tests/integration/README.md) |
|``make test-e2e-sqlite[\#SpecificTestName]``| run [end-to-end](tests/e2e) test(s) for SQLite |[More details](tests/e2e/README.md) |
## Translation
We do all translation work inside [Crowdin](https://crowdin.com/project/gitea).
The only translation that is maintained in this Git repository is
[`en_US.ini`](https://github.com/go-gitea/gitea/blob/master/options/locale/locale_en-US.ini)
and is synced regularly to Crowdin. Once a translation has reached
A SATISFACTORY PERCENTAGE it will be synced back into this repo and
included in the next released version.
All translation work happens on [Crowdin](https://crowdin.com/project/gitea).
The only translation that is maintained in this repository is [the English translation](https://github.com/go-gitea/gitea/blob/master/options/locale/locale_en-US.ini).
It is synced regularly with Crowdin. \
Other locales on main branch **should not** be updated manually as they will be overwritten with each sync. \
Once a language has reached a **satisfactory percentage** of translated keys (~25%), it will be synced back into this repo and included in the next released version.
## Building Gitea
See the [hacking instructions](https://docs.gitea.io/en-us/hacking-on-gitea/).
The tool `go run build/backport-locale.go` can be used to backport locales from the main branch to release branches that were missed.
## Code review
Changes to Gitea must be reviewed before they are accepted—no matter who
makes the change, even if they are an owner or a maintainer. We use GitHub's
pull request workflow to do that. And, we also use [LGTM](http://lgtm.co)
to ensure every PR is reviewed by at least 2 maintainers.
### Pull request format
Please try to make your pull request easy to review for us. And, please read
the *[How to get faster PR reviews](https://github.com/kubernetes/community/blob/261cb0fd089b64002c91e8eddceebf032462ccd6/contributors/guide/pull-requests.md#best-practices-for-faster-reviews)* guide;
it has lots of useful tips for any project you may want to contribute.
Please try to make your pull request easy to review for us. \
For that, please read the [*Best Practices for Faster Reviews*](https://github.com/kubernetes/community/blob/261cb0fd089b64002c91e8eddceebf032462ccd6/contributors/guide/pull-requests.md#best-practices-for-faster-reviews) guide. \
It has lots of useful tips for any project you may want to contribute to. \
Some of the key points:
- Make small pull requests. The smaller, the faster to review and the
more likely it will be merged soon.
- Don't make changes unrelated to your PR. Maybe there are typos on
some comments, maybe refactoring would be welcome on a function... but
if that is not related to your PR, please make *another* PR for that.
- Split big pull requests into multiple small ones. An incremental change
will be faster to review than a huge PR.
- Use the first comment as a summary explainer of your PR and you should keep this up-to-date as the PR evolves.
- Make small pull requests. \
The smaller, the faster to review and the more likely it will be merged soon.
- Don't make changes unrelated to your PR. \
Maybe there are typos on some comments, maybe refactoring would be welcome on a function... \
but if that is not related to your PR, please make *another* PR for that.
- Split big pull requests into multiple small ones. \
An incremental change will be faster to review than a huge PR.
- Allow edits by maintainers. This way, the maintainers will take care of merging the PR later on instead of you.
If your PR could cause a breaking change you must add a BREAKING section to this comment e.g.:
### PR title and summary
In the PR title, describe the problem you are fixing, not how you are fixing it. \
Use the first comment as a summary of your PR. \
In the PR summary, you can describe exactly how you are fixing this problem. \
Keep this summary up-to-date as the PR evolves. \
If your PR changes the UI, you must add **after** screenshots in the PR summary. \
If you are not implementing a new feature, you should also post **before** screenshots for comparison. \
If your PR closes some issues, you must note that in a way that both GitHub and Gitea understand, i.e. by appending a paragraph like
```text
Fixes/Closes/Resolves #<ISSUE_NR_X>.
Fixes/Closes/Resolves #<ISSUE_NR_Y>.
```
to your summary. \
Each issue that will be closed must stand on a separate line.
### Milestone
A PR should only be assigned to a milestone if it will likely be merged into the given version. \
As a rule of thumb, assume that a PR will stay open for an additional month for every 100 added lines. \
PRs without a milestone may not be merged.
### Labels
Every PR should be labeled correctly with every label that applies. \
This includes especially the distinction between `bug` (fixing existing functionality), `feature` (new functionality), `enhancement` (upgrades for existing functionality), and `refactoring` (improving the internal code structure without changing the output (much)). \
Furthermore,
- the amount of pending required approvals
- whether this PR is `blocked`, a `backport` or `breaking`
- if it targets the `ui` or `api`
- if it increases the application `speed`
- reduces `memory usage`
are oftentimes notable labels.
### Breaking PRs
#### What is a breaking PR?
A PR is breaking if it meets one of the following criteria:
- It changes API output in an incompatible way for existing users
- It removes a setting that an admin could previously set (i.e. via `app.ini`)
- An admin must do something manually to restore the old behavior
In particular, this means that adding new settings is not breaking.\
Changing the default value of a setting or replacing the setting with another one is breaking, however.
#### How to handle breaking PRs?
If your PR has a breaking change, you must add a `BREAKING` section to your PR summary, e.g.
```
## :warning: BREAKING :warning:
```
To explain how this could affect users and how to mitigate these changes.
To explain how this will affect users and how to mitigate these changes.
Once code review starts on your PR, do not rebase nor squash your branch as it makes it
difficult to review the new changes. Only if there is a need, sync your branch by merging
the base branch into yours. Don't worry about merge commits messing up your tree as
the final merge process squashes all commits into one, with the visible commit message (first
line) being the PR title + PR index and description being the PR's first comment.
### Maintaining open PRs
Once your PR gets the `lgtm/done` label, don't worry about keeping it up-to-date or breaking
builds (unless there's a merge conflict or a request is made by a maintainer to make
modifications). It is the maintainer team's responsibility from this point to get it merged.
The moment you create a non-draft PR or the moment you convert a draft PR to a non-draft PR is the moment code review starts for it. \
Once that happens, do not rebase or squash your branch anymore as it makes it difficult to review the new changes. \
Merge the base branch into your branch only when you really need to, i.e. because of conflicting changes in the mean time. \
This reduces unnecessary CI runs. \
Don't worry about merge commits messing up your commit history as every PR will be squash merged. \
This means that all changes are joined into a single new commit whose message is as described below.
## Styleguide
### Getting PRs merged
For imports you should use the following format (*without* the comments)
Changes to Gitea must be reviewed before they are accepted — no matter who
makes the change, even if they are an owner or a maintainer. \
The only exception are critical bugs that prevent Gitea from being compiled or started. \
Specifically, we require two approvals from maintainers for every PR. \
Once this criteria has been met, your PR receives the `lgtm/done` label. \
From this point on, your only responsibility is to fix merge conflicts or respond to/implement requests by maintainers. \
It is the responsibility of the maintainers from this point to get your PR merged.
```go
import (
// stdlib
"fmt"
"math"
If a PR has the `lgtm/done` label and there are no open discussions or merge conflicts anymore, any maintainer can add the `reviewed/wait-merge` label. \
This label means that the PR is part of the merge queue and will be merged as soon as possible. \
The merge queue will be cleared in the order of the list below:
// local packages
"code.gitea.io/gitea/models"
"code.gitea.io/sdk/gitea"
<https://github.com/go-gitea/gitea/pulls?q=is%3Apr+label%3Areviewed%2Fwait-merge+sort%3Acreated-asc+is%3Aopen>
// external packages
"github.com/foo/bar"
"gopkg.io/baz.v1"
)
Gitea uses it's own tool, the <https://github.com/GiteaBot/gitea-backporter> to automate parts of the review process. \
This tool does the things listed below automatically:
- create a backport PR if needed once the initial PR was merged
- remove the PR from the merge queue after the PR merged
- keep the oldest branch in the merge queue up to date with merges
### Final call
If a PR has been ignored for more than 7 days with no comments or reviews, and the author or any maintainer believes it will not survive a long wait (such as a refactoring PR), they can send "final call" to the TOC by mentioning them in a comment.
After another 7 days, if there is still zero approval, this is considered a polite refusal, and the PR will be closed to avoid wasting further time. Therefore, the "final call" has a cost, and should be used cautiously.
However, if there are no objections from maintainers, the PR can be merged with only one approval from the TOC (not the author).
### Commit messages
Mergers are able and required to rewrite the PR title and summary (the first comment of a PR) so that it can produce an easily understandable commit message if necessary. \
The final commit message should no longer contain any uncertainty such as `hopefully, <x> won't happen anymore`. Replace uncertainty with certainty.
#### PR Co-authors
A person counts as a PR co-author the moment they (co-)authored a commit that is not simply a `Merge base branch into branch` commit. \
Mergers are required to remove such "false-positive" co-authors when writing the commit message. \
The true co-authors must remain in the commit message.
#### PRs targeting `main`
The commit message of PRs targeting `main` is always
```bash
$PR_TITLE ($PR_INDEX)
$REWRITTEN_PR_SUMMARY
```
## Design guideline
#### Backport PRs
To maintain understandable code and avoid circular dependencies it is important to have a good structure of the code. The Gitea code is divided into the following parts:
The commit message of backport PRs is always
- **models:** Contains the data structures used by xorm to construct database tables. It also contains supporting functions to query and update the database. Dependencies to other code in Gitea should be avoided although some modules might be needed (for example for logging).
- **models/fixtures:** Sample model data used in integration tests.
- **models/migrations:** Handling of database migrations between versions. PRs that changes a database structure shall also have a migration step.
- **modules:** Different modules to handle specific functionality in Gitea. Shall only depend on other modules but not other packages (models, services).
- **public:** Frontend files (javascript, images, css, etc.)
- **routers:** Handling of server requests. As it uses other Gitea packages to serve the request, other packages (models, modules or services) shall not depend on routers.
- **services:** Support functions for common routing operations. Uses models and modules to handle the request.
- **templates:** Golang templates for generating the html output.
- **tests/e2e:** End to end tests
- **tests/integration:** Integration tests
- **tests/gitea-repositories-meta:** Sample repos used in integration tests. Adding a new repo requires editing `models/fixtures/repositories.yml` and `models/fixtures/repo_unit.yml` to match.
- **tests/gitea-lfs-meta:** Sample LFS objects used in integration tests. Adding a new object requires editing `models/fixtures/lfs_meta_object.yml` to match.
- **vendor:** External code that Gitea depends on.
```bash
$PR_TITLE ($INITIAL_PR_INDEX) ($BACKPORT_PR_INDEX)
$REWRITTEN_PR_SUMMARY
```
## Documentation
If you add a new feature or change an existing aspect of Gitea, the documentation for that feature must be created or updated.
If you add a new feature or change an existing aspect of Gitea, the documentation for that feature must be created or updated in the same PR.
## API v1
The API is documented by [swagger](http://try.gitea.io/api/swagger) and is based on [GitHub API v3](https://developer.github.com/v3/).
The API is documented by [swagger](http://try.gitea.io/api/swagger) and is based on [the GitHub API](https://docs.github.com/en/rest).
Thus, Gitea´s API should use the same endpoints and fields as GitHub´s API as far as possible, unless there are good reasons to deviate.
### GitHub API compatability
If Gitea provides functionality that GitHub does not, a new endpoint can be created.
Gitea's API should use the same endpoints and fields as the GitHub API as far as possible, unless there are good reasons to deviate. \
If Gitea provides functionality that GitHub does not, a new endpoint can be created. \
If information is provided by Gitea that is not provided by the GitHub API, a new field can be used that doesn't collide with any GitHub fields. \
Updating an existing API should not remove existing fields unless there is a really good reason to do so. \
The same applies to status responses. If you notice a problem, feel free to leave a comment in the code for future refactoring to API v2 (which is currently not planned).
If information is provided by Gitea that is not provided by the GitHub API, a new field can be used that doesn't collide with any GitHub fields.
### Adding/Maintaining API routes
Updating an existing API should not remove existing fields unless there is a really good reason to do so.
All expected results (errors, success, fail messages) must be documented ([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/repo/issue.go#L319-L327)). \
All JSON input types must be defined as a struct in [modules/structs/](modules/structs/) ([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/modules/structs/issue.go#L76-L91)) \
and referenced in [routers/api/v1/swagger/options.go](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/swagger/options.go). \
They can then be used like [this example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/repo/issue.go#L318). \
All JSON responses must be defined as a struct in [modules/structs/](modules/structs/) ([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/modules/structs/issue.go#L36-L68)) \
and referenced in its category in [routers/api/v1/swagger/](routers/api/v1/swagger/) ([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/swagger/issue.go#L11-L16)) \
They can be used like [this example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/repo/issue.go#L277-L279).
The same applies to status responses. If you notice a problem, feel free to leave a comment in the code for future refactoring to APIv2 (which is currently not planned).
All expected results (errors, success, fail messages) should be documented
([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/repo/issue.go#L319-L327)).
All JSON input types must be defined as a struct in [modules/structs/](modules/structs/)
([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/modules/structs/issue.go#L76-L91))
and referenced in
[routers/api/v1/swagger/options.go](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/swagger/options.go).
They can then be used like the following:
([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/repo/issue.go#L318)).
All JSON responses must be defined as a struct in [modules/structs/](modules/structs/)
([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/modules/structs/issue.go#L36-L68))
and referenced in its category in [routers/api/v1/swagger/](routers/api/v1/swagger/)
([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/swagger/issue.go#L11-L16))
They can be used like the following:
([example](https://github.com/go-gitea/gitea/blob/c620eb5b2d0d874da68ebd734d3864c5224f71f7/routers/api/v1/repo/issue.go#L277-L279))
### When to use what HTTP method
In general, HTTP methods are chosen as follows:
- **GET** endpoints return requested object and status **OK (200)**
- **DELETE** endpoints return status **No Content (204)**
- **POST** endpoints return status **Created (201)**, used to **create** new objects (e.g. a User)
- **PUT** endpoints return status **No Content (204)**, used to **add/assign** existing Objects (e.g. User) to something (e.g. Org-Team)
- **PATCH** endpoints return changed object and status **OK (200)**, used to **edit/change** an existing object
- **GET** endpoints return the requested object(s) and status **OK (200)**
- **DELETE** endpoints return the status **No Content (204)** and no content either
- **POST** endpoints are used to **create** new objects (e.g. a User) and return the status **Created (201)** and the created object
- **PUT** endpoints are used to **add/assign** existing Objects (e.g. a user to a team) and return the status **No Content (204)** and no content either
- **PATCH** endpoints are used to **edit/change** an existing object and return the changed object and the status **OK (200)**
An endpoint which changes/edits an object expects all fields to be optional (except ones to identify the object, which are required).
### Requirements for API routes
### Endpoints returning lists should
All parameters of endpoints changing/editing an object must be optional (except the ones to identify the object, which are required).
Endpoints returning lists must
- support pagination (`page` & `limit` options in query)
- set `X-Total-Count` header via **SetTotalCountHeader** ([example](https://github.com/go-gitea/gitea/blob/7aae98cc5d4113f1e9918b7ee7dd09f67c189e3e/routers/api/v1/repo/issue.go#L444))
## Backports and Frontports
Occasionally backports of PRs are required.
### What is backported?
The backported PR title should be:
We backport PRs given the following circumstances:
1. Feature freeze is active, but `<version>-rc0` has not been released yet. Here, we backport as much as possible. <!-- TODO: Is that our definition with the new backport bot? -->
2. `rc0` has been released. Here, we only backport bug- and security-fixes, and small enhancements. Large PRs such as refactors are not backported anymore. <!-- TODO: Is that our definition with the new backport bot? -->
3. We never backport new features.
4. We never backport breaking changes except when
1. The breaking change has no effect on the vast majority of users
2. The component triggering the breaking change is marked as experimental
### How to backport?
In the past, it was necessary to manually backport your PRs. \
Now, that's not a requirement anymore as our [backport bot](https://github.com/GiteaBot) tries to create backports automatically once the PR is merged when the PR
- does not have the label `backport/manual`
- has the label `backport/<version>`
The `backport/manual` label signifies either that you want to backport the change yourself, or that there were conflicts when backporting, thus you **must** do it yourself.
### Format of backport PRs
The title of backport PRs should be
```
Title of backported PR (#ORIGINAL_PR_NUMBER)
<original PR title> (#<original pr number>)
```
The first two lines of the summary of the backporting PR should be:
The first two lines of the summary of the backporting PR should be
```
Backport #ORIGINAL_PR_NUMBER
Backport #<original pr number>
```
with the rest of the summary matching the original PR. Similarly for frontports
with the rest of the summary and labels matching the original PR.
---
### Frontports
A command to help create backports can be found in `contrib/backport` and can be installed (from inside the gitea repo root directory) using:
```bash
go install contrib/backport/backport.go
```
Frontports behave exactly as described above for backports.
## Developer Certificate of Origin (DCO)
We consider the act of contributing to the code by submitting a Pull
Request as the "Sign off" or agreement to the certifications and terms
of the [DCO](DCO) and [MIT license](LICENSE). No further action is required.
Additionally you could add a line at the end of your commit message.
We consider the act of contributing to the code by submitting a Pull Request as the "Sign off" or agreement to the certifications and terms of the [DCO](DCO) and [MIT license](LICENSE). \
No further action is required. \
You can also decide to sign off your commits by adding the following line at the end of your commit messages:
```
Signed-off-by: Joe Smith <joe.smith@email.com>
```
If you set your `user.name` and `user.email` Git configs, you can add the
line to the end of your commit automatically with `git commit -s`.
If you set the `user.name` and `user.email` Git config options, you can add the line to the end of your commits automatically with `git commit -s`.
We assume in good faith that the information you provide is legally binding.
## Release Cycle
We adopted a release schedule to streamline the process of working
on, finishing, and issuing releases. The overall goal is to make a
minor release every three or four months, which breaks down into two or three months of
general development followed by one month of testing and polishing
known as the release freeze. All the feature pull requests should be
We adopted a release schedule to streamline the process of working on, finishing, and issuing releases. \
The overall goal is to make a major release every three or four months, which breaks down into two or three months of general development followed by one month of testing and polishing known as the release freeze. \
All the feature pull requests should be
merged before feature freeze. And, during the frozen period, a corresponding
release branch is open for fixes backported from main branch. Release candidates
are made during this period for user testing to
obtain a final version that is maintained in this branch.
Major release cycles are seasonal. They always begin on the 25th and end on
the 24th (i.e., the 25th of December to March 24th).
During a development cycle, we may also publish any necessary minor releases
for the previous version. For example, if the latest, published release is
v1.2, then minor changes for the previous release—e.g., v1.1.0 -> v1.1.1—are
still possible.
The previous release gets fixes for:
- Security issues
- Critical bugs
- Regressions
- Build issues
- Necessary enhancements (including necessary UI/UX fixes)
The backported fixes should avoid breaking downgrade between minor releases as much as possible.
## Maintainers
To make sure every PR is checked, we have [team
maintainers](MAINTAINERS). Every PR **MUST** be reviewed by at least
two maintainers (or owners) before it can get merged. A maintainer
should be a contributor of Gitea (or Gogs) and contributed at least
To make sure every PR is checked, we have [maintainers](MAINTAINERS). \
Every PR **must** be reviewed by at least two maintainers (or owners) before it can get merged. \
For refactoring PRs after a week and documentation only PRs, the approval of only one maintainer is enough. \
A maintainer should be a contributor of Gitea and contributed at least
4 accepted PRs. A contributor should apply as a maintainer in the
[Discord](https://discord.gg/NsatcWJ) #develop channel. The owners
or the team maintainers may invite the contributor. A maintainer
[Discord](https://discord.gg/Gitea) `#develop` channel. The team maintainers may invite the contributor. A maintainer
should spend some time on code reviews. If a maintainer has no
time to do that, they should apply to leave the maintainers team
and we will give them the honor of being a member of the [advisors
@ -341,69 +470,74 @@ if possible provide GPG signed commits.
https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/
https://help.github.com/articles/signing-commits-with-gpg/
## Owners
## Technical Oversight Committee (TOC)
Since Gitea is a pure community organization without any company support,
to keep the development healthy we will elect three owners every year. All
contributors may vote to elect up to three candidates, one of which will
be the main owner, and the other two the assistant owners. When the new
owners have been elected, the old owners will give up ownership to the
newly elected owners. If an owner is unable to do so, the other owners
will assist in ceding ownership to the newly elected owners.
For security reasons, Owners or any account with write access (like a bot)
must use 2FA.
At the start of 2023, the `Owners` team was dissolved. Instead, the governance charter proposed a technical oversight committee (TOC) which expands the ownership team of the Gitea project from three elected positions to six positions. Three positions would be elected as it has been over the past years, and the other three would consist of appointed members from the Gitea company.
https://blog.gitea.io/2023/02/gitea-quarterly-report-23q1/
When the new community members have been elected, the old members will give up ownership to the newly elected members. For security reasons, TOC members or any account with write access (like a bot) must use 2FA.
https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/
After the election, the new owners should proactively agree
with our [CONTRIBUTING](CONTRIBUTING.md) requirements in the
[Discord](https://discord.gg/NsatcWJ) #general channel. Below are the
words to speak:
### Current TOC members
```
I'm honored to having been elected an owner of Gitea, I agree with
[CONTRIBUTING](CONTRIBUTING.md). I will spend part of my time on Gitea
and lead the development of Gitea.
```
- 2023-01-01 ~ 2023-12-31 - https://blog.gitea.io/2023/02/gitea-quarterly-report-23q1/
- Company
- [Jason Song](https://gitea.com/wolfogre) <i@wolfogre.com>
- [Lunny Xiao](https://gitea.com/lunny) <xiaolunwen@gmail.com>
- [Matti Ranta](https://gitea.com/techknowlogick) <techknowlogick@gitea.io>
- Community
- [6543](https://gitea.com/6543) <6543@obermui.de>
- [Andrew Thornton](https://gitea.com/zeripath) <art27@cantab.net>
- [John Olheiser](https://gitea.com/jolheiser) <john.olheiser@gmail.com>
To honor the past owners, here's the history of the owners and the time
they served:
### Previous TOC/owners members
- 2022-01-01 ~ 2022-12-31 - https://github.com/go-gitea/gitea/issues/17872
- [Lunny Xiao](https://gitea.com/lunny) <xiaolunwen@gmail.com>
- [Matti Ranta](https://gitea.com/techknowlogick) <techknowlogick@gitea.io>
- [Andrew Thornton](https://gitea.com/zeripath) <art27@cantab.net>
Here's the history of the owners and the time they served:
- 2021-01-01 ~ 2021-12-31 - https://github.com/go-gitea/gitea/issues/13801
- [Lunny Xiao](https://gitea.com/lunny) <xiaolunwen@gmail.com>
- [Lauris Bukšis-Haberkorns](https://gitea.com/lafriks) <lauris@nix.lv>
- [Matti Ranta](https://gitea.com/techknowlogick) <techknowlogick@gitea.io>
- [Lunny Xiao](https://gitea.com/lunny) - 2016, 2017, [2018](https://github.com/go-gitea/gitea/issues/3255), [2019](https://github.com/go-gitea/gitea/issues/5572), [2020](https://github.com/go-gitea/gitea/issues/9230), [2021](https://github.com/go-gitea/gitea/issues/13801), [2022](https://github.com/go-gitea/gitea/issues/17872)
- [Kim Carlbäcker](https://github.com/bkcsoft) - 2016, 2017
- [Thomas Boerger](https://gitea.com/tboerger) - 2016, 2017
- [Lauris Bukšis-Haberkorns](https://gitea.com/lafriks) - [2018](https://github.com/go-gitea/gitea/issues/3255), [2019](https://github.com/go-gitea/gitea/issues/5572), [2020](https://github.com/go-gitea/gitea/issues/9230), [2021](https://github.com/go-gitea/gitea/issues/13801)
- [Matti Ranta](https://gitea.com/techknowlogick) - [2019](https://github.com/go-gitea/gitea/issues/5572), [2020](https://github.com/go-gitea/gitea/issues/9230), [2021](https://github.com/go-gitea/gitea/issues/13801), [2022](https://github.com/go-gitea/gitea/issues/17872)
- [Andrew Thornton](https://gitea.com/zeripath) - [2020](https://github.com/go-gitea/gitea/issues/9230), [2021](https://github.com/go-gitea/gitea/issues/13801), [2022](https://github.com/go-gitea/gitea/issues/17872)
- 2020-01-01 ~ 2020-12-31 - https://github.com/go-gitea/gitea/issues/9230
- [Lunny Xiao](https://gitea.com/lunny) <xiaolunwen@gmail.com>
- [Lauris Bukšis-Haberkorns](https://gitea.com/lafriks) <lauris@nix.lv>
- [Matti Ranta](https://gitea.com/techknowlogick) <techknowlogick@gitea.io>
## Governance Compensation
- 2019-01-01 ~ 2019-12-31 - https://github.com/go-gitea/gitea/issues/5572
- [Lunny Xiao](https://github.com/lunny) <xiaolunwen@gmail.com>
- [Lauris Bukšis-Haberkorns](https://github.com/lafriks) <lauris@nix.lv>
- [Matti Ranta](https://github.com/techknowlogick) <techknowlogick@gitea.io>
Each member of the community elected TOC will be granted $500 each month as compensation for their work.
- 2018-01-01 ~ 2018-12-31 - https://github.com/go-gitea/gitea/issues/3255
- [Lunny Xiao](https://github.com/lunny) <xiaolunwen@gmail.com>
- [Lauris Bukšis-Haberkorns](https://github.com/lafriks) <lauris@nix.lv>
- [Kim Carlbäcker](https://github.com/bkcsoft) <kim.carlbacker@gmail.com>
Furthermore, any community release manager for a specific release or LTS will be compensated $500 for the delivery of said release.
- 2016-11-04 ~ 2017-12-31
- [Lunny Xiao](https://github.com/lunny) <xiaolunwen@gmail.com>
- [Thomas Boerger](https://github.com/tboerger) <thomas@webhippie.de>
- [Kim Carlbäcker](https://github.com/bkcsoft) <kim.carlbacker@gmail.com>
These funds will come from community sources like the OpenCollective rather than directly from the company.
Only non-company members are eligible for this compensation, and if a member of the community TOC takes the responsibility of release manager, they would only be compensated for their TOC duties.
Gitea Ltd employees are not eligible to receive any funds from the OpenCollective unless it is reimbursement for a purchase made for the Gitea project itself.
## TOC & Working groups
With Gitea covering many projects outside of the main repository, several groups will be created to help focus on specific areas instead of requiring maintainers to be a jack-of-all-trades. Maintainers are of course more than welcome to be part of multiple groups should they wish to contribute in multiple places.
The currently proposed groups are:
- **Core Group**: maintain the primary Gitea repository
- **Integration Group**: maintain the Gitea ecosystem's related tools, including go-sdk/tea/changelog/bots etc.
- **Documentation Group**: maintain related documents and repositories
- **Translation Group**: coordinate with translators and maintain translations
- **Security Group**: managed by TOC directly, members are decided by TOC, maintains security patches/responsible for security items
## Roadmap
Each year a roadmap will be discussed with the entire Gitea maintainers team, and feedback will be solicited from various stakeholders.
TOC members need to review the roadmap every year and work together on the direction of the project.
When a vote is required for a proposal or other change, the vote of community elected TOC members count slightly more than the vote of company elected TOC members. With this approach, we both avoid ties and ensure that changes align with the mission statement and community opinion.
You can visit our roadmap on the wiki.
## Versions
Gitea has the `main` branch as a tip branch and has version branches
such as `release/v0.9`. `release/v0.9` is a release branch and we will
tag `v0.9.0` for binary download. If `v0.9.0` has bugs, we will accept
pull requests on the `release/v0.9` branch and publish a `v0.9.1` tag,
such as `release/v1.19`. `release/v1.19` is a release branch and we will
tag `v1.19.0` for binary download. If `v1.19.0` has bugs, we will accept
pull requests on the `release/v1.19` branch and publish a `v1.19.1` tag,
after bringing the bug fix also to the main branch.
Since the `main` branch is a tip version, if you wish to use Gitea
@ -427,17 +561,3 @@ be reviewed by two maintainers and must pass the automatic tests.
- bump the version of https://dl.gitea.io/gitea/version.json
- merge the blog post PR
- announce the release in discord `#announcements`
## Copyright
Code that you contribute should use the standard copyright header:
```
// Copyright <year> The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
```
Files in the repository contain copyright from the year they are added
to the year they are last changed. If the copyright author is changed,
just paste the header below the old one.

View File

@ -1,5 +1,5 @@
#Build stage
FROM docker.io/library/golang:1.20-alpine3.17 AS build-env
FROM docker.io/library/golang:1.20-alpine3.18 AS build-env
ARG GOPROXY
ENV GOPROXY ${GOPROXY:-direct}
@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \
# Begin env-to-ini build
RUN go build contrib/environment-to-ini/environment-to-ini.go
FROM docker.io/library/alpine:3.17
FROM docker.io/library/alpine:3.18
LABEL maintainer="maintainers@gitea.io"
EXPOSE 22 3000

View File

@ -1,5 +1,5 @@
#Build stage
FROM docker.io/library/golang:1.20-alpine3.17 AS build-env
FROM docker.io/library/golang:1.20-alpine3.18 AS build-env
ARG GOPROXY
ENV GOPROXY ${GOPROXY:-direct}
@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \
# Begin env-to-ini build
RUN go build contrib/environment-to-ini/environment-to-ini.go
FROM docker.io/library/alpine:3.17
FROM docker.io/library/alpine:3.18
LABEL maintainer="maintainers@gitea.io"
EXPOSE 2222 3000

View File

@ -41,7 +41,7 @@ Patrick Schratz <patrick.schratz@gmail.com> (@pat-s)
Janis Estelmann <admin@oldschoolhack.me> (@KN4CK3R)
Steven Kriegler <sk.bunsenbrenner@gmail.com> (@justusbunsi)
Jimmy Praet <jimmy.praet@telenet.be> (@jpraet)
Leon Hofmeister <dev.lh@web.de> (@delvh)
Leon Hofmeister <dev.lh@web.de> (@delvh)
Wim <wim@42.be> (@42wim)
Jason Song <i@wolfogre.com> (@wolfogre)
Yarden Shoham <git@yardenshoham.com> (@yardenshoham)
@ -49,3 +49,6 @@ Yu Tian <zettat123@gmail.com> (@Zettat123)
Eddie Yang <576951401@qq.com> (@yp05327)
Dong Ge <gedong_1994@163.com> (@sillyguodong)
Xinyi Gong <hestergong@gmail.com> (@HesterG)
wxiaoguang <wxiaoguang@gmail.com> (@wxiaoguang)
Gary Moon <gary@garymoon.net> (@garymoon)
Philip Peterson <philip.c.peterson@gmail.com> (@philip-peterson)

140
Makefile
View File

@ -25,17 +25,17 @@ COMMA := ,
XGO_VERSION := go-1.20.x
AIR_PACKAGE ?= github.com/cosmtrek/air@v1.40.4
EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.6.0
ERRCHECK_PACKAGE ?= github.com/kisielk/errcheck@v1.6.2
GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.4.0
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.2
GXZ_PAGAGE ?= github.com/ulikunitz/xz/cmd/gxz@v0.5.10
AIR_PACKAGE ?= github.com/cosmtrek/air@v1.43.0
EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.7.0
GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.5.0
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.52.2
GXZ_PAGAGE ?= github.com/ulikunitz/xz/cmd/gxz@v0.5.11
MISSPELL_PACKAGE ?= github.com/client9/misspell/cmd/misspell@v0.3.4
SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.4
XGO_PACKAGE ?= src.techknowlogick.com/xgo@latest
GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1.5.0
GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1.6.0
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@latest
ACTIONLINT_PACKAGE ?= github.com/rhysd/actionlint/cmd/actionlint@latest
DOCKER_IMAGE ?= gitea/gitea
DOCKER_TAG ?= latest
@ -97,6 +97,11 @@ else
endif
endif
# if version = "main" then update version to "nightly"
ifeq ($(VERSION),main)
VERSION := main-nightly
endif
LDFLAGS := $(LDFLAGS) -X "main.MakeVersion=$(MAKE_VERSION)" -X "main.Version=$(GITEA_VERSION)" -X "main.Tags=$(TAGS)"
LINUX_ARCHS ?= linux/amd64,linux/386,linux/arm-5,linux/arm-6,linux/arm64
@ -109,7 +114,7 @@ FOMANTIC_WORK_DIR := web_src/fomantic
WEBPACK_SOURCES := $(shell find web_src/js web_src/css -type f)
WEBPACK_CONFIGS := webpack.config.js
WEBPACK_DEST := public/js/index.js public/css/index.css
WEBPACK_DEST_ENTRIES := public/js public/css public/fonts public/img/webpack public/serviceworker.js
WEBPACK_DEST_ENTRIES := public/js public/css public/fonts public/img/webpack
BINDATA_DEST := modules/public/bindata.go modules/options/bindata.go modules/templates/bindata.go
BINDATA_HASH := $(addsuffix .hash,$(BINDATA_DEST))
@ -135,7 +140,7 @@ GO_DIRS := build cmd models modules routers services tests
WEB_DIRS := web_src/js web_src/css
GO_SOURCES := $(wildcard *.go)
GO_SOURCES += $(shell find $(GO_DIRS) -type f -name "*.go" -not -path modules/options/bindata.go -not -path modules/public/bindata.go -not -path modules/templates/bindata.go)
GO_SOURCES += $(shell find $(GO_DIRS) -type f -name "*.go" ! -path modules/options/bindata.go ! -path modules/public/bindata.go ! -path modules/templates/bindata.go)
GO_SOURCES += $(GENERATED_GO_DEST)
GO_SOURCES_NO_BINDATA := $(GO_SOURCES)
@ -194,9 +199,21 @@ help:
@echo " - deps-backend install backend dependencies"
@echo " - deps-tools install tool dependencies"
@echo " - lint lint everything"
@echo " - lint-fix lint everything and fix issues"
@echo " - lint-actions lint action workflow files"
@echo " - lint-frontend lint frontend files"
@echo " - lint-frontend-fix lint frontend files and fix issues"
@echo " - lint-backend lint backend files"
@echo " - lint-backend-fix lint backend files and fix issues"
@echo " - lint-go lint go files"
@echo " - lint-go-fix lint go files and fix issues"
@echo " - lint-go-vet lint go files with vet"
@echo " - lint-js lint js files"
@echo " - lint-js-fix lint js files and fix issues"
@echo " - lint-css lint css files"
@echo " - lint-css-fix lint css files and fix issues"
@echo " - lint-md lint markdown files"
@echo " - lint-swagger lint swagger files"
@echo " - checks run various consistency checks"
@echo " - checks-frontend check frontend files"
@echo " - checks-backend check backend files"
@ -214,9 +231,7 @@ help:
@echo " - generate-manpage generate manpage"
@echo " - generate-swagger generate the swagger spec from code comments"
@echo " - swagger-validate check if the swagger spec is valid"
@echo " - golangci-lint run golangci-lint linter"
@echo " - go-licenses regenerate go licenses"
@echo " - vet examines Go source code and reports suspicious constructs"
@echo " - tidy run go mod tidy"
@echo " - test[\#TestSpecificName] run unit test"
@echo " - test-sqlite[\#TestSpecificName] run integration test for sqlite"
@ -270,8 +285,12 @@ clean:
fmt:
GOFUMPT_PACKAGE=$(GOFUMPT_PACKAGE) $(GO) run build/code-batch-process.go gitea-fmt -w '{file-list}'
$(eval TEMPLATES := $(shell find templates -type f -name '*.tmpl'))
@# strip whitespace after '{{' and before `}}` unless there is only whitespace before it
@$(SED_INPLACE) -e 's/{{[ ]\{1,\}/{{/g' -e '/^[ ]\{1,\}}}/! s/[ ]\{1,\}}}/}}/g' $(TEMPLATES)
@# strip whitespace after '{{' or '(' and before '}}' or ')' unless there is only
@# whitespace before it
@$(SED_INPLACE) \
-e 's/{{[ ]\{1,\}/{{/g' -e '/^[ ]\{1,\}}}/! s/[ ]\{1,\}}}/}}/g' \
-e 's/([ ]\{1,\}/(/g' -e '/^[ ]\{1,\})/! s/[ ]\{1,\})/)/g' \
$(TEMPLATES)
.PHONY: fmt-check
fmt-check: fmt
@ -286,12 +305,6 @@ fmt-check: fmt
misspell-check:
go run $(MISSPELL_PACKAGE) -error $(GO_DIRS) $(WEB_DIRS)
.PHONY: vet
vet:
@echo "Running go vet..."
@GOOS= GOARCH= $(GO) build code.gitea.io/gitea-vet
@$(GO) vet -vettool=gitea-vet $(GO_PACKAGES)
.PHONY: $(TAGS_EVIDENCE)
$(TAGS_EVIDENCE):
@mkdir -p $(MAKE_EVIDENCE_DIR)
@ -324,11 +337,6 @@ swagger-validate:
$(GO) run $(SWAGGER_PACKAGE) validate './$(SWAGGER_SPEC)'
$(SED_INPLACE) '$(SWAGGER_SPEC_S_TMPL)' './$(SWAGGER_SPEC)'
.PHONY: errcheck
errcheck:
@echo "Running errcheck..."
$(GO) run $(ERRCHECK_PACKAGE) $(GO_PACKAGES)
.PHONY: checks
checks: checks-frontend checks-backend
@ -341,26 +349,81 @@ checks-backend: tidy-check swagger-check fmt-check misspell-check swagger-valida
.PHONY: lint
lint: lint-frontend lint-backend
.PHONY: lint-fix
lint-fix: lint-frontend-fix lint-backend-fix
.PHONY: lint-frontend
lint-frontend: node_modules lint-md
lint-frontend: lint-js lint-css lint-md lint-swagger
.PHONY: lint-frontend-fix
lint-frontend-fix: lint-js-fix lint-css-fix lint-md lint-swagger
.PHONY: lint-backend
lint-backend: lint-go lint-go-vet lint-editorconfig
.PHONY: lint-backend-fix
lint-backend-fix: lint-go-fix lint-go-vet lint-editorconfig
.PHONY: lint-js
lint-js: node_modules
npx eslint --color --max-warnings=0 --ext js,vue web_src/js build *.config.js docs/assets/js tests/e2e
npx stylelint --color --max-warnings=0 web_src/css
.PHONY: lint-js-fix
lint-js-fix: node_modules
npx eslint --color --max-warnings=0 --ext js,vue web_src/js build *.config.js docs/assets/js tests/e2e --fix
.PHONY: lint-css
lint-css: node_modules
npx stylelint --color --max-warnings=0 web_src/css web_src/js/components/*.vue
.PHONY: lint-css-fix
lint-css-fix: node_modules
npx stylelint --color --max-warnings=0 web_src/css web_src/js/components/*.vue --fix
.PHONY: lint-swagger
lint-swagger: node_modules
npx spectral lint -q -F hint $(SWAGGER_SPEC)
.PHONY: lint-md
lint-md: node_modules
npx markdownlint docs *.md
.PHONY: lint-backend
lint-backend: golangci-lint vet editorconfig-checker
.PHONY: lint-go
lint-go:
$(GO) run $(GOLANGCI_LINT_PACKAGE) run
.PHONY: lint-go-fix
lint-go-fix:
$(GO) run $(GOLANGCI_LINT_PACKAGE) run --fix
# workaround step for the lint-go-windows CI task because 'go run' can not
# have distinct GOOS/GOARCH for its build and run steps
.PHONY: lint-go-windows
lint-go-windows:
@GOOS= GOARCH= $(GO) install $(GOLANGCI_LINT_PACKAGE)
golangci-lint run
.PHONY: lint-go-vet
lint-go-vet:
@echo "Running go vet..."
@GOOS= GOARCH= $(GO) build code.gitea.io/gitea-vet
@$(GO) vet -vettool=gitea-vet $(GO_PACKAGES)
.PHONY: lint-editorconfig
lint-editorconfig:
$(GO) run $(EDITORCONFIG_CHECKER_PACKAGE) templates .github/workflows
.PHONY: lint-actions
lint-actions:
$(GO) run $(ACTIONLINT_PACKAGE)
.PHONY: watch
watch:
bash build/watch.sh
@bash build/watch.sh
.PHONY: watch-frontend
watch-frontend: node-check node_modules
rm -rf $(WEBPACK_DEST_ENTRIES)
@rm -rf $(WEBPACK_DEST_ENTRIES)
NODE_ENV=development npx webpack --watch --progress
.PHONY: watch-backend
@ -843,7 +906,6 @@ deps-backend:
deps-tools:
$(GO) install $(AIR_PACKAGE)
$(GO) install $(EDITORCONFIG_CHECKER_PACKAGE)
$(GO) install $(ERRCHECK_PACKAGE)
$(GO) install $(GOFUMPT_PACKAGE)
$(GO) install $(GOLANGCI_LINT_PACKAGE)
$(GO) install $(GXZ_PAGAGE)
@ -852,6 +914,7 @@ deps-tools:
$(GO) install $(XGO_PACKAGE)
$(GO) install $(GO_LICENSES_PACKAGE)
$(GO) install $(GOVULNCHECK_PACKAGE)
$(GO) install $(ACTIONLINT_PACKAGE)
node_modules: package-lock.json
npm install --no-save
@ -942,21 +1005,6 @@ generate-manpage:
@gzip -9 man/man1/gitea.1 && echo man/man1/gitea.1.gz created
@#TODO A small script that formats config-cheat-sheet.en-us.md nicely for use as a config man page
.PHONY: golangci-lint
golangci-lint:
$(GO) run $(GOLANGCI_LINT_PACKAGE) run
# workaround step for the lint-backend-windows CI task because 'go run' can not
# have distinct GOOS/GOARCH for its build and run steps
.PHONY: golangci-lint-windows
golangci-lint-windows:
@GOOS= GOARCH= $(GO) install $(GOLANGCI_LINT_PACKAGE)
golangci-lint run
.PHONY: editorconfig-checker
editorconfig-checker:
$(GO) run $(EDITORCONFIG_CHECKER_PACKAGE) templates
.PHONY: docker
docker:
docker build --disable-content-trust=false -t $(DOCKER_REF) .

View File

@ -110,7 +110,7 @@ Translations are done through Crowdin. If you want to translate to a new languag
You can also just create an issue for adding a language or ask on discord on the #translation channel. If you need context or find some translation issues, you can leave a comment on the string or ask on Discord. For general translation questions there is a section in the docs. Currently a bit empty but we hope to fill it as questions pop up.
https://docs.gitea.io/en-us/translation-guidelines/
https://docs.gitea.io/en-us/contributing/translation-guidelines/
[![Crowdin](https://badges.crowdin.net/gitea/localized.svg)](https://crowdin.com/project/gitea)

File diff suppressed because one or more lines are too long

View File

@ -12,7 +12,7 @@ import (
"path/filepath"
"strings"
"gopkg.in/ini.v1"
"code.gitea.io/gitea/modules/setting"
)
func main() {
@ -22,14 +22,13 @@ func main() {
os.Exit(1)
}
ini.PrettyFormat = false
mustNoErr := func(err error) {
if err != nil {
panic(err)
}
}
collectInis := func(ref string) map[string]*ini.File {
inis := map[string]*ini.File{}
collectInis := func(ref string) map[string]setting.ConfigProvider {
inis := map[string]setting.ConfigProvider{}
err := filepath.WalkDir("options/locale", func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
@ -37,10 +36,7 @@ func main() {
if d.IsDir() || !strings.HasSuffix(d.Name(), ".ini") {
return nil
}
cfg, err := ini.LoadSources(ini.LoadOptions{
IgnoreInlineComment: true,
UnescapeValueCommentSymbols: true,
}, path)
cfg, err := setting.NewConfigProviderForLocale(path)
mustNoErr(err)
inis[path] = cfg
fmt.Printf("collecting: %s @ %s\n", path, ref)

View File

@ -35,12 +35,40 @@ func main() {
base, out := os.Args[1], os.Args[2]
// Add ext for excluded files because license_test.go will be included for some reason.
// And there are more files that should be excluded, check with:
//
// go run github.com/google/go-licenses@v1.6.0 save . --force --save_path=.go-licenses 2>/dev/null
// find .go-licenses -type f | while read FILE; do echo "${$(basename $FILE)##*.}"; done | sort -u
// AUTHORS
// COPYING
// LICENSE
// Makefile
// NOTICE
// gitignore
// go
// md
// mod
// sum
// toml
// txt
// yml
//
// It could be removed once we have a better regex.
excludedExt := map[string]bool{
".gitignore": true,
".go": true,
".mod": true,
".sum": true,
".toml": true,
".yml": true,
}
var paths []string
err := filepath.WalkDir(base, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() || !licenseRe.MatchString(entry.Name()) {
if entry.IsDir() || !licenseRe.MatchString(entry.Name()) || excludedExt[filepath.Ext(entry.Name())] {
return nil
}
paths = append(paths, path)
@ -82,6 +110,11 @@ func main() {
panic(err)
}
// Ensure file has a final newline
if jsonBytes[len(jsonBytes)-1] != '\n' {
jsonBytes = append(jsonBytes, '\n')
}
err = os.WriteFile(out, jsonBytes, 0o644)
if err != nil {
panic(err)

View File

@ -1,8 +1,8 @@
#!/bin/bash
set -euo pipefail
make watch-frontend &
make watch-backend &
make --no-print-directory watch-frontend &
make --no-print-directory watch-backend &
trap 'kill $(jobs -p)' EXIT
wait

View File

@ -42,8 +42,7 @@ func runGenerateActionsRunnerToken(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
scope := c.String("scope")

View File

@ -9,6 +9,7 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"strings"
@ -57,10 +58,9 @@ func confirm() (bool, error) {
}
func initDB(ctx context.Context) error {
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
setting.LoadDBSetting()
setting.InitSQLLog(false)
setting.InitSQLLoggersForCli(log.INFO)
if setting.Database.Type == "" {
log.Fatal(`Database settings are missing from the configuration file: %q.
@ -94,3 +94,17 @@ func installSignals() (context.Context, context.CancelFunc) {
return ctx, cancel
}
func setupConsoleLogger(level log.Level, colorize bool, out io.Writer) {
if out != os.Stdout && out != os.Stderr {
panic("setupConsoleLogger can only be used with os.Stdout or os.Stderr")
}
writeMode := log.WriterMode{
Level: level,
Colorize: colorize,
WriterOption: log.WriterConsoleOption{Stderr: out == os.Stderr},
}
writer := log.NewEventWriterConsole("console-default", writeMode)
log.GetManager().GetLogger(log.DEFAULT).RemoveAllWriters().AddWriters(writer)
}

View File

@ -4,10 +4,10 @@
package cmd
import (
"errors"
"fmt"
golog "log"
"os"
"path/filepath"
"strings"
"text/tabwriter"
@ -82,24 +82,25 @@ You should back-up your database before doing this and ensure that your database
}
func runRecreateTable(ctx *cli.Context) error {
// Redirect the default golog to here
golog.SetFlags(0)
golog.SetPrefix("")
golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.LoadDBSetting()
setting.Log.EnableXORMLog = ctx.Bool("debug")
setting.Database.LogSQL = ctx.Bool("debug")
// FIXME: don't use CfgProvider directly
setting.CfgProvider.Section("log").Key("XORM").SetValue(",")
setting.InitSQLLog(!ctx.Bool("debug"))
stdCtx, cancel := installSignals()
defer cancel()
// Redirect the default golog to here
golog.SetFlags(0)
golog.SetPrefix("")
golog.SetOutput(log.LoggerToWriter(log.GetLogger(log.DEFAULT).Info))
debug := ctx.Bool("debug")
setting.Init(&setting.Options{})
setting.LoadDBSetting()
if debug {
setting.InitSQLLoggersForCli(log.DEBUG)
} else {
setting.InitSQLLoggersForCli(log.INFO)
}
setting.Database.LogSQL = debug
if err := db.InitEngine(stdCtx); err != nil {
fmt.Println(err)
fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
@ -126,44 +127,31 @@ func runRecreateTable(ctx *cli.Context) error {
})
}
func setDoctorLogger(ctx *cli.Context) {
func setupDoctorDefaultLogger(ctx *cli.Context, colorize bool) {
// Silence the default loggers
setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)
logFile := ctx.String("log-file")
if !ctx.IsSet("log-file") {
logFile = "doctor.log"
}
colorize := log.CanColorStdout
if ctx.IsSet("color") {
colorize = ctx.Bool("color")
}
if len(logFile) == 0 {
log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
// if no doctor log-file is set, do not show any log from default logger
return
}
defer func() {
recovered := recover()
if recovered == nil {
if logFile == "-" {
setupConsoleLogger(log.TRACE, colorize, os.Stdout)
} else {
logFile, _ = filepath.Abs(logFile)
writeMode := log.WriterMode{Level: log.TRACE, WriterOption: log.WriterFileOption{FileName: logFile}}
writer, err := log.NewEventWriter("console-to-file", "file", writeMode)
if err != nil {
log.FallbackErrorf("unable to create file log writer: %v", err)
return
}
err, ok := recovered.(error)
if !ok {
panic(recovered)
}
if errors.Is(err, os.ErrPermission) {
fmt.Fprintf(os.Stderr, "ERROR: Unable to write logs to provided file due to permissions error: %s\n %v\n", logFile, err)
} else {
fmt.Fprintf(os.Stderr, "ERROR: Unable to write logs to provided file: %s\n %v\n", logFile, err)
}
fmt.Fprintf(os.Stderr, "WARN: Logging will be disabled\n Use `--log-file` to configure log file location\n")
log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"NONE","stacktracelevel":"NONE","colorize":%t}`, colorize))
}()
if logFile == "-" {
log.NewLogger(1000, "doctor", "console", fmt.Sprintf(`{"level":"trace","stacktracelevel":"NONE","colorize":%t}`, colorize))
} else {
log.NewLogger(1000, "doctor", "file", fmt.Sprintf(`{"filename":%q,"level":"trace","stacktracelevel":"NONE"}`, logFile))
log.GetManager().GetLogger(log.DEFAULT).RemoveAllWriters().AddWriters(writer)
}
}
@ -171,22 +159,17 @@ func runDoctor(ctx *cli.Context) error {
stdCtx, cancel := installSignals()
defer cancel()
// Silence the default loggers
log.DelNamedLogger("console")
log.DelNamedLogger(log.DEFAULT)
// Now setup our own
setDoctorLogger(ctx)
colorize := log.CanColorStdout
if ctx.IsSet("color") {
colorize = ctx.Bool("color")
}
// Finally redirect the default golog to here
setupDoctorDefaultLogger(ctx, colorize)
// Finally redirect the default golang's log to here
golog.SetFlags(0)
golog.SetPrefix("")
golog.SetOutput(log.NewLoggerAsWriter("INFO", log.GetLogger(log.DEFAULT)))
golog.SetOutput(log.LoggerToWriter(log.GetLogger(log.DEFAULT).Info))
if ctx.IsSet("list") {
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
@ -234,17 +217,5 @@ func runDoctor(ctx *cli.Context) error {
}
}
// Now we can set up our own logger to return information about what the doctor is doing
if err := log.NewNamedLogger("doctorouter",
0,
"console",
"console",
fmt.Sprintf(`{"level":"INFO","stacktracelevel":"NONE","colorize":%t,"flags":-1}`, colorize)); err != nil {
fmt.Println(err)
return err
}
logger := log.GetLogger("doctorouter")
defer logger.Close()
return doctor.RunChecks(stdCtx, logger, ctx.Bool("fix"), checks)
return doctor.RunChecks(stdCtx, colorize, ctx.Bool("fix"), checks)
}

View File

@ -172,10 +172,7 @@ func runDump(ctx *cli.Context) error {
outType := ctx.String("type")
if fileName == "-" {
file = os.Stdout
err := log.DelLogger("console")
if err != nil {
fatal("Deleting default logger failed. Can not write to stdout: %v", err)
}
setupConsoleLogger(log.FATAL, log.CanColorStderr, os.Stderr)
} else {
for _, suffix := range outputTypeEnum.Enum {
if strings.HasSuffix(fileName, "."+suffix) {
@ -185,8 +182,7 @@ func runDump(ctx *cli.Context) error {
}
fileName += "." + outType
}
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
// make sure we are logging to the console no matter what the configuration tells us do to
// FIXME: don't use CfgProvider directly

View File

@ -97,17 +97,12 @@ type assetFile struct {
}
func initEmbeddedExtractor(c *cli.Context) error {
// FIXME: there is a bug, if the user runs `gitea embedded` with a different user or root,
// The setting.Init (loadRunModeFrom) will fail and do log.Fatal
// But the console logger has been deleted, so nothing is printed, the user sees nothing and Gitea just exits.
// Silence the console logger
log.DelNamedLogger("console")
log.DelNamedLogger(log.DEFAULT)
setupConsoleLogger(log.ERROR, log.CanColorStderr, os.Stderr)
// Read configuration file
setting.InitProviderAllowEmpty()
setting.LoadCommonSettings()
setting.Init(&setting.Options{
AllowEmpty: true,
})
patterns, err := compileCollectPatterns(c.Args())
if err != nil {

View File

@ -18,7 +18,6 @@ import (
"code.gitea.io/gitea/modules/private"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"github.com/urfave/cli"
)
@ -141,7 +140,7 @@ func (d *delayWriter) Close() error {
if d == nil {
return nil
}
stopped := util.StopTimer(d.timer)
stopped := d.timer.Stop()
if stopped || d.buf == nil {
return nil
}
@ -202,7 +201,7 @@ Gitea or set your environment appropriately.`, "")
oldCommitIDs := make([]string, hookBatchSize)
newCommitIDs := make([]string, hookBatchSize)
refFullNames := make([]string, hookBatchSize)
refFullNames := make([]git.RefName, hookBatchSize)
count := 0
total := 0
lastline := 0
@ -237,14 +236,14 @@ Gitea or set your environment appropriately.`, "")
oldCommitID := string(fields[0])
newCommitID := string(fields[1])
refFullName := string(fields[2])
refFullName := git.RefName(fields[2])
total++
lastline++
// If the ref is a branch or tag, check if it's protected
// if supportProcReceive all ref should be checked because
// permission check was delayed
if supportProcReceive || strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
if supportProcReceive || refFullName.IsBranch() || refFullName.IsTag() {
oldCommitIDs[count] = oldCommitID
newCommitIDs[count] = newCommitID
refFullNames[count] = refFullName
@ -352,7 +351,7 @@ Gitea or set your environment appropriately.`, "")
}
oldCommitIDs := make([]string, hookBatchSize)
newCommitIDs := make([]string, hookBatchSize)
refFullNames := make([]string, hookBatchSize)
refFullNames := make([]git.RefName, hookBatchSize)
count := 0
total := 0
wasEmpty := false
@ -374,7 +373,7 @@ Gitea or set your environment appropriately.`, "")
fmt.Fprintf(out, ".")
oldCommitIDs[count] = string(fields[0])
newCommitIDs[count] = string(fields[1])
refFullNames[count] = string(fields[2])
refFullNames[count] = git.RefName(fields[2])
if refFullNames[count] == git.BranchPrefix+"master" && newCommitIDs[count] != git.EmptySHA && count == total {
masterPushed = true
}
@ -576,7 +575,7 @@ Gitea or set your environment appropriately.`, "")
}
hookOptions.OldCommitIDs = make([]string, 0, hookBatchSize)
hookOptions.NewCommitIDs = make([]string, 0, hookBatchSize)
hookOptions.RefFullNames = make([]string, 0, hookBatchSize)
hookOptions.RefFullNames = make([]git.RefName, 0, hookBatchSize)
for {
// note: pktLineTypeUnknow means pktLineTypeFlush and pktLineTypeData all allowed
@ -594,7 +593,7 @@ Gitea or set your environment appropriately.`, "")
}
hookOptions.OldCommitIDs = append(hookOptions.OldCommitIDs, t[0])
hookOptions.NewCommitIDs = append(hookOptions.NewCommitIDs, t[1])
hookOptions.RefFullNames = append(hookOptions.RefFullNames, t[2])
hookOptions.RefFullNames = append(hookOptions.RefFullNames, git.RefName(t[2]))
}
hookOptions.GitPushOptions = make(map[string]string)
@ -641,7 +640,7 @@ Gitea or set your environment appropriately.`, "")
for _, rs := range resp.Results {
if len(rs.Err) > 0 {
err = writeDataPktLine(ctx, os.Stdout, []byte("ng "+rs.OriginalRef+" "+rs.Err))
err = writeDataPktLine(ctx, os.Stdout, []byte("ng "+rs.OriginalRef.String()+" "+rs.Err))
if err != nil {
return err
}
@ -649,7 +648,7 @@ Gitea or set your environment appropriately.`, "")
}
if rs.IsNotMatched {
err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef))
err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef.String()))
if err != nil {
return err
}

View File

@ -16,8 +16,7 @@ func runSendMail(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
if err := argsSet(c, "title"); err != nil {
return err

View File

@ -7,14 +7,8 @@ import (
"testing"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
)
func init() {
setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAndLoadCommonSettingsForTest()
}
func TestMain(m *testing.M) {
unittest.MainTest(m, &unittest.TestOptions{
GiteaRootPath: "..",

View File

@ -21,6 +21,7 @@ var (
Subcommands: []cli.Command{
subcmdShutdown,
subcmdRestart,
subcmdReloadTemplates,
subcmdFlushQueues,
subcmdLogging,
subCmdProcesses,
@ -46,6 +47,16 @@ var (
},
Action: runRestart,
}
subcmdReloadTemplates = cli.Command{
Name: "reload-templates",
Usage: "Reload template files in the running process",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "debug",
},
},
Action: runReloadTemplates,
}
subcmdFlushQueues = cli.Command{
Name: "flush-queues",
Usage: "Flush queues in the running process",
@ -115,6 +126,15 @@ func runRestart(c *cli.Context) error {
return handleCliResponseExtra(extra)
}
func runReloadTemplates(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
extra := private.ReloadTemplates(ctx)
return handleCliResponseExtra(extra)
}
func runFlushQueues(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()

View File

@ -16,13 +16,13 @@ import (
var (
defaultLoggingFlags = []cli.Flag{
cli.StringFlag{
Name: "group, g",
Usage: "Group to add logger to - will default to \"default\"",
Name: "logger",
Usage: `Logger name - will default to "default"`,
}, cli.StringFlag{
Name: "name, n",
Usage: "Name of the new logger - will default to mode",
Name: "writer",
Usage: "Name of the log writer - will default to mode",
}, cli.StringFlag{
Name: "level, l",
Name: "level",
Usage: "Logging level for the new logger",
}, cli.StringFlag{
Name: "stacktrace-level, L",
@ -83,8 +83,8 @@ var (
cli.BoolFlag{
Name: "debug",
}, cli.StringFlag{
Name: "group, g",
Usage: "Group to add logger to - will default to \"default\"",
Name: "logger",
Usage: `Logger name - will default to "default"`,
},
},
Action: runRemoveLogger,
@ -93,15 +93,6 @@ var (
Usage: "Add a logger",
Subcommands: []cli.Command{
{
Name: "console",
Usage: "Add a console logger",
Flags: append(defaultLoggingFlags,
cli.BoolFlag{
Name: "stderr",
Usage: "Output console logs to stderr - only relevant for console",
}),
Action: runAddConsoleLogger,
}, {
Name: "file",
Usage: "Add a file logger",
Flags: append(defaultLoggingFlags, []cli.Flag{
@ -148,28 +139,6 @@ var (
},
}...),
Action: runAddConnLogger,
}, {
Name: "smtp",
Usage: "Add an SMTP logger",
Flags: append(defaultLoggingFlags, []cli.Flag{
cli.StringFlag{
Name: "username, u",
Usage: "Mail server username",
}, cli.StringFlag{
Name: "password, P",
Usage: "Mail server password",
}, cli.StringFlag{
Name: "host, H",
Usage: "Mail server host (defaults to: 127.0.0.1:25)",
}, cli.StringSliceFlag{
Name: "send-to, s",
Usage: "Email address(es) to send to",
}, cli.StringFlag{
Name: "subject, S",
Usage: "Subject header of sent emails",
},
}...),
Action: runAddSMTPLogger,
},
},
}, {
@ -194,50 +163,16 @@ func runRemoveLogger(c *cli.Context) error {
defer cancel()
setup(ctx, c.Bool("debug"))
group := c.String("group")
if len(group) == 0 {
group = log.DEFAULT
logger := c.String("logger")
if len(logger) == 0 {
logger = log.DEFAULT
}
name := c.Args().First()
writer := c.Args().First()
extra := private.RemoveLogger(ctx, group, name)
extra := private.RemoveLogger(ctx, logger, writer)
return handleCliResponseExtra(extra)
}
func runAddSMTPLogger(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
mode := "smtp"
if c.IsSet("host") {
vals["host"] = c.String("host")
} else {
vals["host"] = "127.0.0.1:25"
}
if c.IsSet("username") {
vals["username"] = c.String("username")
}
if c.IsSet("password") {
vals["password"] = c.String("password")
}
if !c.IsSet("send-to") {
return fmt.Errorf("Some recipients must be provided")
}
vals["sendTos"] = c.StringSlice("send-to")
if c.IsSet("subject") {
vals["subject"] = c.String("subject")
} else {
vals["subject"] = "Diagnostic message from Gitea"
}
return commonAddLogger(c, mode, vals)
}
func runAddConnLogger(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
@ -301,25 +236,12 @@ func runAddFileLogger(c *cli.Context) error {
return commonAddLogger(c, mode, vals)
}
func runAddConsoleLogger(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
mode := "console"
if c.IsSet("stderr") && c.Bool("stderr") {
vals["stderr"] = c.Bool("stderr")
}
return commonAddLogger(c, mode, vals)
}
func commonAddLogger(c *cli.Context, mode string, vals map[string]interface{}) error {
if len(c.String("level")) > 0 {
vals["level"] = log.FromString(c.String("level")).String()
vals["level"] = log.LevelFromString(c.String("level")).String()
}
if len(c.String("stacktrace-level")) > 0 {
vals["stacktraceLevel"] = log.FromString(c.String("stacktrace-level")).String()
vals["stacktraceLevel"] = log.LevelFromString(c.String("stacktrace-level")).String()
}
if len(c.String("expression")) > 0 {
vals["expression"] = c.String("expression")
@ -333,18 +255,18 @@ func commonAddLogger(c *cli.Context, mode string, vals map[string]interface{}) e
if c.IsSet("color") {
vals["colorize"] = c.Bool("color")
}
group := "default"
if c.IsSet("group") {
group = c.String("group")
logger := log.DEFAULT
if c.IsSet("logger") {
logger = c.String("logger")
}
name := mode
if c.IsSet("name") {
name = c.String("name")
writer := mode
if c.IsSet("writer") {
writer = c.String("writer")
}
ctx, cancel := installSignals()
defer cancel()
extra := private.AddLogger(ctx, group, name, mode, vals)
extra := private.AddLogger(ctx, logger, writer, mode, vals)
return handleCliResponseExtra(extra)
}

View File

@ -8,6 +8,7 @@ import (
"fmt"
"strings"
actions_model "code.gitea.io/gitea/models/actions"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git"
"code.gitea.io/gitea/models/migrations"
@ -32,7 +33,7 @@ var CmdMigrateStorage = cli.Command{
cli.StringFlag{
Name: "type, t",
Value: "",
Usage: "Type of stored files to copy. Allowed types: 'attachments', 'lfs', 'avatars', 'repo-avatars', 'repo-archivers', 'packages'",
Usage: "Type of stored files to copy. Allowed types: 'attachments', 'lfs', 'avatars', 'repo-avatars', 'repo-archivers', 'packages', 'actions-log'",
},
cli.StringFlag{
Name: "storage, s",
@ -134,6 +135,22 @@ func migratePackages(ctx context.Context, dstStorage storage.ObjectStorage) erro
})
}
func migrateActionsLog(ctx context.Context, dstStorage storage.ObjectStorage) error {
return db.Iterate(ctx, nil, func(ctx context.Context, task *actions_model.ActionTask) error {
if task.LogExpired {
// the log has been cleared
return nil
}
if !task.LogInStorage {
// running tasks store logs in DBFS
return nil
}
p := task.LogFilename
_, err := storage.Copy(dstStorage, p, storage.Actions, p)
return err
})
}
func runMigrateStorage(ctx *cli.Context) error {
stdCtx, cancel := installSignals()
defer cancel()
@ -201,6 +218,7 @@ func runMigrateStorage(ctx *cli.Context) error {
"repo-avatars": migrateRepoAvatars,
"repo-archivers": migrateRepoArchivers,
"packages": migratePackages,
"actions-log": migrateActionsLog,
}
tp := strings.ToLower(ctx.String("type"))

View File

@ -25,7 +25,7 @@ func TestMigratePackages(t *testing.T) {
creator := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
content := "package main\n\nfunc main() {\nfmt.Println(\"hi\")\n}\n"
buf, err := packages_module.CreateHashedBufferFromReader(strings.NewReader(content), 1024)
buf, err := packages_module.CreateHashedBufferFromReaderWithSize(strings.NewReader(content), 1024)
assert.NoError(t, err)
defer buf.Close()
@ -67,7 +67,7 @@ func TestMigratePackages(t *testing.T) {
entries, err := os.ReadDir(p)
assert.NoError(t, err)
assert.EqualValues(t, 2, len(entries))
assert.Len(t, entries, 2)
assert.EqualValues(t, "01", entries[0].Name())
assert.EqualValues(t, "tmp", entries[1].Name())
}

View File

@ -51,8 +51,7 @@ func runRestoreRepository(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
var units []string
if s := c.String("units"); s != "" {
units = strings.Split(s, ",")

View File

@ -56,14 +56,12 @@ var CmdServ = cli.Command{
}
func setup(ctx context.Context, debug bool) {
_ = log.DelLogger("console")
if debug {
_ = log.NewLogger(1000, "console", "console", `{"level":"trace","stacktracelevel":"NONE","stderr":true}`)
setupConsoleLogger(log.TRACE, false, os.Stderr)
} else {
_ = log.NewLogger(1000, "console", "console", `{"level":"fatal","stacktracelevel":"NONE","stderr":true}`)
setupConsoleLogger(log.FATAL, false, os.Stderr)
}
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
if debug {
setting.RunMode = "dev"
}

View File

@ -24,7 +24,6 @@ import (
"github.com/felixge/fgprof"
"github.com/urfave/cli"
ini "gopkg.in/ini.v1"
)
// PIDFile could be set from build tag
@ -104,11 +103,9 @@ func createPIDFile(pidPath string) {
func runWeb(ctx *cli.Context) error {
if ctx.Bool("verbose") {
_ = log.DelLogger("console")
log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "trace", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
setupConsoleLogger(log.TRACE, log.CanColorStdout, os.Stdout)
} else if ctx.Bool("quiet") {
_ = log.DelLogger("console")
log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "fatal", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
setupConsoleLogger(log.FATAL, log.CanColorStdout, os.Stdout)
}
defer func() {
if panicked := recover(); panicked != nil {
@ -145,10 +142,8 @@ func runWeb(ctx *cli.Context) error {
return err
}
}
installCtx, cancel := context.WithCancel(graceful.GetManager().HammerContext())
c := install.Routes(installCtx)
c := install.Routes()
err := listen(c, false)
cancel()
if err != nil {
log.Critical("Unable to open listener for installer. Is Gitea already running?")
graceful.GetManager().DoGracefulShutdown()
@ -157,7 +152,7 @@ func runWeb(ctx *cli.Context) error {
case <-graceful.GetManager().IsShutdown():
<-graceful.GetManager().Done()
log.Info("PID: %d Gitea Web Finished", os.Getpid())
log.Close()
log.GetManager().Close()
return err
default:
}
@ -178,8 +173,7 @@ func runWeb(ctx *cli.Context) error {
log.Info("Global init")
// Perform global initialization
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
setting.Init(&setting.Options{})
routers.GlobalInitInstalled(graceful.GetManager().HammerContext())
// We check that AppDataPath exists here (it should have been created during installation)
@ -201,7 +195,7 @@ func runWeb(ctx *cli.Context) error {
err := listen(c, true)
<-graceful.GetManager().Done()
log.Info("PID: %d Gitea Web Finished", os.Getpid())
log.Close()
log.GetManager().Close()
return err
}
@ -223,9 +217,10 @@ func setPort(port string) error {
defaultLocalURL += ":" + setting.HTTPPort + "/"
// Save LOCAL_ROOT_URL if port changed
setting.CreateOrAppendToCustomConf("server.LOCAL_ROOT_URL", func(cfg *ini.File) {
cfg.Section("server").Key("LOCAL_ROOT_URL").SetValue(defaultLocalURL)
})
setting.CfgProvider.Section("server").Key("LOCAL_ROOT_URL").SetValue(defaultLocalURL)
if err := setting.CfgProvider.Save(); err != nil {
return fmt.Errorf("Failed to save config file: %v", err)
}
}
return nil
}

View File

@ -1,6 +1,7 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//nolint:forbidigo
package main
import (
@ -16,7 +17,7 @@ import (
"strings"
"syscall"
"github.com/google/go-github/v51/github"
"github.com/google/go-github/v52/github"
"github.com/urfave/cli"
"gopkg.in/yaml.v3"
)

View File

@ -5,16 +5,12 @@ package main
import (
"os"
"regexp"
"strconv"
"strings"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"github.com/urfave/cli"
ini "gopkg.in/ini.v1"
)
// EnvironmentPrefix environment variables prefixed with this represent ini values to write
@ -32,6 +28,10 @@ func main() {
will be mapped to the ini section "[section_name]" and the key
"KEY_NAME" with the value as provided.
Environment variables of the form "GITEA__SECTION_NAME__KEY_NAME__FILE"
will be mapped to the ini section "[section_name]" and the key
"KEY_NAME" with the value loaded from the specified file.
Environment variables are usually restricted to a reduced character
set "0-9A-Z_" - in order to allow the setting of sections with
characters outside of that set, they should be escaped as following:
@ -95,61 +95,16 @@ func runEnvironmentToIni(c *cli.Context) error {
providedWorkPath := c.String("work-path")
setting.SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath)
cfg := ini.Empty()
isFile, err := util.IsFile(setting.CustomConf)
cfg, err := setting.NewConfigProviderFromFile(&setting.Options{CustomConf: setting.CustomConf, AllowEmpty: true})
if err != nil {
log.Fatal("Unable to check if %s is a file. Error: %v", setting.CustomConf, err)
log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
}
if isFile {
if err := cfg.Append(setting.CustomConf); err != nil {
log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
}
} else {
log.Warn("Custom config '%s' not found, ignore this if you're running first time", setting.CustomConf)
}
cfg.NameMapper = ini.SnackCase
changed := false
prefixGitea := c.String("prefix") + "__"
suffixFile := "__FILE"
changed := setting.EnvironmentToConfig(cfg, prefixGitea, suffixFile, os.Environ())
prefix := c.String("prefix") + "__"
for _, kv := range os.Environ() {
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
}
section, err := cfg.GetSection(sectionName)
if err != nil {
section, err = cfg.NewSection(sectionName)
if err != nil {
log.Error("Error creating section: %s : %v", sectionName, err)
continue
}
}
key := section.Key(keyName)
if key == nil {
key, err = section.NewKey(keyName, value)
if err != nil {
log.Error("Error creating key: %s in section: %s with value: %s : %v", keyName, sectionName, value, err)
continue
}
}
oldValue := key.Value()
if !changed && oldValue != value {
changed = true
}
key.SetValue(value)
}
// try to save the config file
destination := c.String("out")
if len(destination) == 0 {
destination = setting.CustomConf
@ -161,6 +116,8 @@ func runEnvironmentToIni(c *cli.Context) error {
return err
}
}
// clear Gitea's specific environment variables if requested
if c.Bool("clear") {
for _, kv := range os.Environ() {
idx := strings.IndexByte(kv, '=')
@ -168,69 +125,11 @@ func runEnvironmentToIni(c *cli.Context) error {
continue
}
eKey := kv[:idx]
if strings.HasPrefix(eKey, prefix) {
if strings.HasPrefix(eKey, prefixGitea) {
_ = os.Unsetenv(eKey)
}
}
}
return nil
}
const escapeRegexpString = "_0[xX](([0-9a-fA-F][0-9a-fA-F])+)_"
var escapeRegex = regexp.MustCompile(escapeRegexpString)
// DecodeSectionKey will decode a portable string encoded Section__Key pair
// Portable strings are considered to be of the form [A-Z0-9_]*
// We will encode a disallowed value as the UTF8 byte string preceded by _0X and
// followed by _. E.g. _0X2C_ for a '-' and _0X2E_ for '.'
// Section and Key are separated by a plain '__'.
// The entire section can be encoded as a UTF8 byte string
func DecodeSectionKey(encoded string) (string, string) {
section := ""
key := ""
inKey := false
last := 0
escapeStringIndices := escapeRegex.FindAllStringIndex(encoded, -1)
for _, unescapeIdx := range escapeStringIndices {
preceding := encoded[last:unescapeIdx[0]]
if !inKey {
if splitter := strings.Index(preceding, "__"); splitter > -1 {
section += preceding[:splitter]
inKey = true
key += preceding[splitter+2:]
} else {
section += preceding
}
} else {
key += preceding
}
toDecode := encoded[unescapeIdx[0]+3 : unescapeIdx[1]-1]
decodedBytes := make([]byte, len(toDecode)/2)
for i := 0; i < len(toDecode)/2; i++ {
// Can ignore error here as we know these should be hexadecimal from the regexp
byteInt, _ := strconv.ParseInt(toDecode[2*i:2*i+2], 16, 0)
decodedBytes[i] = byte(byteInt)
}
if inKey {
key += string(decodedBytes)
} else {
section += string(decodedBytes)
}
last = unescapeIdx[1]
}
remaining := encoded[last:]
if !inKey {
if splitter := strings.Index(remaining, "__"); splitter > -1 {
section += remaining[:splitter]
key += remaining[splitter+2:]
} else {
section += remaining
}
} else {
key += remaining
}
section = strings.ToLower(section)
return section, key
}

View File

@ -1,6 +1,7 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//nolint:forbidigo
package main
import (

View File

@ -52,7 +52,7 @@ After=network.target
# Uncomment the next line if you have repos with lots of files and get a HTTP 500 error because of that
# LimitNOFILE=524288:524288
RestartSec=2s
Type=simple
Type=notify
User=git
Group=git
WorkingDirectory=/var/lib/gitea/
@ -62,6 +62,7 @@ WorkingDirectory=/var/lib/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/gitea
WatchdogSec=30s
# 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

View File

@ -1,6 +1,6 @@
#!/usr/bin/env bash
# This is an update script for gitea installed via the binary distribution
# from dl.gitea.io on linux as systemd service. It performs a backup and updates
# from dl.gitea.com on linux as systemd service. It performs a backup and updates
# Gitea in place.
# NOTE: This adds the GPG Signing Key of the Gitea maintainers to the keyring.
# Depends on: bash, curl, xz, sha256sum. optionally jq, gpg
@ -10,6 +10,15 @@
# upgrade.sh 1.15.10
# giteahome=/opt/gitea giteaconf=$giteahome/app.ini upgrade.sh
# Check if gitea service is running
if ! pidof gitea &> /dev/null; then
echo "Error: gitea is not running."
exit 1
fi
# Continue with rest of the script if gitea is running
echo "Gitea is running. Continuing with rest of script..."
# apply variables from environment
: "${giteabin:="/usr/local/bin/gitea"}"
: "${giteahome:="/var/lib/gitea"}"
@ -69,7 +78,7 @@ require curl xz sha256sum "$sudocmd"
# select version to install
if [[ -z "${giteaversion:-}" ]]; then
require jq
giteaversion=$(curl --connect-timeout 10 -sL https://dl.gitea.io/gitea/version.json | jq -r .latest.version)
giteaversion=$(curl --connect-timeout 10 -sL https://dl.gitea.com/gitea/version.json | jq -r .latest.version)
echo "Latest available version is $giteaversion"
fi
@ -91,7 +100,7 @@ cd "$giteahome" # needed for gitea dump later
# download new binary
binname="gitea-${giteaversion}-${arch}"
binurl="https://dl.gitea.io/gitea/${giteaversion}/${binname}.xz"
binurl="https://dl.gitea.com/gitea/${giteaversion}/${binname}.xz"
echo "Downloading $binurl..."
curl --connect-timeout 10 --silent --show-error --fail --location -O "$binurl{,.sha256,.asc}"

View File

@ -49,8 +49,9 @@ APP_NAME = ; Gitea: Git with a cup of tea
;; RUN_USER will automatically detect the current user - but you can set it here change it if you run locally
RUN_USER = ; git
;;
;; Application run mode, affects performance and debugging. Either "dev", "prod" or "test", default is "prod"
RUN_MODE = ; prod
;; Application run mode, affects performance and debugging: "dev" or "prod", default is "prod"
;; Mode "dev" makes Gitea easier to develop and debug, values other than "dev" are treated as "prod" which is for production use.
;RUN_MODE = prod
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -230,7 +231,6 @@ RUN_MODE = ; prod
;;
;; Disable CDN even in "prod" mode
;OFFLINE_MODE = false
;DISABLE_ROUTER_LOG = false
;;
;; TLS Settings: Either ACME or manual
;; (Other common TLS configuration are found before)
@ -303,7 +303,7 @@ RUN_MODE = ; prod
LFS_JWT_SECRET =
;;
;; LFS authentication validity period (in time.Duration), pushes taking longer than this may fail.
;LFS_HTTP_AUTH_EXPIRY = 20m
;LFS_HTTP_AUTH_EXPIRY = 24h
;;
;; Maximum allowed LFS file size in bytes (Set to 0 for no limit).
;LFS_MAX_FILE_SIZE = 0
@ -387,7 +387,7 @@ USER = root
;ITERATE_BUFFER_SIZE = 50
;;
;; Show the database generated SQL
LOG_SQL = false ; if unset defaults to true
;LOG_SQL = false
;;
;; Maximum number of DB Connect retries
;DB_RETRIES = 10
@ -550,34 +550,32 @@ ENABLE = true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Main Logger
;;
;; Either "console", "file", "conn", "smtp" or "database", default is "console"
;; Either "console", "file" or "conn", default is "console"
;; Use comma to separate multiple modes, e.g. "console, file"
MODE = console
;;
;; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical" or "None", default is "Info"
;; Either "Trace", "Debug", "Info", "Warn", "Error" or "None", default is "Info"
LEVEL = Info
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Router Logger
;; Print Stacktrace with logs (rarely helpful, do not set) Either "Trace", "Debug", "Info", "Warn", "Error", default is "None"
;STACKTRACE_LEVEL = None
;;
;; Switch off the router log
;DISABLE_ROUTER_LOG=false
;; Buffer length of the channel, keep it as it is if you don't know what it is.
;BUFFER_LEN = 10000
;;
;; Set the log "modes" for the router log (if file is set the log file will default to router.log)
ROUTER = console
;; Sub logger modes, a single comma means use default MODE above, empty means disable it
;logger.access.MODE=
;logger.router.MODE=,
;logger.xorm.MODE=,
;;
;; The router will log different things at different levels.
;; Collect SSH logs (Creates log from ssh git request)
;;
;; * started messages will be logged at TRACE level
;; * polling/completed routers will be logged at INFO
;; * slow routers will be logged at WARN
;; * failed routers will be logged at WARN
;;
;; The routing level will default to that of the system but individual router level can be set in
;; [log.<mode>.router] LEVEL
;ENABLE_SSH_LOG = false
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Access Logger (Creates log in NCSA common log format)
;;
;; 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
@ -587,57 +585,32 @@ ROUTER = console
;; 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
;; * In request 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 =
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Access Logger (Creates log in NCSA common log format)
;;
;ENABLE_ACCESS_LOG = false
;;
;; Set the log "modes" for the access log (if file is set the log file will default to access.log)
;ACCESS = file
;REQUEST_ID_HEADERS =
;;
;; Sets the template used to create the access log.
;ACCESS_LOG_TEMPLATE = {{.Ctx.RemoteHost}} - {{.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}}"
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; SSH log (Creates log from ssh git request)
;;
;ENABLE_SSH_LOG = false
;;
;; Other Settings
;;
;; Print Stacktraces with logs. (Rarely helpful.) Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "None"
;STACKTRACE_LEVEL = None
;;
;; Buffer length of the channel, keep it as it is if you don't know what it is.
;BUFFER_LEN = 10000
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Creating specific log configuration
;;
;; You can set specific configuration for individual modes and subloggers
;; Log modes (aka log writers)
;;
;; Configuration available to all log modes/subloggers
;[log.%(WriterMode)]
;MODE=console/file/conn/...
;LEVEL=
;FLAGS = stdflags
;EXPRESSION =
;PREFIX =
;COLORIZE = false
;;
;; For "console" mode only
;[log.console]
;STDERR = false
;;
;; For "file" mode only
;LEVEL =
;; Set the file_name for the logger. If this is a relative path this
;; will be relative to ROOT_PATH
;[log.file]
;; Set the file_name for the logger. If this is a relative path this will be relative to ROOT_PATH
;FILE_NAME =
;; This enables automated log rotate(switch of following options), default is true
;LOG_ROTATE = true
@ -651,9 +624,8 @@ ROUTER = console
;COMPRESS = true
;; compression level see godoc for compress/gzip
;COMPRESSION_LEVEL = -1
;
;; For "conn" mode only
;LEVEL =
;;
;[log.conn]
;; Reconnect host for every single message, default is false
;RECONNECT_ON_MSG = false
;; Try to reconnect when connection is lost, default is false
@ -662,19 +634,6 @@ ROUTER = console
;PROTOCOL = tcp
;; Host address
;ADDR =
;
;; For "smtp" mode only
;LEVEL =
;; Name displayed in mail title, default is "Diagnostic message from server"
;SUBJECT = Diagnostic message from server
;; Mail server
;HOST =
;; Mailer user name and password
;USER =
;; Use PASSWD = `your password` for quoting if you use special characters in the password.
;PASSWD =
;; Receivers, can be one or more, e.g. 1@example.com,2@example.com
;RECEIVERS =
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -724,6 +683,24 @@ ROUTER = console
;; Disable the usage of using partial clones for git.
;DISABLE_PARTIAL_CLONE = false
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Git Operation timeout in seconds
;[git.timeout]
;DEFAULT = 360
;MIGRATE = 600
;MIRROR = 300
;CLONE = 300
;PULL = 300
;GC = 60
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Git config options
;; This section only does "set" config, a removed config key from this section won't be removed from git config automatically. The format is `some.configKey = value`.
;[git.config]
;diff.algorithm = histogram
;core.logAllRefUpdates = true
;gc.reflogExpire = 90
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
[service]
@ -742,11 +719,11 @@ ROUTER = console
;; Whether a new user needs to be confirmed manually after registration. (Requires `REGISTER_EMAIL_CONFIRM` to be disabled.)
;REGISTER_MANUAL_CONFIRM = false
;;
;; List of domain names that are allowed to be used to register on a Gitea instance
;; gitea.io,example.com
;EMAIL_DOMAIN_WHITELIST =
;; List of domain names that are allowed to be used to register on a Gitea instance, wildcard is supported
;; eg: gitea.io,example.com,*.mydomain.com
;EMAIL_DOMAIN_ALLOWLIST =
;;
;; Comma-separated list of domain names that are not allowed to be used to register on a Gitea instance
;; Comma-separated list of domain names that are not allowed to be used to register on a Gitea instance, wildcard is supported
;EMAIL_DOMAIN_BLOCKLIST =
;;
;; Disallow registration, only allow admins to create accounts.
@ -926,12 +903,6 @@ ROUTER = console
;; Global limit of repositories per user, applied at creation time. -1 means no limit
;MAX_CREATION_LIMIT = -1
;;
;; Mirror sync queue length, increase if mirror syncing starts hanging (DEPRECATED: please use [queue.mirror] LENGTH instead)
;MIRROR_QUEUE_LENGTH = 1000
;;
;; Patch test queue length, increase if pull request patch testing starts hanging (DEPRECATED: please use [queue.pr_patch_checker] LENGTH instead)
;PULL_REQUEST_QUEUE_LENGTH = 1000
;;
;; Preferred Licenses to place at the top of the List
;; The name here must match the filename in options/license or custom/options/license
;PREFERRED_LICENSES = Apache License 2.0,MIT License
@ -946,6 +917,9 @@ ROUTER = console
;; Force ssh:// clone url instead of scp-style uri when default SSH port is used
;USE_COMPAT_SSH_URI = false
;;
;; Value for the "go get" request returns the repository url as https or ssh, default is https
;GO_GET_CLONE_URL_PROTOCOL = https
;;
;; Close issues as long as a commit on any branch marks it as fixed
;; Comma separated list of globally disabled repo units. Allowed values: repo.issues, repo.ext_issues, repo.pulls, repo.wiki, repo.ext_wiki, repo.projects, repo.packages, repo.actions.
;DISABLED_REPO_UNITS =
@ -992,7 +966,7 @@ ROUTER = console
;;
;; List of file extensions for which lines should be wrapped in the Monaco editor
;; Separate extensions with a comma. To line wrap files without an extension, just put a comma
;LINE_WRAP_EXTENSIONS = .txt,.md,.markdown,.mdown,.mkd,
;LINE_WRAP_EXTENSIONS = .txt,.md,.markdown,.mdown,.mkd,.livemd,
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -1070,6 +1044,9 @@ ROUTER = console
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; List of reasons why a Pull Request or Issue can be locked
;LOCK_REASONS = Too heated,Off-topic,Resolved,Spam
;; Maximum number of pinned Issues per repo
;; Set to 0 to disable pinning Issues
;MAX_PINNED = 3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -1203,11 +1180,6 @@ ROUTER = console
;; Number of line of codes shown for a code comment
;CODE_COMMENT_LINES = 4
;;
;; Value of `theme-color` meta tag, used by Android >= 5.0
;; An invalid color like "none" or "disable" will have the default style
;; More info: https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android
;THEME_COLOR_META_TAG = `#6cc644`
;;
;; Max size of files to be displayed (default is 8MiB)
;MAX_DISPLAY_FILE_SIZE = 8388608
;;
@ -1236,9 +1208,6 @@ ROUTER = console
;; Whether to search within description at repository search on explore page.
;SEARCH_REPO_DESCRIPTION = true
;;
;; Whether to enable a Service Worker to cache frontend assets
;USE_SERVICE_WORKER = false
;;
;; Whether to only show relevant repos on the explore page when no keyword is specified and default sorting is used.
;; A repo is considered irrelevant if it's a fork or if it has no metadata (no description, no icon, no topic).
;ONLY_SHOW_RELEVANT_REPOS = false
@ -1331,11 +1300,12 @@ ROUTER = console
;; Comma separated list of custom URL-Schemes that are allowed as links when rendering Markdown
;; for example git,magnet,ftp (more at https://en.wikipedia.org/wiki/List_of_URI_schemes)
;; URLs starting with http and https are always displayed, whatever is put in this entry.
;; If this entry is empty, all URL schemes are allowed.
;CUSTOM_URL_SCHEMES =
;;
;; List of file extensions that should be rendered/edited as Markdown
;; Separate the extensions with a comma. To render files without any extension as markdown, just put a comma
;FILE_EXTENSIONS = .md,.markdown,.mdown,.mkd
;FILE_EXTENSIONS = .md,.markdown,.mdown,.mkd,.livemd
;;
;; Enables math inline and block detection
;ENABLE_MATH = true
@ -1377,22 +1347,6 @@ ROUTER = console
;; Set to -1 to disable timeout.
;STARTUP_TIMEOUT = 30s
;;
;; Issue indexer queue, currently support: channel, levelqueue or redis, default is levelqueue (deprecated - use [queue.issue_indexer])
;ISSUE_INDEXER_QUEUE_TYPE = levelqueue; **DEPRECATED** use settings in `[queue.issue_indexer]`.
;;
;; When ISSUE_INDEXER_QUEUE_TYPE is levelqueue, this will be the path where the queue will be saved.
;; This can be overridden by `ISSUE_INDEXER_QUEUE_CONN_STR`.
;; default is queues/common
;ISSUE_INDEXER_QUEUE_DIR = queues/common; **DEPRECATED** use settings in `[queue.issue_indexer]`. Relative paths will be made absolute against `%(APP_DATA_PATH)s`.
;;
;; When `ISSUE_INDEXER_QUEUE_TYPE` is `redis`, this will store the redis connection string.
;; When `ISSUE_INDEXER_QUEUE_TYPE` is `levelqueue`, this is a directory or additional options of
;; the form `leveldb://path/to/db?option=value&....`, and overrides `ISSUE_INDEXER_QUEUE_DIR`.
;ISSUE_INDEXER_QUEUE_CONN_STR = "addrs=127.0.0.1:6379 db=0"; **DEPRECATED** use settings in `[queue.issue_indexer]`.
;;
;; Batch queue number, default is 20
;ISSUE_INDEXER_QUEUE_BATCH_NUMBER = 20; **DEPRECATED** use settings in `[queue.issue_indexer]`.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Repository Indexer settings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -1400,6 +1354,10 @@ ROUTER = console
;; repo indexer by default disabled, since it uses a lot of disk space
;REPO_INDEXER_ENABLED = false
;;
;; repo indexer units, the items to index, could be `sources`, `forks`, `mirrors`, `templates` or any combination of them separated by a comma.
;; If empty then it defaults to `sources` only, as if you'd like to disable fully please see REPO_INDEXER_ENABLED.
;REPO_INDEXER_REPO_TYPES = sources,forks,mirrors,templates
;;
;; Code search engine type, could be `bleve` or `elasticsearch`.
;REPO_INDEXER_TYPE = bleve
;;
@ -1419,8 +1377,6 @@ ROUTER = console
;; A comma separated list of glob patterns to exclude from the index; ; default is empty
;REPO_INDEXER_EXCLUDE =
;;
;;
;UPDATE_BUFFER_LEN = 20; **DEPRECATED** use settings in `[queue.issue_indexer]`.
;MAX_FILE_SIZE = 1048576
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -1442,15 +1398,15 @@ ROUTER = console
;DATADIR = queues/ ; Relative paths will be made absolute against `%(APP_DATA_PATH)s`.
;;
;; Default queue length before a channel queue will block
;LENGTH = 20
;LENGTH = 100
;;
;; Batch size to send for batched queues
;BATCH_LENGTH = 20
;;
;; Connection string for redis queues this will store the redis connection string.
;; Connection string for redis queues this will store the redis or redis-cluster connection string.
;; When `TYPE` is `persistable-channel`, this provides a directory for the underlying leveldb
;; or additional options of the form `leveldb://path/to/db?option=value&....`, and will override `DATADIR`.
;CONN_STR = "addrs=127.0.0.1:6379 db=0"
;CONN_STR = "redis://127.0.0.1:6379/0"
;;
;; Provides the suffix of the default redis/disk queue name - specific queues can be overridden within in their [queue.name] sections.
;QUEUE_NAME = "_queue"
@ -1458,29 +1414,8 @@ ROUTER = console
;; Provides the suffix of the default redis/disk unique queue set name - specific queues can be overridden within in their [queue.name] sections.
;SET_NAME = "_unique"
;;
;; If the queue cannot be created at startup - level queues may need a timeout at startup - wrap the queue:
;WRAP_IF_NECESSARY = true
;;
;; Attempt to create the wrapped queue at max
;MAX_ATTEMPTS = 10
;;
;; Timeout queue creation
;TIMEOUT = 15m30s
;;
;; Create a pool with this many workers
;WORKERS = 0
;;
;; Dynamically scale the worker pool to at this many workers
;MAX_WORKERS = 10
;;
;; Add boost workers when the queue blocks for BLOCK_TIMEOUT
;BLOCK_TIMEOUT = 1s
;;
;; Remove the boost workers after BOOST_TIMEOUT
;BOOST_TIMEOUT = 5m
;;
;; During a boost add BOOST_WORKERS
;BOOST_WORKERS = 1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -1740,8 +1675,9 @@ ROUTER = console
;; For "memory" only, GC interval in seconds, default is 60
;INTERVAL = 60
;;
;; For "redis" and "memcache", connection host address
;; For "redis", "redis-cluster" and "memcache", connection host address
;; redis: `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
;; redis-cluster: `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
;; memcache: `127.0.0.1:11211`
;; twoqueue: `{"size":50000,"recent_ratio":0.25,"ghost_ratio":0.5}` or `50000`
;HOST =
@ -1773,7 +1709,7 @@ ROUTER = console
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Either "memory", "file", "redis", "db", "mysql", "couchbase", "memcache" or "postgres"
;; Either "memory", "file", "redis", "redis-cluster", "db", "mysql", "couchbase", "memcache" or "postgres"
;; Default is "memory". "db" will reuse the configuration in [database]
;PROVIDER = memory
;;
@ -1781,6 +1717,7 @@ ROUTER = console
;; memory: doesn't have any config yet
;; file: session file path, e.g. `data/sessions`
;; redis: `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
;; redis-cluster: `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
;; mysql: go-sql-driver/mysql dsn config string, e.g. `root:password@/session_table`
;PROVIDER_CONFIG = data/sessions ; Relative paths will be made absolute against _`AppWorkPath`_.
;;
@ -1816,16 +1753,19 @@ ROUTER = console
;; Max Width and Height of uploaded avatars.
;; This is to limit the amount of RAM used when resizing the image.
;AVATAR_MAX_WIDTH = 4096
;AVATAR_MAX_HEIGHT = 3072
;AVATAR_MAX_HEIGHT = 4096
;;
;; The multiplication factor for rendered avatar images.
;; Larger values result in finer rendering on HiDPI devices.
;AVATAR_RENDERED_SIZE_FACTOR = 3
;AVATAR_RENDERED_SIZE_FACTOR = 2
;;
;; Maximum allowed file size for uploaded avatars.
;; This is to limit the amount of RAM used when resizing the image.
;AVATAR_MAX_FILE_SIZE = 1048576
;;
;; If the uploaded file is not larger than this byte size, the image will be used as is, without resizing/converting.
;AVATAR_MAX_ORIGIN_SIZE = 262144
;;
;; Chinese users can choose "duoshuo"
;; or a custom avatar source, like: http://cn.gravatar.com/avatar/
;GRAVATAR_SOURCE = gravatar
@ -1900,11 +1840,6 @@ ROUTER = console
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Specifies the format for fully outputted dates. Defaults to RFC1123
;; Special supported values are ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, RFC3339, RFC3339Nano, Kitchen, Stamp, StampMilli, StampMicro and StampNano
;; For more information about the format see http://golang.org/pkg/time/#pkg-constants
;FORMAT =
;;
;; Location the UI time display i.e. Asia/Shanghai
;; Empty means server's location setting
;DEFAULT_UI_LOCATION =
@ -2260,32 +2195,6 @@ ROUTER = console
;Check at least this proportion of LFSMetaObjects per repo. (This may cause all stale LFSMetaObjects to be checked.)
;PROPORTION_TO_CHECK_PER_REPO = 0.6
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Git Operation timeout in seconds
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;[git.timeout]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;DEFAULT = 360
;MIGRATE = 600
;MIRROR = 300
;CLONE = 300
;PULL = 300
;GC = 60
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Git Reflog timeout in days
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;[git.reflog]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;ENABLED = true
;EXPIRATION = 90
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;[mirror]
@ -2340,7 +2249,6 @@ ROUTER = console
;[other]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;SHOW_FOOTER_BRANDING = false
;; Show version information about Gitea and Go in the footer
;SHOW_FOOTER_VERSION = true
;; Show template execution time in the footer
@ -2417,7 +2325,7 @@ ROUTER = console
;QUEUE_LENGTH = 1000
;;
;; Task queue connection string, available only when `QUEUE_TYPE` is `redis`.
;; If there is a password of redis, use `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`.
;; If there is a password of redis, use `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` or `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` for `redis-clsuter`.
;QUEUE_CONN_STR = "redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -2491,6 +2399,8 @@ ROUTER = console
;LIMIT_TOTAL_OWNER_COUNT = -1
;; Maximum size of packages a single owner can use (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_TOTAL_OWNER_SIZE = -1
;; Maximum size of an Alpine upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_ALPINE = -1
;; Maximum size of a Cargo upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_CARGO = -1
;; Maximum size of a Chef upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
@ -2503,8 +2413,14 @@ ROUTER = console
;LIMIT_SIZE_CONDA = -1
;; Maximum size of a Container upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_CONTAINER = -1
;; Maximum size of a CRAN upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_CRAN = -1
;; Maximum size of a Debian upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_DEBIAN = -1
;; Maximum size of a Generic upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_GENERIC = -1
;; Maximum size of a Go upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_GO = -1
;; Maximum size of a Helm upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_HELM = -1
;; Maximum size of a Maven upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
@ -2517,6 +2433,8 @@ ROUTER = console
;LIMIT_SIZE_PUB = -1
;; Maximum size of a PyPI upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_PYPI = -1
;; Maximum size of a RPM upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_RPM = -1
;; Maximum size of a RubyGems upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_RUBYGEMS = -1
;; Maximum size of a Swift upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)

View File

@ -1,4 +1,4 @@
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}dev{{/if}}-rootless
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}nightly{{/if}}-rootless
{{#if build.tags}}
{{#unless (contains "-rc" build.tag)}}
tags:
@ -10,12 +10,12 @@ tags:
{{/if}}
manifests:
-
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}dev{{/if}}-linux-amd64-rootless
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}nightly{{/if}}-linux-amd64-rootless
platform:
architecture: amd64
os: linux
-
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}dev{{/if}}-linux-arm64-rootless
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}nightly{{/if}}-linux-arm64-rootless
platform:
architecture: arm64
os: linux

View File

@ -1,4 +1,4 @@
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}dev{{/if}}
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}nightly{{/if}}
{{#if build.tags}}
{{#unless (contains "-rc" build.tag)}}
tags:
@ -10,12 +10,12 @@ tags:
{{/if}}
manifests:
-
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}dev{{/if}}-linux-amd64
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}nightly{{/if}}-linux-amd64
platform:
architecture: amd64
os: linux
-
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}dev{{/if}}-linux-arm64
image: gitea/gitea:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}{{#if (hasPrefix "refs/heads/release/v" build.ref)}}{{trimPrefix "refs/heads/release/v" build.ref}}-{{/if}}nightly{{/if}}-linux-arm64
platform:
architecture: arm64
os: linux

View File

@ -53,7 +53,7 @@ function doSearch() {
} else {
const para = document.createElement('P');
para.textContent = 'Please enter a word or phrase above';
document.getElementById('search-results').appendChild(para);
document.getElementById('search-results').append(para);
}
}
@ -85,7 +85,7 @@ function executeSearch(searchQuery) {
} else {
const para = document.createElement('P');
para.textContent = 'No matches found';
document.getElementById('search-results').appendChild(para);
document.getElementById('search-results').append(para);
}
});
}
@ -128,7 +128,7 @@ function populateResults(result) {
categories: value.item.categories,
snippet
});
document.getElementById('search-results').appendChild(htmlToElement(output));
document.getElementById('search-results').append(htmlToElement(output));
for (const snipvalue of snippetHighlights) {
new Mark(document.getElementById(`summary-${key}`)).mark(snipvalue);
@ -138,8 +138,8 @@ function populateResults(result) {
function render(templateString, data) {
let conditionalMatches, copy;
const conditionalPattern = /\$\{\s*isset ([a-zA-Z]*) \s*\}(.*)\$\{\s*end\s*}/g;
// since loop below depends on re.lastInxdex, we use a copy to capture any manipulations whilst inside the loop
const conditionalPattern = /\$\{\s*isset ([a-zA-Z]*) \s*\}(.*)\$\{\s*end\s*\}/g;
// since loop below depends on re.lastIndex, we use a copy to capture any manipulations whilst inside the loop
copy = templateString;
while ((conditionalMatches = conditionalPattern.exec(templateString)) !== null) {
if (data[conditionalMatches[1]]) {

View File

@ -10,7 +10,7 @@ enableEmoji: true
permalinks:
post: /:year/:month/:title/
doc: /:slug/
doc: /:sections[1:]/:slug/
page: /:slug/
default: /:slug/
@ -18,8 +18,8 @@ params:
description: Git with a cup of tea
author: The Gitea Authors
website: https://docs.gitea.io
version: 1.19.0
minGoVersion: 1.19
version: 1.19.0 # FIXME: this version was used as "latest stable release", but it always gets outdated and doesn't make sense
minGoVersion: 1.20
goVersion: 1.20
minNodeVersion: 16
search: nav

View File

@ -0,0 +1,13 @@
---
date: "2023-04-27T14:00:00+08:00"
title: "Actions"
slug: "actions"
weight: 36
toc: false
draft: false
menu:
sidebar:
name: "Usage - Actions"
weight: 31
identifier: "actions"
---

View File

@ -5,6 +5,8 @@ slug: adding-legal-pages
weight: 110
toc: false
draft: false
aliases:
- /en-us/adding-legal-pages
menu:
sidebar:
parent: "administration"

View File

@ -0,0 +1,40 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "添加法律页面"
slug: adding-legal-pages
weight: 110
toc: false
draft: false
aliases:
- /zh-cn/adding-legal-pages
menu:
sidebar:
parent: "administration"
name: "添加法律页面"
identifier: "adding-legal-pages"
weight: 110
---
一些法域(例如欧盟)要求在网站上添加特定的法律页面(例如隐私政策)。按照以下步骤将它们添加到你的 Gitea 实例中。
## 获取页面
Gitea 源代码附带了示例页面,位于 `contrib/legal` 目录中。将它们复制到 `custom/public/` 目录下。例如,如果要添加隐私政策:
```
wget -O /path/to/custom/public/privacy.html https://raw.githubusercontent.com/go-gitea/gitea/main/contrib/legal/privacy.html.sample
```
现在,你需要编辑该页面以满足你的需求。特别是,你必须更改电子邮件地址、网址以及与 "Your Gitea Instance" 相关的引用,以匹配你的情况。
请务必不要放置会暗示 Gitea 项目对你的服务器负责的一般服务条款或隐私声明。
## 使其可见
创建或追加到 `/path/to/custom/templates/custom/extra_links_footer.tmpl` 文件中:
```go
<a class="item" href="{{AppSubUrl}}/assets/privacy.html">隐私政策</a>
```
重启 Gitea 以查看更改。

View File

@ -5,6 +5,8 @@ slug: "backup-and-restore"
weight: 11
toc: false
draft: false
aliases:
- /en-us/backup-and-restore
menu:
sidebar:
parent: "administration"

View File

@ -1,10 +1,12 @@
---
date: "2018-06-06T09:33:00+08:00"
title: "使用:备份与恢复"
title: "备份与恢复"
slug: "backup-and-restore"
weight: 11
toc: false
draft: false
aliases:
- /zh-cn/backup-and-restore
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "backup-and-restore"
weight: 11
toc: false
draft: false
aliases:
- /zh-tw/backup-and-restore
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "cmd-embedded"
weight: 20
toc: false
draft: false
aliases:
- /en-us/cmd-embedded
menu:
sidebar:
parent: "administration"
@ -38,7 +40,7 @@ gitea embedded list [--include-vendored] [patterns...]
The `--include-vendored` flag makes the command include vendored files, which are
normally excluded; that is, files from external libraries that are required for Gitea
(e.g. [font-awesome](https://fontawesome.com/), [octicons](https://octicons.github.com/), etc).
(e.g. [octicons](https://octicons.github.com/), etc).
A list of file search patterns can be provided. Gitea uses [gobwas/glob](https://github.com/gobwas/glob)
for its glob syntax. Here are some examples:

View File

@ -0,0 +1,105 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "嵌入资源提取工具"
slug: "cmd-embedded"
weight: 20
toc: false
draft: false
aliases:
- /zh-cn/cmd-embedded
menu:
sidebar:
parent: "administration"
name: "嵌入资源提取工具"
weight: 20
identifier: "cmd-embedded"
---
# 嵌入资源提取工具
**目录**
{{< toc >}}
Gitea 的可执行文件包含了运行所需的所有资源:模板、图片、样式表和翻译文件。你可以通过在 `custom` 目录下的相应路径中放置替换文件来覆盖其中的任何资源(详见 [自定义 Gitea 配置]({{< relref "doc/administration/customizing-gitea.zh-cn.md" >}}))。
要获取嵌入资源的副本以进行编辑,可以使用 CLI 中的 `embedded` 命令,通过操作系统的 shell 执行。
**注意:** 嵌入资源提取工具包含在 Gitea 1.12 及以上版本中。
## 资源列表
要列出嵌入在 Gitea 可执行文件中的资源,请使用以下语法:
```sh
gitea embedded list [--include-vendored] [patterns...]
```
`--include-vendored` 标志使命令包括被供应的文件,这些文件通常被排除在外;即来自外部库的文件,这些文件是 Gitea 所需的(例如 [octicons](https://octicons.github.com/) 等)。
可以提供一系列文件搜索模式。Gitea 使用 [gobwas/glob](https://github.com/gobwas/glob) 作为其 glob 语法。以下是一些示例:
- 列出所有模板文件,无论在哪个虚拟目录下:`**.tmpl`
- 列出所有邮件模板文件:`templates/mail/**.tmpl`
- 列出 `public/img` 目录下的所有文件:`public/img/**`
不要忘记为模式使用引号,因为空格、`*` 和其他字符可能对命令行解释器有特殊含义。
如果未提供模式,则列出所有文件。
### 示例
列出所有路径中包含 `openid` 的嵌入文件:
```sh
$ gitea embedded list '**openid**'
public/img/auth/openid_connect.svg
public/img/openid-16x16.png
templates/user/auth/finalize_openid.tmpl
templates/user/auth/signin_openid.tmpl
templates/user/auth/signup_openid_connect.tmpl
templates/user/auth/signup_openid_navbar.tmpl
templates/user/auth/signup_openid_register.tmpl
templates/user/settings/security_openid.tmpl
```
## 提取资源
要提取嵌入在 Gitea 可执行文件中的资源,请使用以下语法:
```sh
gitea [--config {file}] embedded extract [--destination {dir}|--custom] [--overwrite|--rename] [--include-vendored] {patterns...}
```
`--config` 选项用于告知 Gitea `app.ini` 配置文件的位置(如果不在默认位置)。此选项仅在使用 `--custom` 标志时使用。
`--destination` 选项用于指定提取文件的目标目录。默认为当前目录。
`--custom` 标志告知 Gitea 直接将文件提取到 `custom` 目录中。为使其正常工作,该命令需要知道 `app.ini` 配置文件的位置(通过 `--config` 指定),并且根据配置的不同,需要从 Gitea 通常启动的目录运行。有关详细信息,请参阅 [自定义 Gitea 配置]({{< relref "doc/administration/customizing-gitea.zh-cn.md" >}})。
`--overwrite` 标志允许覆盖目标目录中的任何现有文件。
`--rename` 标志告知 Gitea 将目标目录中的任何现有文件重命名为 `filename.bak`。之前的 `.bak` 文件将被覆盖。
至少需要提供一个文件搜索模式;有关模式的语法和示例,请参阅上述 `list` 子命令。
### 重要提示
请确保**只提取需要自定义的文件**。位于 `custom` 目录中的文件不会受到 Gitea 的升级过程的影响。当 Gitea 升级到新版本通过替换可执行文件许多嵌入文件将发生变化。Gitea 将尊重并使用在 `custom` 目录中找到的任何文件,即使这些文件是旧的和不兼容的。
### 示例
将邮件模板提取到临时目录:
```sh
$ mkdir tempdir
$ gitea embedded extract --destination tempdir 'templates/mail/**.tmpl'
Extracting to tempdir:
tempdir/templates/mail/auth/activate.tmpl
tempdir/templates/mail/auth/activate_email.tmpl
tempdir/templates/mail/auth/register_notify.tmpl
tempdir/templates/mail/auth/reset_passwd.tmpl
tempdir/templates/mail/issue/assigned.tmpl
tempdir/templates/mail/issue/default.tmpl
tempdir/templates/mail/notify/collaborator.tmpl
```

View File

@ -5,6 +5,8 @@ slug: "command-line"
weight: 1
toc: false
draft: false
aliases:
- /en-us/command-line
menu:
sidebar:
parent: "administration"
@ -223,7 +225,7 @@ Admin operations:
- `--synchronize-users`: Enable user synchronization.
- `--page-size value`: Search page size.
- Examples:
- `gitea admin auth add-ldap --name ldap --security-protocol unencrypted --host mydomain.org --port 389 --user-search-base "ou=Users,dc=mydomain,dc=org" --user-filter "(&(objectClass=posixAccount)(uid=%s))" --email-attribute mail`
- `gitea admin auth add-ldap --name ldap --security-protocol unencrypted --host mydomain.org --port 389 --user-search-base "ou=Users,dc=mydomain,dc=org" --user-filter "(&(objectClass=posixAccount)(|(uid=%[1]s)(mail=%[1]s)))" --email-attribute mail`
- `update-ldap`: Update existing LDAP (via Bind DN) authentication source
- Options:
- `--id value`: ID of authentication source. Required.

View File

@ -0,0 +1,556 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "Gitea 命令行"
slug: "command-line"
weight: 1
toc: false
draft: false
aliases:
- /zh-cn/command-line
menu:
sidebar:
parent: "administration"
name: "Gitea 命令行"
weight: 1
identifier: "command-line"
---
# 命令行
**目录**
{{< toc >}}
## 用法
`gitea [全局选项] 命令 [命令或全局选项] [参数...]`
## 全局选项
所有全局选项均可被放置在命令级别。
- `--help``-h`:显示帮助文本并退出。可选。
- `--version``-v`:显示版本信息并退出。可选。 (示例:`Gitea version 1.1.0+218-g7b907ed built with: bindata, sqlite`)。
- `--custom-path path``-C path`Gitea 自定义文件夹的路径。可选。 (默认值:`AppWorkPath`/custom 或 `$GITEA_CUSTOM`)。
- `--config path``-c path`Gitea 配置文件的路径。可选。 (默认值:`custom`/conf/app.ini)。
- `--work-path path``-w path`Gitea 的 `AppWorkPath`。可选。 (默认值LOCATION_OF_GITEA_BINARY 或 `$GITEA_WORK_DIR`)
注意:默认的 custom-path、config 和 work-path 也可以在构建时更改(如果需要)。
## 命令
### web
启动服务器:
- 选项:
- `--port number``-p number`:端口号。可选。 (默认值3000)。覆盖配置文件中的设置。
- `--install-port number`:运行安装页面的端口号。可选。 (默认值3000)。覆盖配置文件中的设置。
- `--pid path``-P path`Pid 文件的路径。可选。
- `--quiet``-q`:只在控制台上输出 Fatal 日志,用于在设置日志之前发出的日志。
- `--verbose`:在控制台上输出跟踪日志,用于在设置日志之前发出的日志。
- 示例:
- `gitea web`
- `gitea web --port 80`
- `gitea web --config /etc/gitea.ini --pid /some/custom/gitea.pid`
- 注意:
- Gitea 不应以 root 用户身份运行。要绑定到低于 1024 的端口,您可以在 Linux 上使用 setcap 命令:`sudo setcap 'cap_net_bind_service=+ep' /path/to/gitea`。每次更新 Gitea 都需要重新执行此操作。
### admin
管理员操作:
- 命令:
- `user`
- `list`
- 选项:
- `--admin`:仅列出管理员用户。可选。
- 描述:列出所有现有用户。
- 示例:
- `gitea admin user list`
- `delete`
- 选项:
- `--email`:要删除的用户的电子邮件。
- `--username`:要删除的用户的用户名。
- `--id`要删除的用户的ID。
- 必须提供 `--id`、`--username` 或 `--email` 中的一个。如果提供多个,则所有条件必须匹配。
- 示例:
- `gitea admin user delete --id 1`
- `create`
- 选项:
- `--name value`:用户名。必填。自 Gitea 1.9.0 版本起,请改用 `--username` 标志。
- `--username value`用户名。必填。Gitea 1.9.0 新增。
- `--password value`:密码。必填。
- `--email value`:邮箱。必填。
- `--admin`:如果提供此选项,将创建一个管理员用户。可选。
- `--access-token`如果提供将为用户创建访问令牌。可选。默认值false
- `--must-change-password`如果提供创建的用户将在初始登录后需要选择一个新密码。可选。默认值true
- `--random-password`:如果提供,将使用随机生成的密码作为创建用户的密码。`--password` 的值将被忽略。可选。
- `--random-password-length`如果提供将用于配置随机生成密码的长度。可选。默认值12
- 示例:
- `gitea admin user create --username myname --password asecurepassword --email me@example.com`
- `change-password`
- 选项:
- `--username value``-u value`:用户名。必填。
- `--password value``-p value`:新密码。必填。
- 示例:
- `gitea admin user change-password --username myname --password asecurepassword`
- `must-change-password`
- 参数:
- `[username...]`:需要更改密码的用户
- 选项:
- `--all``-A`:强制所有用户更改密码
- `--exclude username``-e username`:排除给定的用户。可以多次设置。
- `--unset`:撤销对给定用户的强制密码更改
- `regenerate`
- 选项:
- `hooks`:重新生成所有仓库的 Git Hooks。
- `keys`:重新生成 authorized_keys 文件。
- 示例:
- `gitea admin regenerate hooks`
- `gitea admin regenerate keys`
- `auth`
- `list`
- 描述:列出所有存在的外部认证源。
- 示例:
- `gitea admin auth list`
- `delete`
- 选项:
- `--id`:要删除的源的 ID。必填。
- 示例:
- `gitea admin auth delete --id 1`
- `add-oauth`
- 选项:
- `--name`:应用程序名称。
- `--provider`OAuth2 提供者。
- `--key`:客户端 IDKey
- `--secret`:客户端密钥。
- `--auto-discover-url`OpenID Connect 自动发现 URL仅在使用 OpenID Connect 作为提供程序时需要)。
- `--use-custom-urls`:在 GitLab/GitHub OAuth 端点上使用自定义 URL。
- `--custom-tenant-id`:在 OAuth 端点上使用自定义租户 ID。
- `--custom-auth-url`:使用自定义授权 URLGitLab/GitHub 的选项)。
- `--custom-token-url`:使用自定义令牌 URLGitLab/GitHub 的选项)。
- `--custom-profile-url`:使用自定义配置文件 URLGitLab/GitHub 的选项)。
- `--custom-email-url`:使用自定义电子邮件 URLGitHub 的选项)。
- `--icon-url`OAuth2 登录源的自定义图标 URL。
- `--skip-local-2fa`:允许源覆盖本地 2FA。可选
- `--scopes`:请求此 OAuth2 源的附加范围。(可选)
- `--required-claim-name`:必须设置的声明名称,以允许用户使用此源登录。(可选)
- `--required-claim-value`:必须设置的声明值,以允许用户使用此源登录。(可选)
- `--group-claim-name`:提供此源的组名的声明名称。(可选)
- `--admin-group`:管理员用户的组声明值。(可选)
- `--restricted-group`:受限用户的组声明值。(可选)
- `--group-team-map`:组与组织团队之间的 JSON 映射。(可选)
- `--group-team-map-removal`:根据组自动激活团队成员资格的删除。(可选)
- 示例:
- `gitea admin auth add-oauth --name external-github --provider github --key OBTAIN_FROM_SOURCE --secret OBTAIN_FROM_SOURCE`
- `update-oauth`
- 选项:
- `--id`:要更新的源的 ID。必填。
- `--name`:应用程序名称。
- `--provider`OAuth2 提供者。
- `--key`:客户端 IDKey
- `--secret`:客户端密钥。
- `--auto-discover-url`OpenID Connect 自动发现 URL仅在使用 OpenID Connect 作为提供程序时需要)。
- `--use-custom-urls`:在 GitLab/GitHub OAuth 端点上使用自定义 URL。
- `--custom-tenant-id`:在 OAuth 端点上使用自定义租户 ID。
- `--custom-auth-url`:使用自定义授权 URLGitLab/GitHub 的选项)。
- `--custom-token-url`:使用自定义令牌 URLGitLab/GitHub 的选项)。
- `--custom-profile-url`:使用自定义配置文件 URLGitLab/GitHub 的选项)。
- `--custom-email-url`:使用自定义电子邮件 URLGitHub 的选项)。
- `--icon-url`OAuth2 登录源的自定义图标 URL。
- `--skip-local-2fa`:允许源覆盖本地 2FA。可选
- `--scopes`:请求此 OAuth2 源的附加范围。
- `--required-claim-name`:必须设置的声明名称,以允许用户使用此源登录。(可选)
- `--required-claim-value`:必须设置的声明值,以允许用户使用此源登录。(可选)
- `--group-claim-name`:提供此源的组名的声明名称。(可选)
- `--admin-group`:管理员用户的组声明值。(可选)
- `--restricted-group`:受限用户的组声明值。(可选)
- 示例:
- `gitea admin auth update-oauth --id 1 --name external-github-updated`
- `add-smtp`
- 选项:
- `--name`:应用程序名称。必填。
- `--auth-type`SMTP 认证类型PLAIN/LOGIN/CRAM-MD5。默认为 PLAIN。
- `--host`SMTP 主机。必填。
- `--port`SMTP 端口。必填。
- `--force-smtps`SMTPS 始终在端口 465 上使用。设置此选项以强制在其他端口上使用 SMTPS。
- `--skip-verify`:跳过 TLS 验证。
- `--helo-hostname`:发送 HELO 时使用的主机名。留空以发送当前主机名。
- `--disable-helo`:禁用 SMTP helo。
- `--allowed-domains`:留空以允许所有域。使用逗号(',')分隔多个域。
- `--skip-local-2fa`:跳过 2FA 登录。
- `--active`:启用此认证源。
备注:
`--force-smtps`、`--skip-verify`、`--disable-helo`、`--skip-local-2fs` 和 `--active` 选项可以采用以下形式使用:
- `--option`、`--option=true` 以启用选项
- `--option=false` 以禁用选项
如果未指定这些选项,则在 `update-smtp` 中不会更改值,或者在 `add-smtp` 中将使用默认的 `false` 值。
- 示例:
- `gitea admin auth add-smtp --name ldap --host smtp.mydomain.org --port 587 --skip-verify --active`
- `update-smtp`
- 选项:
- `--id`:要更新的源的 ID。必填。
- 其他选项与 `add-smtp` 共享
- 示例:
- `gitea admin auth update-smtp --id 1 --host smtp.mydomain.org --port 587 --skip-verify=false`
- `gitea admin auth update-smtp --id 1 --active=false`
- `add-ldap`:添加新的 LDAP通过 Bind DN认证源
- 选项:
- `--name value`:认证名称。必填。
- `--not-active`:停用认证源。
- `--security-protocol value`:安全协议名称。必填。
- `--skip-tls-verify`:禁用 TLS 验证。
- `--host value`LDAP 服务器的地址。必填。
- `--port value`:连接到 LDAP 服务器时使用的端口。必填。
- `--user-search-base value`:用户帐户将在其中搜索的 LDAP 基础路径。必填。
- `--user-filter value`:声明如何查找试图进行身份验证的用户记录的 LDAP 过滤器。必填。
- `--admin-filter value`:指定是否应授予用户管理员特权的 LDAP 过滤器。
- `--restricted-filter value`:指定是否应将用户设置为受限状态的 LDAP 过滤器。
- `--username-attribute value`:用户 LDAP 记录中包含用户名的属性。
- `--firstname-attribute value`:用户 LDAP 记录中包含用户名字的属性。
- `--surname-attribute value`:用户 LDAP 记录中包含用户姓氏的属性。
- `--email-attribute value`:用户 LDAP 记录中包含用户电子邮件地址的属性。必填。
- `--public-ssh-key-attribute value`:用户 LDAP 记录中包含用户公共 SSH 密钥的属性。
- `--avatar-attribute value`:用户 LDAP 记录中包含用户头像的属性。
- `--bind-dn value`:在搜索用户时绑定到 LDAP 服务器的 DN。
- `--bind-password value`:绑定 DN 的密码(如果有)。
- `--attributes-in-bind`:在绑定 DN 上下文中获取属性。
- `--synchronize-users`:启用用户同步。
- `--page-size value`:搜索页面大小。
- 示例:
- `gitea admin auth add-ldap --name ldap --security-protocol unencrypted --host mydomain.org --port 389 --user-search-base "ou=Users,dc=mydomain,dc=org" --user-filter "(&(objectClass=posixAccount)(|(uid=%[1]s)(mail=%[1]s)))" --email-attribute mail`
- `update-ldap`:更新现有的 LDAP通过 Bind DN认证源
- 选项:
- `--id value`:认证源的 ID。必填。
- `--name value`:认证名称。
- `--not-active`:停用认证源。
- `--security-protocol value`:安全协议名称。
- `--skip-tls-verify`:禁用 TLS 验证。
- `--host value`LDAP 服务器的地址。
- `--port value`:连接到 LDAP 服务器时使用的端口。
- `--user-search-base value`:用户帐户将在其中搜索的 LDAP 基础路径。
- `--user-filter value`:声明如何查找试图进行身份验证的用户记录的 LDAP 过滤器。
- `--admin-filter value`:指定是否应授予用户管理员特权的 LDAP 过滤器。
- `--restricted-filter value`:指定是否应将用户设置为受限状态的 LDAP 过滤器。
- `--username-attribute value`:用户 LDAP 记录中包含用户名的属性。
- `--firstname-attribute value`:用户 LDAP 记录中包含用户名字的属性。
- `--surname-attribute value`:用户 LDAP 记录中包含用户姓氏的属性。
- `--email-attribute value`:用户 LDAP 记录中包含用户电子邮件地址的属性。
- `--public-ssh-key-attribute value`:用户 LDAP 记录中包含用户公共 SSH 密钥的属性。
- `--avatar-attribute value`:用户 LDAP 记录中包含用户头像的属性。
- `--bind-dn value`:在搜索用户时绑定到 LDAP 服务器的 DN。
- `--bind-password value`:绑定 DN 的密码(如果有)。
- `--attributes-in-bind`:在绑定 DN 上下文中获取属性。
- `--synchronize-users`:启用用户同步。
- `--page-size value`:搜索页面大小。
- 示例:
- `gitea admin auth update-ldap --id 1 --name "my ldap auth source"`
- `gitea admin auth update-ldap --id 1 --username-attribute uid --firstname-attribute givenName --surname-attribute sn`
- `add-ldap-simple`:添加新的 LDAP简单身份验证认证源
- 选项:
- `--name value`:认证名称。必填。
- `--not-active`:停用认证源。
- `--security-protocol value`:安全协议名称。必填。
- `--skip-tls-verify`:禁用 TLS 验证。
- `--host value`LDAP 服务器的地址。必填。
- `--port value`:连接到 LDAP 服务器时使用的端口。必填。
- `--user-search-base value`:用户帐户将在其中搜索的 LDAP 基础路径。
- `--user-filter value`:声明如何查找试图进行身份验证的用户记录的 LDAP 过滤器。必填。
- `--admin-filter value`:指定是否应授予用户管理员特权的 LDAP 过滤器。
- `--restricted-filter value`:指定是否应将用户设置为受限状态的 LDAP 过滤器。
- `--username-attribute value`:用户 LDAP 记录中包含用户名的属性。
- `--firstname-attribute value`:用户 LDAP 记录中包含用户名字的属性。
- `--surname-attribute value`:用户 LDAP 记录中包含用户姓氏的属性。
- `--email-attribute value`:用户 LDAP 记录中包含用户电子邮件地址的属性。必填。
- `--public-ssh-key-attribute value`:用户 LDAP 记录中包含用户公共 SSH 密钥的属性。
- `--avatar-attribute value`:用户 LDAP 记录中包含用户头像的属性。
- `--user-dn value`:用户的 DN。必填。
- 示例:
- `gitea admin auth add-ldap-simple --name ldap --security-protocol unencrypted --host mydomain.org --port 389 --user-dn "cn=%s,ou=Users,dc=mydomain,dc=org" --user-filter "(&(objectClass=posixAccount)(cn=%s))" --email-attribute mail`
- `update-ldap-simple`:更新现有的 LDAP简单身份验证认证源
- 选项:
- `--id value`:认证源的 ID。必填。
- `--name value`:认证名称。
- `--not-active`:停用认证源。
- `--security-protocol value`:安全协议名称。
- `--skip-tls-verify`:禁用 TLS 验证。
- `--host value`LDAP 服务器的地址。
- `--port value`:连接到 LDAP 服务器时使用的端口。
- `--user-search-base value`:用户帐户将在其中搜索的 LDAP 基础路径。
- `--user-filter value`:声明如何查找试图进行身份验证的用户记录的 LDAP 过滤器。
- `--admin-filter value`:指定是否应授予用户管理员特权的 LDAP 过滤器。
- `--restricted-filter value`:指定是否应将用户设置为受限状态的 LDAP 过滤器。
- `--username-attribute value`:用户 LDAP 记录中包含用户名的属性。
- `--firstname-attribute value`:用户 LDAP 记录中包含用户名字的属性。
- `--surname-attribute value`:用户 LDAP 记录中包含用户姓氏的属性。
- `--email-attribute value`:用户 LDAP 记录中包含用户电子邮件地址的属性。
- `--public-ssh-key-attribute value`:用户 LDAP 记录中包含用户公共 SSH 密钥的属性。
- `--avatar-attribute value`:用户 LDAP 记录中包含用户头像的属性。
- `--user-dn value`:用户的 DN。
- 示例:
- `gitea admin auth update-ldap-simple --id 1 --name "my ldap auth source"`
- `gitea admin auth update-ldap-simple --id 1 --username-attribute uid --firstname-attribute givenName --surname-attribute sn`
### cert
生成自签名的SSL证书。将输出到当前目录下的`cert.pem`和`key.pem`文件中,并且会覆盖任何现有文件。
- 选项:
- `--host value`逗号分隔的主机名和IP地址列表此证书适用于这些主机。支持使用通配符。必填。
- `--ecdsa-curve value`用于生成密钥的ECDSA曲线。可选。有效选项为P224、P256、P384、P521。
- `--rsa-bits value`要生成的RSA密钥的大小。可选。如果设置了--ecdsa-curve则忽略此选项。默认值2048
- `--start-date value`:证书的创建日期。可选。(格式:`Jan 1 15:04:05 2011`)。
- `--duration value`证书有效期。可选。默认值8760h0m0s
- `--ca`:如果提供此选项,则证书将生成自己的证书颁发机构。可选。
- 示例:
- `gitea cert --host git.example.com,example.com,www.example.com --ca`
### dump
将所有文件和数据库导出到一个zip文件中。输出文件将保存在当前目录下类似于`gitea-dump-1482906742.zip`。
- 选项:
- `--file name``-f name`指定要创建的导出文件的名称。可选。默认值gitea-dump-[timestamp].zip
- `--tempdir path``-t path`:指定临时目录的路径。可选。(默认值:/tmp
- `--skip-repository``-R`:跳过仓库的导出。可选。
- `--skip-custom-dir`:跳过自定义目录的导出。可选。
- `--skip-lfs-data`跳过LFS数据的导出。可选。
- `--skip-attachment-data`:跳过附件数据的导出。可选。
- `--skip-package-data`:跳过包数据的导出。可选。
- `--skip-log`:跳过日志数据的导出。可选。
- `--database``-d`指定数据库的SQL语法。可选。
- `--verbose``-V`:如果提供此选项,显示附加详细信息。可选。
- `--type`设置导出的格式。可选。默认值zip
- 示例:
- `gitea dump`
- `gitea dump --verbose`
### generate
用于在配置文件中生成随机值和令牌。对于自动部署时生成值非常有用。
- 命令:
- `secret`:
- 选项:
- `INTERNAL_TOKEN`: 用于内部 API 调用身份验证的令牌。
- `JWT_SECRET`: 用于 LFS 和 OAUTH2 JWT 身份验证的密钥LFS_JWT_SECRET 是此选项的别名,用于向后兼容)。
- `SECRET_KEY`: 全局密钥。
- 示例:
- `gitea generate secret INTERNAL_TOKEN`
- `gitea generate secret JWT_SECRET`
- `gitea generate secret SECRET_KEY`
### keys
提供一个 SSHD AuthorizedKeysCommand。需要在 sshd 配置文件中进行配置:
```ini
...
# -e 的值和 AuthorizedKeysCommandUser 应与运行 Gitea 的用户名匹配
AuthorizedKeysCommandUser git
AuthorizedKeysCommand /path/to/gitea keys -e git -u %u -t %t -k %k
```
该命令将返回适用于提供的密钥的合适 authorized_keys 行。您还应在 `app.ini``[server]` 部分设置值 `SSH_CREATE_AUTHORIZED_KEYS_FILE=false`
注意: opensshd 要求 Gitea 程序由 root 拥有,并且不可由组或其他人写入。程序必须使用绝对路径指定。
注意: Gitea 必须在运行此命令时处于运行状态才能成功。
### migrate
迁移数据库。该命令可用于在首次启动服务器之前运行其他命令。此命令是幂等的。
### convert
将现有的 MySQL 数据库从 utf8 转换为 utf8mb4。
### doctor
根据给定的配置诊断当前 Gitea 实例的问题。目前有以下检查清单:
- 检查 OpenSSH 的 authorized_keys 文件是否正确
当您的 Gitea 实例支持 OpenSSH 时,当您的 Gitea 实例添加或更改任何公钥时Gitea 实例的二进制路径将被写入 `authorized_keys` 文件。
有时,如果您在升级时移动或重命名了 Gitea 二进制文件,并且您没有在管理面板上运行“使用 Gitea 的 SSH 密钥更新「.ssh/authorized_keys」文件”操作。那么通过 SSH 的所有拉取/推送操作将无法正常工作。
此检查将帮助您检查它是否正常工作。
对于贡献者,如果您想添加更多的检查项,您可以编写一个新的函数,如 `func(ctx *cli.Context) ([]string, error)`,并将其追加到 `doctor.go` 文件中。
```go
var checklist = []check{
{
title: "Check if OpenSSH authorized_keys file id correct",
f: runDoctorLocationMoved,
},
// more checks please append here
}
```
此函数将接收一个命令行上下文,并返回有关问题或错误的详细信息列表。
#### doctor recreate-table
有时,在迁移时,旧的列和默认值可能会在数据库模式中保持不变。这可能会导致警告,如下所示:
```
2020/08/02 11:32:29 ...rm/session_schema.go:360:Sync2() [W] Table user Column keep_activity_private db default is , struct default is 0
```
您可以通过以下方式让 Gitea 重新创建这些表,并将旧数据复制到新表中,并适当设置默认值:
```
gitea doctor recreate-table user
```
您可以使用以下方式让 Gitea 重新创建多个表:
```
gitea doctor recreate-table table1 table2 ...
```
如果您希望 Gitea 重新创建所有表,请直接调用:
```
gitea doctor recreate-table
```
强烈建议在运行这些命令之前备份您的数据库。
### manager
管理运行中的服务器操作:
- 命令:
- `shutdown`: 优雅地关闭运行中的进程
- `restart`: 优雅地重新启动运行中的进程对于Windows服务器尚未实现
- `flush-queues`: 刷新运行中的进程中的队列
- 选项:
- `--timeout value`: 刷新过程的超时时间(默认值: 1m0s
- `--non-blocking`: 设置为true以在返回之前不等待刷新完成
- `logging`: 调整日志命令
- 命令:
- `pause`: 暂停日志记录
- 注意:
- 如果日志级别低于此级别日志级别将被临时提升为INFO。
- Gitea将在一定程度上缓冲日志并在超过该点后丢弃日志。
- `resume`: 恢复日志记录
- `release-and-reopen`: 使Gitea释放和重新打开用于日志记录的文件和连接相当于向Gitea发送SIGUSR1信号
- `remove name`: 删除指定的日志记录器
- 选项:
- `--group group`, `-g group`: 从中删除子记录器的组(默认为`default`
- `add`: 添加日志记录器
- 命令:
- `console`: 添加控制台日志记录器
- 选项:
- `--group value`, `-g value`: 要添加日志记录器的组 - 默认为"default"
- `--name value`, `-n value`: 新日志记录器的名称 - 默认为模式
- `--level value`, `-l value`: 新日志记录器的日志级别
- `--stacktrace-level value`, `-L value`: 堆栈跟踪日志级别
- `--flags value`, `-F value`: 日志记录器的标志
- `--expression value`, `-e value`: 日志记录器的匹配表达式
- `--prefix value`, `-p value`: 日志记录器的前缀
- `--color`: 在日志中使用颜色
- `--stderr`: 将控制台日志输出到stderr - 仅适用于控制台
- `file`: 添加文件日志记录器
- 选项:
- `--group value`, `-g value`: 要添加日志记录器的组 - 默认为"default"
- `--name value`, `-n value`: 新日志记录器的名称 - 默认为模式
- `--level value`, `-l value`: 新日志记录器的日志级别
- `--stacktrace-level value`, `-L value`: 堆栈跟踪日志级别
- `--flags value`, `-F value`: 日志记录器的标志
- `--expression value`, `-e value`: 日志记录器的匹配表达式
- `--prefix value`, `-p value`: 日志记录器的前缀
- `--color`: 在日志中使用颜色
- `--filename value`, `-f value`: 日志记录器的文件名
- `--rotate`, `-r`: 轮转日志
- `--max-size value`, `-s value`: 在轮转之前的最大大小(以字节为单位)
- `--daily`, `-d`: 每天轮转日志
- `--max-days value`, `-D value`: 保留的每日日志的最大数量
- `--compress`, `-z`: 压缩轮转的日志
- `--compression-level value`, `-Z value`: 使用的压缩级别
- `conn`: 添加网络连接日志记录器
- 选项:
- `--group value`, `-g value`: 要添加日志记录器的组 - 默认为"default"
- `--name value`, `-n value`: 新日志记录器的名称 - 默认为模式
- `--level value`, `-l value`: 新日志记录器的日志级别
- `--stacktrace-level value`, `-L value`: 堆栈跟踪日志级别
- `--flags value`, `-F value`: 日志记录器的标志
- `--expression value`, `-e value`: 日志记录器的匹配表达式
- `--prefix value`, `-p value`: 日志记录器的前缀
- `--color`: 在日志中使用颜色
- `--reconnect-on-message`, `-R`: 对于每个消息重新连接主机
- `--reconnect`, `-r`: 连接中断时重新连接主机
- `--protocol value`, `-P value`: 设置要使用的协议tcp、unix或udp默认为tcp
- `--address value`, `-a value`: 要连接到的主机地址和端口(默认为:7020
- `smtp`: 添加SMTP日志记录器
- 选项:
- `--group value`, `-g value`: 要添加日志记录器的组 - 默认为"default"
- `--name value`, `-n value`: 新日志记录器的名称 - 默认为模式
- `--level value`, `-l value`: 新日志记录器的日志级别
- `--stacktrace-level value`, `-L value`: 堆栈跟踪日志级别
- `--flags value`, `-F value`: 日志记录器的标志
- `--expression value`, `-e value`: 日志记录器的匹配表达式
- `--prefix value`, `-p value`: 日志记录器的前缀
- `--color`: 在日志中使用颜色
- `--username value`, `-u value`: 邮件服务器用户名
- `--password value`, `-P value`: 邮件服务器密码
- `--host value`, `-H value`: 邮件服务器主机(默认为: 127.0.0.1:25
- `--send-to value`, `-s value`: 要发送到的电子邮件地址
- `--subject value`, `-S value`: 发送电子邮件的主题标题
- `processes`: 显示 Gitea 进程和 Goroutine 信息
- 选项:
- `--flat`: 以平面表格形式显示进程,而不是树形结构
- `--no-system`: 不显示系统进程
- `--stacktraces`: 显示与进程关联的 Goroutine 的堆栈跟踪
- `--json`: 输出为 JSON 格式
- `--cancel PID`: 向具有 PID 的进程发送取消命令(仅适用于非系统进程)
### dump-repo
`dump-repo` 从 Git/GitHub/Gitea/GitLab 中转储存储库数据:
- 选项:
- `--git_service service`Git 服务,可以是 `git`、`github`、`gitea`、`gitlab`。如果 `clone_addr` 可以被识别,则可以忽略此选项。
- `--repo_dir dir``-r dir`:存储数据的存储库目录路径。
- `--clone_addr addr`:将被克隆的 URL目前可以是 git/github/gitea/gitlab 的 http/https URL。例如https://github.com/lunny/tango.git
- `--auth_username lunny`:访问 `clone_addr` 的用户名。
- `--auth_password <password>`:访问 `clone_addr` 的密码。
- `--auth_token <token>`:访问 `clone_addr` 的个人令牌。
- `--owner_name lunny`:如果非空,数据将存储在具有所有者名称的目录中。
- `--repo_name tango`:如果非空,数据将存储在具有存储库名称的目录中。
- `--units <units>`:要迁移的项目,一个或多个项目应以逗号分隔。允许的项目有 wiki, issues, labels, releases, release_assets, milestones, pull_requests, comments。如果为空则表示所有项目。
### restore-repo
`restore-repo` 从磁盘目录中还原存储库数据:
- 选项:
- `--repo_dir dir``-r dir`:还原数据的存储库目录路径。
- `--owner_name lunny`:还原目标所有者名称。
- `--repo_name tango`:还原目标存储库名称。
- `--units <units>`:要还原的项目,一个或多个项目应以逗号分隔。允许的项目有 wiki, issues, labels, releases, release_assets, milestones, pull_requests, comments。如果为空则表示所有项目。
### actions generate-runner-token
生成一个供 Runner 使用的新令牌,用于向服务器注册。
- 选项:
- `--scope {owner}[/{repo}]``-s {owner}[/{repo}]`:限制 Runner 的范围,没有范围表示该 Runner 可用于所有仓库,但你也可以将其限制为特定的仓库或所有者。
要注册全局 Runner
```
gitea actions generate-runner-token
```
要注册特定组织的 Runner例如 `org`
```
gitea actions generate-runner-token -s org
```
要注册特定仓库的 Runner例如 `username/test-repo`
```
gitea actions generate-runner-token -s username/test-repo
```

View File

@ -5,6 +5,8 @@ slug: "config-cheat-sheet"
weight: 30
toc: false
draft: false
aliases:
- /en-us/config-cheat-sheet
menu:
sidebar:
parent: "administration"
@ -71,7 +73,7 @@ In addition there is _`StaticRootPath`_ which can be set as a built-in at build
- `RUN_USER`: **_current OS username_/`$USER`/`$USERNAME` e.g. git**: The user Gitea will run as.
This should be a dedicated system (non-user) account. Setting this incorrectly will cause Gitea
to not start.
- `RUN_MODE`: **prod**: Application run mode, affects performance and debugging. Either "dev", "prod" or "test".
- `RUN_MODE`: **prod**: Application run mode, affects performance and debugging: `dev` or `prod`, default is `prod`. Mode `dev` makes Gitea easier to develop and debug, values other than `dev` are treated as `prod` which is for production use.
## Repository (`repository`)
@ -87,16 +89,14 @@ In addition there is _`StaticRootPath`_ which can be set as a built-in at build
- `DEFAULT_PUSH_CREATE_PRIVATE`: **true**: Default private when creating a new repository with push-to-create.
- `MAX_CREATION_LIMIT`: **-1**: Global maximum creation limit of repositories per user,
`-1` means no limit.
- `PULL_REQUEST_QUEUE_LENGTH`: **1000**: Length of pull request patch test queue, make it. **DEPRECATED** use `LENGTH` in `[queue.pr_patch_checker]`.
as large as possible. Use caution when editing this value.
- `MIRROR_QUEUE_LENGTH`: **1000**: Patch test queue length, increase if pull request patch
testing starts hanging. **DEPRECATED** use `LENGTH` in `[queue.mirror]`.
- `PREFERRED_LICENSES`: **Apache License 2.0,MIT License**: Preferred Licenses to place at
the top of the list. Name must match file name in options/license or custom/options/license.
- `DISABLE_HTTP_GIT`: **false**: Disable the ability to interact with repositories over the
HTTP protocol.
- `USE_COMPAT_SSH_URI`: **false**: Force ssh:// clone url instead of scp-style uri when
default SSH port is used.
- `GO_GET_CLONE_URL_PROTOCOL`: **https**: Value for the "go get" request returns the repository url as https or ssh
default is https.
- `ACCESS_CONTROL_ALLOW_ORIGIN`: **\<empty\>**: Value for Access-Control-Allow-Origin header,
default is not to present. **WARNING**: This maybe harmful to you website if you do not
give it a right value.
@ -117,7 +117,7 @@ In addition there is _`StaticRootPath`_ which can be set as a built-in at build
### Repository - Editor (`repository.editor`)
- `LINE_WRAP_EXTENSIONS`: **.txt,.md,.markdown,.mdown,.mkd,**: List of file extensions for which lines should be wrapped in the Monaco editor. Separate extensions with a comma. To line wrap files without an extension, just put a comma
- `LINE_WRAP_EXTENSIONS`: **.txt,.md,.markdown,.mdown,.mkd,.livemd,**: List of file extensions for which lines should be wrapped in the Monaco editor. Separate extensions with a comma. To line wrap files without an extension, just put a comma
- `PREVIEWABLE_FILE_MODES`: **markdown**: Valid file modes that have a preview API associated with them, such as `api/v1/markdown`. Separate the values by commas. The preview tab in edit mode won't be displayed if the file extension doesn't match.
### Repository - Pull Request (`repository.pull-request`)
@ -141,6 +141,7 @@ In addition there is _`StaticRootPath`_ which can be set as a built-in at build
### Repository - Issue (`repository.issue`)
- `LOCK_REASONS`: **Too heated,Off-topic,Resolved,Spam**: A list of reasons why a Pull Request or Issue can be locked
- `MAX_PINNED`: **3**: Maximum number of pinned Issues per Repo. Set to 0 to disable pinning Issues.
### Repository - Upload (`repository.upload`)
@ -220,7 +221,6 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `SHOW_USER_EMAIL`: **true**: Whether the email of the user should be shown in the Explore Users page.
- `THEMES`: **auto,gitea,arc-green**: All available themes. Allow users select personalized themes.
regardless of the value of `DEFAULT_THEME`.
- `THEME_COLOR_META_TAG`: **#6cc644**: Value of `theme-color` meta tag, used by Android >= 5.0. An invalid color like "none" or "disable" will have the default style. More info: https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android
- `MAX_DISPLAY_FILE_SIZE`: **8388608**: Max size of files to be displayed (default is 8MiB)
- `REACTIONS`: All available reactions users can choose on issues/prs and comments
Values can be emoji alias (:smile:) or a unicode emoji.
@ -230,7 +230,6 @@ The following configuration set `Content-Type: application/vnd.android.package-a
add it to this config.
- `DEFAULT_SHOW_FULL_NAME`: **false**: Whether the full name of the users should be shown where possible. If the full name isn't set, the username will be used.
- `SEARCH_REPO_DESCRIPTION`: **true**: Whether to search within description at repository search on explore page.
- `USE_SERVICE_WORKER`: **false**: Whether to enable a Service Worker to cache frontend assets.
- `ONLY_SHOW_RELEVANT_REPOS`: **false** Whether to only show relevant repos on the explore page when no keyword is specified and default sorting is used.
A repo is considered irrelevant if it's a fork or if it has no metadata (no description, no icon, no topic).
@ -276,7 +275,8 @@ The following configuration set `Content-Type: application/vnd.android.package-a
trailing whitespace to paragraphs is not necessary to force a line break.
- `CUSTOM_URL_SCHEMES`: Use a comma separated list (ftp,git,svn) to indicate additional
URL hyperlinks to be rendered in Markdown. URLs beginning in http and https are
always displayed
always displayed. If this entry is empty, all URL schemes are allowed
- `FILE_EXTENSIONS`: **.md,.markdown,.mdown,.mkd,.livemd**: List of file extensions that should be rendered/edited as Markdown. Separate the extensions with a comma. To render files without any extension as markdown, just put a comma.
- `ENABLE_MATH`: **true**: Enables detection of `\(...\)`, `\[...\]`, `$...$` and `$$...$$` blocks as math blocks.
## Server (`server`)
@ -365,7 +365,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `LFS_START_SERVER`: **false**: Enables Git LFS support.
- `LFS_CONTENT_PATH`: **%(APP_DATA_PATH)s/lfs**: Default LFS content path. (if it is on local storage.) **DEPRECATED** use settings in `[lfs]`.
- `LFS_JWT_SECRET`: **\<empty\>**: LFS authentication secret, change this a unique string.
- `LFS_HTTP_AUTH_EXPIRY`: **20m**: LFS authentication validity period in time.Duration, pushes taking longer than this may fail.
- `LFS_HTTP_AUTH_EXPIRY`: **24h**: LFS authentication validity period in time.Duration, pushes taking longer than this may fail.
- `LFS_MAX_FILE_SIZE`: **0**: Maximum allowed LFS file size in bytes (Set to 0 for no limit).
- `LFS_LOCKS_PAGING_NUM`: **50**: Maximum number of LFS Locks returned per page.
@ -462,13 +462,9 @@ relation to port exhaustion.
- `ISSUE_INDEXER_CONN_STR`: ****: Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch, or meilisearch. i.e. http://elastic:changeme@localhost:9200
- `ISSUE_INDEXER_NAME`: **gitea_issues**: Issue indexer name, available when ISSUE_INDEXER_TYPE is elasticsearch
- `ISSUE_INDEXER_PATH`: **indexers/issues.bleve**: Index file used for issue search; available when ISSUE_INDEXER_TYPE is bleve and elasticsearch. Relative paths will be made absolute against _`AppWorkPath`_.
- The next 4 configuration values are deprecated and should be set in `queue.issue_indexer` however are kept for backwards compatibility:
- `ISSUE_INDEXER_QUEUE_TYPE`: **levelqueue**: Issue indexer queue, currently supports:`channel`, `levelqueue`, `redis`. **DEPRECATED** use settings in `[queue.issue_indexer]`.
- `ISSUE_INDEXER_QUEUE_DIR`: **queues/common**: When `ISSUE_INDEXER_QUEUE_TYPE` is `levelqueue`, this will be the path where the queue will be saved. **DEPRECATED** use settings in `[queue.issue_indexer]`. Relative paths will be made absolute against `%(APP_DATA_PATH)s`.
- `ISSUE_INDEXER_QUEUE_CONN_STR`: **addrs=127.0.0.1:6379 db=0**: When `ISSUE_INDEXER_QUEUE_TYPE` is `redis`, this will store the redis connection string. When `ISSUE_INDEXER_QUEUE_TYPE` is `levelqueue`, this is a directory or additional options of the form `leveldb://path/to/db?option=value&....`, and overrides `ISSUE_INDEXER_QUEUE_DIR`. **DEPRECATED** use settings in `[queue.issue_indexer]`.
- `ISSUE_INDEXER_QUEUE_BATCH_NUMBER`: **20**: Batch queue number. **DEPRECATED** use settings in `[queue.issue_indexer]`.
- `REPO_INDEXER_ENABLED`: **false**: Enables code search (uses a lot of disk space, about 6 times more than the repository size).
- `REPO_INDEXER_REPO_TYPES`: **sources,forks,mirrors,templates**: Repo indexer units. The items to index could be `sources`, `forks`, `mirrors`, `templates` or any combination of them separated by a comma. If empty then it defaults to `sources` only, as if you'd like to disable fully please see `REPO_INDEXER_ENABLED`.
- `REPO_INDEXER_TYPE`: **bleve**: Code search engine type, could be `bleve` or `elasticsearch`.
- `REPO_INDEXER_PATH`: **indexers/repos.bleve**: Index file used for code search.
- `REPO_INDEXER_CONN_STR`: ****: Code indexer connection string, available when `REPO_INDEXER_TYPE` is elasticsearch. i.e. http://elastic:changeme@localhost:9200
@ -477,7 +473,6 @@ relation to port exhaustion.
- `REPO_INDEXER_INCLUDE`: **empty**: A comma separated list of glob patterns (see https://github.com/gobwas/glob) to **include** in the index. Use `**.txt` to match any files with .txt extension. An empty list means include all files.
- `REPO_INDEXER_EXCLUDE`: **empty**: A comma separated list of glob patterns (see https://github.com/gobwas/glob) to **exclude** from the index. Files that match this list will not be indexed, even if they match in `REPO_INDEXER_INCLUDE`.
- `REPO_INDEXER_EXCLUDE_VENDORED`: **true**: Exclude vendored files from index.
- `UPDATE_BUFFER_LEN`: **20**: Buffer length of index request. **DEPRECATED** use settings in `[queue.issue_indexer]`.
- `MAX_FILE_SIZE`: **1048576**: Maximum size in bytes of files to be indexed.
- `STARTUP_TIMEOUT`: **30s**: If the indexer takes longer than this timeout to start - fail. (This timeout will be added to the hammer time above for child processes - as bleve will not start until the previous parent is shutdown.) Set to -1 to never timeout.
@ -485,23 +480,14 @@ relation to port exhaustion.
Configuration at `[queue]` will set defaults for queues with overrides for individual queues at `[queue.*]`. (However see below.)
- `TYPE`: **persistable-channel**: General queue type, currently support: `persistable-channel` (uses a LevelDB internally), `channel`, `level`, `redis`, `dummy`
- `DATADIR`: **queues/**: Base DataDir for storing persistent and level queues. `DATADIR` for individual queues can be set in `queue.name` sections but will default to `DATADIR/`**`common`**. (Previously each queue would default to `DATADIR/`**`name`**.) Relative paths will be made absolute against `%(APP_DATA_PATH)s`.
- `LENGTH`: **20**: Maximal queue size before channel queues block
- `TYPE`: **level**: General queue type, currently support: `level` (uses a LevelDB internally), `channel`, `redis`, `dummy`. Invalid types are treated as `level`.
- `DATADIR`: **queues/common**: Base DataDir for storing level queues. `DATADIR` for individual queues can be set in `queue.name` sections. Relative paths will be made absolute against `%(APP_DATA_PATH)s`.
- `LENGTH`: **100**: Maximal queue size before channel queues block
- `BATCH_LENGTH`: **20**: Batch data before passing to the handler
- `CONN_STR`: **redis://127.0.0.1:6379/0**: Connection string for the redis queue type. Options can be set using query params. Similarly LevelDB options can also be set using: **leveldb://relative/path?option=value** or **leveldb:///absolute/path?option=value**, and will override `DATADIR`
- `CONN_STR`: **redis://127.0.0.1:6379/0**: Connection string for the redis queue type. For `redis-cluster` use `redis+cluster://127.0.0.1:6379/0`. Options can be set using query params. Similarly, LevelDB options can also be set using: **leveldb://relative/path?option=value** or **leveldb:///absolute/path?option=value**, and will override `DATADIR`
- `QUEUE_NAME`: **_queue**: The suffix for default redis and disk queue name. Individual queues will default to **`name`**`QUEUE_NAME` but can be overridden in the specific `queue.name` section.
- `SET_NAME`: **_unique**: The suffix that will be added to the default redis and disk queue `set` name for unique queues. Individual queues will default to
**`name`**`QUEUE_NAME`_`SET_NAME`_ but can be overridden in the specific `queue.name` section.
- `WRAP_IF_NECESSARY`: **true**: Will wrap queues with a timeoutable queue if the selected queue is not ready to be created - (Only relevant for the level queue.)
- `MAX_ATTEMPTS`: **10**: Maximum number of attempts to create the wrapped queue
- `TIMEOUT`: **GRACEFUL_HAMMER_TIME + 30s**: Timeout the creation of the wrapped queue if it takes longer than this to create.
- Queues by default come with a dynamically scaling worker pool. The following settings configure this:
- `WORKERS`: **0**: Number of initial workers for the queue.
- `SET_NAME`: **_unique**: The suffix that will be added to the default redis and disk queue `set` name for unique queues. Individual queues will default to **`name`**`QUEUE_NAME`_`SET_NAME`_ but can be overridden in the specific `queue.name` section.
- `MAX_WORKERS`: **10**: Maximum number of worker go-routines for the queue.
- `BLOCK_TIMEOUT`: **1s**: If the queue blocks for this time, boost the number of workers - the `BLOCK_TIMEOUT` will then be doubled before boosting again whilst the boost is ongoing.
- `BOOST_TIMEOUT`: **5m**: Boost workers will timeout after this long.
- `BOOST_WORKERS`: **1**: This many workers will be added to the worker pool if there is a boost.
Gitea creates the following non-unique queues:
@ -519,21 +505,6 @@ And the following unique queues:
- `mirror`
- `pr_patch_checker`
Certain queues have defaults that override the defaults set in `[queue]` (this occurs mostly to support older configuration):
- `[queue.issue_indexer]`
- `TYPE` this will default to `[queue]` `TYPE` if it is set but if not it will appropriately convert `[indexer]` `ISSUE_INDEXER_QUEUE_TYPE` if that is set.
- `LENGTH` will default to `[indexer]` `UPDATE_BUFFER_LEN` if that is set.
- `BATCH_LENGTH` will default to `[indexer]` `ISSUE_INDEXER_QUEUE_BATCH_NUMBER` if that is set.
- `DATADIR` will default to `[indexer]` `ISSUE_INDEXER_QUEUE_DIR` if that is set.
- `CONN_STR` will default to `[indexer]` `ISSUE_INDEXER_QUEUE_CONN_STR` if that is set.
- `[queue.mailer]`
- `LENGTH` will default to **100** or whatever `[mailer]` `SEND_BUFFER_LEN` is.
- `[queue.pr_patch_checker]`
- `LENGTH` will default to **1000** or whatever `[repository]` `PULL_REQUEST_QUEUE_LENGTH` is.
- `[queue.mirror]`
- `LENGTH` will default to **1000** or whatever `[repository]` `MIRROR_QUEUE_LENGTH` is.
## Admin (`admin`)
- `DEFAULT_EMAIL_NOTIFICATIONS`: **enabled**: Default configuration for email notifications for users (user configurable). Options: enabled, onmention, disabled
@ -543,7 +514,7 @@ Certain queues have defaults that override the defaults set in `[queue]` (this o
- `INSTALL_LOCK`: **false**: Controls access to the installation page. When set to "true", the installation page is not accessible.
- `SECRET_KEY`: **\<random at every install\>**: Global secret key. This key is VERY IMPORTANT, if you lost it, the data encrypted by it (like 2FA secret) can't be decrypted anymore.
- `SECRET_KEY_URI`: **<empty>**: Instead of defining SECRET_KEY, this option can be used to use the key stored in a file (example value: `file:/etc/gitea/secret_key`). It shouldn't be lost like SECRET_KEY.
- `SECRET_KEY_URI`: **\<empty\>**: Instead of defining SECRET_KEY, this option can be used to use the key stored in a file (example value: `file:/etc/gitea/secret_key`). It shouldn't be lost like SECRET_KEY.
- `LOGIN_REMEMBER_DAYS`: **7**: Cookie lifetime, in days.
- `COOKIE_USERNAME`: **gitea\_awesome**: Name of the cookie used to store the current username.
- `COOKIE_REMEMBER_NAME`: **gitea\_incredible**: Name of cookie used to store authentication
@ -569,7 +540,7 @@ Certain queues have defaults that override the defaults set in `[queue]` (this o
- `ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET`: **true**: Set to `false` to allow local users to push to gitea-repositories without setting up the Gitea environment. This is not recommended and if you want local users to push to Gitea repositories you should set the environment appropriately.
- `IMPORT_LOCAL_PATHS`: **false**: Set to `false` to prevent all users (including admin) from importing local path on server.
- `INTERNAL_TOKEN`: **\<random at every install if no uri set\>**: Secret used to validate communication within Gitea binary.
- `INTERNAL_TOKEN_URI`: **<empty>**: Instead of defining INTERNAL_TOKEN in the configuration, this configuration option can be used to give Gitea a path to a file that contains the internal token (example value: `file:/etc/gitea/internal_token`)
- `INTERNAL_TOKEN_URI`: **\<empty\>**: Instead of defining INTERNAL_TOKEN in the configuration, this configuration option can be used to give Gitea a path to a file that contains the internal token (example value: `file:/etc/gitea/internal_token`)
- `PASSWORD_HASH_ALGO`: **pbkdf2**: The hash algorithm to use \[argon2, pbkdf2, pbkdf2_v1, pbkdf2_hi, scrypt, bcrypt\], argon2 and scrypt will spend significant amounts of memory.
- Note: The default parameters for `pbkdf2` hashing have changed - the previous settings are available as `pbkdf2_v1` but are not recommended.
- The hash functions may be tuned by using `$` after the algorithm:
@ -600,8 +571,8 @@ Certain queues have defaults that override the defaults set in `[queue]` (this o
## Camo (`camo`)
- `ENABLED`: **false**: Enable media proxy, we support images only at the moment.
- `SERVER_URL`: **<empty>**: URL of camo server, it **is required** if camo is enabled.
- `HMAC_KEY`: **<empty>**: Provide the HMAC key for encoding URLs, it **is required** if camo is enabled.
- `SERVER_URL`: **\<empty\>**: URL of camo server, it **is required** if camo is enabled.
- `HMAC_KEY`: **\<empty\>**: Provide the HMAC key for encoding URLs, it **is required** if camo is enabled.
- `ALLWAYS`: **false**: Set to true to use camo for both HTTP and HTTPS content, otherwise only non-HTTPS URLs are proxied
## OpenID (`openid`)
@ -680,9 +651,8 @@ Certain queues have defaults that override the defaults set in `[queue]` (this o
- `ENABLE_TIMETRACKING`: **true**: Enable Timetracking feature.
- `DEFAULT_ENABLE_TIMETRACKING`: **true**: Allow repositories to use timetracking by default.
- `DEFAULT_ALLOW_ONLY_CONTRIBUTORS_TO_TRACK_TIME`: **true**: Only allow users with write permissions to track time.
- `EMAIL_DOMAIN_WHITELIST`: **\<empty\>**: If non-empty, list of domain names that can only be used to register
on this instance.
- `EMAIL_DOMAIN_BLOCKLIST`: **\<empty\>**: If non-empty, list of domain names that cannot be used to register on this instance
- `EMAIL_DOMAIN_ALLOWLIST`: **\<empty\>**: If non-empty, comma separated list of domain names that can only be used to register on this instance, wildcard is supported.
- `EMAIL_DOMAIN_BLOCKLIST`: **\<empty\>**: If non-empty, comma separated list of domain names that cannot be used to register on this instance, wildcard is supported.
- `SHOW_REGISTRATION_BUTTON`: **! DISABLE\_REGISTRATION**: Show Registration Button
- `SHOW_MILESTONES_DASHBOARD_PAGE`: **true** Enable this to show the milestones dashboard page - a view of all the user's milestones
- `AUTO_WATCH_NEW_REPOS`: **true**: Enable this to let all organisation users watch new repos when they are created
@ -785,10 +755,11 @@ and
## Cache (`cache`)
- `ENABLED`: **true**: Enable the cache.
- `ADAPTER`: **memory**: Cache engine adapter, either `memory`, `redis`, `twoqueue` or `memcache`. (`twoqueue` represents a size limited LRU cache.)
- `ADAPTER`: **memory**: Cache engine adapter, either `memory`, `redis`, `redis-cluster`, `twoqueue` or `memcache`. (`twoqueue` represents a size limited LRU cache.)
- `INTERVAL`: **60**: Garbage Collection interval (sec), for memory and twoqueue cache only.
- `HOST`: **\<empty\>**: Connection string for `redis` and `memcache`. For `twoqueue` sets configuration for the queue.
- `HOST`: **\<empty\>**: Connection string for `redis`, `redis-cluster` and `memcache`. For `twoqueue` sets configuration for the queue.
- Redis: `redis://:macaron@127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
- Redis-cluster `redis+cluster://:macaron@127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
- Memcache: `127.0.0.1:9090;127.0.0.1:9091`
- TwoQueue LRU cache: `{"size":50000,"recent_ratio":0.25,"ghost_ratio":0.5}` or `50000` representing the maximum number of objects stored in the cache.
- `ITEM_TTL`: **16h**: Time to keep items in cache if not used, Setting it to -1 disables caching.
@ -801,7 +772,7 @@ and
## Session (`session`)
- `PROVIDER`: **memory**: Session engine provider \[memory, file, redis, db, mysql, couchbase, memcache, postgres\]. Setting `db` will reuse the configuration in `[database]`
- `PROVIDER`: **memory**: Session engine provider \[memory, file, redis, redis-cluster, db, mysql, couchbase, memcache, postgres\]. Setting `db` will reuse the configuration in `[database]`
- `PROVIDER_CONFIG`: **data/sessions**: For file, the root path; for db, empty (database config will be used); for others, the connection string. Relative paths will be made absolute against _`AppWorkPath`_.
- `COOKIE_SECURE`: **false**: Enable this to force using HTTPS for all session access.
- `COOKIE_NAME`: **i\_like\_gitea**: The name of the cookie used for the session ID.
@ -821,9 +792,10 @@ and
- `AVATAR_STORAGE_TYPE`: **default**: Storage type defined in `[storage.xxx]`. Default is `default` which will read `[storage]` if no section `[storage]` will be a type `local`.
- `AVATAR_UPLOAD_PATH`: **data/avatars**: Path to store user avatar image files.
- `AVATAR_MAX_WIDTH`: **4096**: Maximum avatar image width in pixels.
- `AVATAR_MAX_HEIGHT`: **3072**: Maximum avatar image height in pixels.
- `AVATAR_MAX_FILE_SIZE`: **1048576** (1Mb): Maximum avatar image file size in bytes.
- `AVATAR_RENDERED_SIZE_FACTOR`: **3**: The multiplication factor for rendered avatar images. Larger values result in finer rendering on HiDPI devices.
- `AVATAR_MAX_HEIGHT`: **4096**: Maximum avatar image height in pixels.
- `AVATAR_MAX_FILE_SIZE`: **1048576** (1MiB): Maximum avatar image file size in bytes.
- `AVATAR_MAX_ORIGIN_SIZE`: **262144** (256KiB): If the uploaded file is not larger than this byte size, the image will be used as is, without resizing/converting.
- `AVATAR_RENDERED_SIZE_FACTOR`: **2**: The multiplication factor for rendered avatar images. Larger values result in finer rendering on HiDPI devices.
- `REPOSITORY_AVATAR_STORAGE_TYPE`: **default**: Storage type defined in `[storage.xxx]`. Default is `default` which will read `[storage]` if no section `[storage]` will be a type `local`.
- `REPOSITORY_AVATAR_UPLOAD_PATH`: **data/repo-avatars**: Path to store repository avatar image files.
@ -862,22 +834,16 @@ Default templates for project boards:
## Log (`log`)
- `ROOT_PATH`: **\<empty\>**: Root path for log files.
- `MODE`: **console**: Logging mode. For multiple modes, use a comma to separate values. You can configure each mode in per mode log subsections `\[log.modename\]`. By default the file mode will log to `$ROOT_PATH/gitea.log`.
- `MODE`: **console**: Logging mode. For multiple modes, use a comma to separate values. You can configure each mode in per mode log subsections `\[log.writer-mode-name\]`.
- `LEVEL`: **Info**: General log level. \[Trace, Debug, Info, Warn, Error, Critical, Fatal, None\]
- `STACKTRACE_LEVEL`: **None**: Default log level at which to log create stack traces. \[Trace, Debug, Info, Warn, Error, Critical, Fatal, None\]
- `STACKTRACE_LEVEL`: **None**: Default log level at which to log create stack traces (rarely useful, do not set it). \[Trace, Debug, Info, Warn, Error, Critical, Fatal, None\]
- `ENABLE_SSH_LOG`: **false**: save ssh log to log file
- `ENABLE_XORM_LOG`: **true**: Set whether to perform XORM logging. Please note SQL statement logging can be disabled by setting `LOG_SQL` to false in the `[database]` section.
### Router Log (`log`)
- `DISABLE_ROUTER_LOG`: **false**: Mute printing of the router log.
- `ROUTER`: **console**: The mode or name of the log the router should log to. (If you set this to `,` it will log to default Gitea logger.)
NB: You must have `DISABLE_ROUTER_LOG` set to `false` for this option to take effect. Configure each mode in per mode log subsections `\[log.modename.router\]`.
- `logger.access.MODE`: **\<empty\>**: The "access" logger
- `logger.router.MODE`: **,**: The "router" logger, a single comma means it will use the default MODE above
- `logger.xorm.MODE`: **,**: The "xorm" logger
### Access Log (`log`)
- `ENABLE_ACCESS_LOG`: **false**: Creates an access.log in NCSA common log format, or as per the following template
- `ACCESS`: **file**: Logging mode for the access logger, use a comma to separate values. Configure each mode in per mode log subsections `\[log.modename.access\]`. By default the file mode will log to `$ROOT_PATH/access.log`. (If you set this to `,` it will log to the default Gitea logger.)
- `ACCESS_LOG_TEMPLATE`: **`{{.Ctx.RemoteHost}} - {{.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}}"`**: Sets the template used to create the access log.
- The following variables are available:
- `Ctx`: the `context.Context` of the request.
@ -885,31 +851,31 @@ Default templates for project boards:
- `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.
- You must be very careful to ensure that this template does not throw errors or panics as this template runs outside 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.*`)
### Log subsections (`log.<writer-mode-name>`)
- `LEVEL`: **log.LEVEL**: Sets the log-level of this sublogger. Defaults to the `LEVEL` set in the global `[log]` section.
- `MODE`: **name**: Sets the mode of this log writer - Defaults to the provided subsection name. This allows you to have two different file loggers at different levels.
- `LEVEL`: **log.LEVEL**: Sets the log-level of this writer. Defaults to the `LEVEL` set in the global `[log]` section.
- `STACKTRACE_LEVEL`: **log.STACKTRACE_LEVEL**: Sets the log level at which to log stack traces.
- `MODE`: **name**: Sets the mode of this sublogger - Defaults to the provided subsection name. This allows you to have two different file loggers at different levels.
- `EXPRESSION`: **""**: A regular expression to match either the function name, file or message. Defaults to empty. Only log messages that match the expression will be saved in the logger.
- `FLAGS`: **stdflags**: A comma separated string representing the log flags. Defaults to `stdflags` which represents the prefix: `2009/01/23 01:23:23 ...a/b/c/d.go:23:runtime.Caller() [I]: message`. `none` means don't prefix log lines. See `modules/log/flags.go` for more information.
- `PREFIX`: **""**: An additional prefix for every log line in this logger. Defaults to empty.
- `COLORIZE`: **false**: Whether to colorize the log lines
### Console log mode (`log.console`, `log.console.*`, or `MODE=console`)
### Console log mode (`log.console`, or `MODE=console`)
- For the console logger `COLORIZE` will default to `true` if not on windows or the terminal is determined to be able to color.
- `STDERR`: **false**: Use Stderr instead of Stdout.
### File log mode (`log.file`, `log.file.*` or `MODE=file`)
### File log mode (`log.file`, or `MODE=file`)
- `FILE_NAME`: Set the file name for this logger. Defaults as described above. If relative will be relative to the `ROOT_PATH`
- `FILE_NAME`: Set the file name for this logger. Defaults to `gitea.log` (exception: access log defaults to `access.log`). If relative will be relative to the `ROOT_PATH`
- `LOG_ROTATE`: **true**: Rotate the log files.
- `MAX_SIZE_SHIFT`: **28**: Maximum size shift of a single file, 28 represents 256Mb.
- `DAILY_ROTATE`: **true**: Rotate logs daily.
@ -917,21 +883,13 @@ Default templates for project boards:
- `COMPRESS`: **true**: Compress old log files by default with gzip
- `COMPRESSION_LEVEL`: **-1**: Compression level
### Conn log mode (`log.conn`, `log.conn.*` or `MODE=conn`)
### Conn log mode (`log.conn`, or `MODE=conn`)
- `RECONNECT_ON_MSG`: **false**: Reconnect host for every single message.
- `RECONNECT`: **false**: Try to reconnect when connection is lost.
- `PROTOCOL`: **tcp**: Set the protocol, either "tcp", "unix" or "udp".
- `ADDR`: **:7020**: Sets the address to connect to.
### SMTP log mode (`log.smtp`, `log.smtp.*` or `MODE=smtp`)
- `USER`: User email address to send from.
- `PASSWD`: Password for the smtp server.
- `HOST`: **127.0.0.1:25**: The SMTP host to connect to.
- `RECEIVERS`: Email addresses to send to.
- `SUBJECT`: **Diagnostic message from Gitea**
## Cron (`cron`)
- `ENABLED`: **false**: Enable to run all cron tasks periodically with default settings.
@ -1047,7 +1005,7 @@ Default templates for project boards:
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
- `NOTICE_ON_SUCCESS`: **false**: Set to true to switch on success notices.
- `SCHEDULE`: **@every 168h**: Cron syntax to set how often to check.
- `OLDER_THAN`: **@every 8760h**: any action older than this expression will be deleted from database, suggest using `8760h` (1 year) because that's the max length of heatmap.
- `OLDER_THAN`: **8760h**: any action older than this expression will be deleted from database, suggest using `8760h` (1 year) because that's the max length of heatmap.
#### Cron - Check for new Gitea versions (`cron.update_checker`)
@ -1063,7 +1021,7 @@ Default templates for project boards:
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
- `NO_SUCCESS_NOTICE`: **false**: Set to true to switch off success notices.
- `SCHEDULE`: **@every 168h**: Cron syntax to set how often to check.
- `OLDER_THAN`: **@every 8760h**: any system notice older than this expression will be deleted from database.
- `OLDER_THAN`: **8760h**: any system notice older than this expression will be deleted from database.
#### Cron - Garbage collect LFS pointers in repositories (`cron.gc_lfs`)
@ -1096,12 +1054,7 @@ Default templates for project boards:
- `DISABLE_CORE_PROTECT_NTFS`: **false** Set to true to forcibly set `core.protectNTFS` to false.
- `DISABLE_PARTIAL_CLONE`: **false** Disable the usage of using partial clones for git.
## Git - Reflog settings (`git.reflog`)
- `ENABLED`: **true** Set to true to enable Git to write changes to reflogs in each repo.
- `EXPIRATION`: **90** Reflog entry lifetime, in days. Entries are removed opportunistically by Git.
## Git - Timeout settings (`git.timeout`)
### Git - Timeout settings (`git.timeout`)
- `DEFAULT`: **360**: Git operations default timeout seconds.
- `MIGRATE`: **600**: Migrate external repositories timeout seconds.
@ -1110,6 +1063,15 @@ Default templates for project boards:
- `PULL`: **300**: Git pull from internal repositories timeout seconds.
- `GC`: **60**: Git repository GC timeout seconds.
### Git - Config options (`git.config`)
The key/value pairs in this section will be used as git config.
This section only does "set" config, a removed config key from this section won't be removed from git config automatically. The format is `some.configKey = value`.
- `diff.algorithm`: **histogram**
- `core.logAllRefUpdates`: **true**
- `gc.reflogExpire`: **90**
## Metrics (`metrics`)
- `ENABLED`: **false**: Enables /metrics endpoint for prometheus.
@ -1153,7 +1115,7 @@ Gitea can support Markup using external tools. The example below will add a mark
ENABLED = true
NEED_POSTPROCESS = true
FILE_EXTENSIONS = .adoc,.asciidoc
RENDER_COMMAND = "asciidoc --out-file=- -"
RENDER_COMMAND = "asciidoctor --embedded --safe-mode=secure --out-file=- -"
IS_INPUT_FILE = false
```
@ -1204,7 +1166,6 @@ in this mapping or the filetype using heuristics.
## Time (`time`)
- `FORMAT`: Time format to display on UI. i.e. RFC1123 or 2006-01-02 15:04:05
- `DEFAULT_UI_LOCATION`: Default location of time on the UI, so that we can display correct user's time on UI. i.e. Asia/Shanghai
## Task (`task`)
@ -1213,7 +1174,7 @@ Task queue configuration has been moved to `queue.task`. However, the below conf
- `QUEUE_TYPE`: **channel**: Task queue type, could be `channel` or `redis`.
- `QUEUE_LENGTH`: **1000**: Task queue length, available only when `QUEUE_TYPE` is `channel`.
- `QUEUE_CONN_STR`: **redis://127.0.0.1:6379/0**: Task queue connection string, available only when `QUEUE_TYPE` is `redis`. If redis needs a password, use `redis://123@127.0.0.1:6379/0`.
- `QUEUE_CONN_STR`: **redis://127.0.0.1:6379/0**: Task queue connection string, available only when `QUEUE_TYPE` is `redis`. If redis needs a password, use `redis://123@127.0.0.1:6379/0` or `redis+cluster://123@127.0.0.1:6379/0`.
## Migrations (`migrations`)
@ -1243,19 +1204,24 @@ Task queue configuration has been moved to `queue.task`. However, the below conf
- `CHUNKED_UPLOAD_PATH`: **tmp/package-upload**: Path for chunked uploads. Defaults to `APP_DATA_PATH` + `tmp/package-upload`
- `LIMIT_TOTAL_OWNER_COUNT`: **-1**: Maximum count of package versions a single owner can have (`-1` means no limits)
- `LIMIT_TOTAL_OWNER_SIZE`: **-1**: Maximum size of packages a single owner can use (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_ALPINE`: **-1**: Maximum size of an Alpine upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_CARGO`: **-1**: Maximum size of a Cargo upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_CHEF`: **-1**: Maximum size of a Chef upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_COMPOSER`: **-1**: Maximum size of a Composer upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_CONAN`: **-1**: Maximum size of a Conan upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_CONDA`: **-1**: Maximum size of a Conda upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_CONTAINER`: **-1**: Maximum size of a Container upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_CRAN`: **-1**: Maximum size of a CRAN upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_DEBIAN`: **-1**: Maximum size of a Debian upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_GENERIC`: **-1**: Maximum size of a Generic upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_GO`: **-1**: Maximum size of a Go upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_HELM`: **-1**: Maximum size of a Helm upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_MAVEN`: **-1**: Maximum size of a Maven upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_NPM`: **-1**: Maximum size of a npm upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_NUGET`: **-1**: Maximum size of a NuGet upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_PUB`: **-1**: Maximum size of a Pub upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_PYPI`: **-1**: Maximum size of a PyPI upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_RPM`: **-1**: Maximum size of a RPM upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_RUBYGEMS`: **-1**: Maximum size of a RubyGems upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_SWIFT`: **-1**: Maximum size of a Swift upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_VAGRANT`: **-1**: Maximum size of a Vagrant upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
@ -1391,7 +1357,6 @@ although Github don't support this form.
## Other (`other`)
- `SHOW_FOOTER_BRANDING`: **false**: Show Gitea branding in the footer.
- `SHOW_FOOTER_VERSION`: **true**: Show Gitea and Go version information in the footer.
- `SHOW_FOOTER_TEMPLATE_LOAD_TIME`: **true**: Show time of template execution in the footer.
- `ENABLE_SITEMAP`: **true**: Generate sitemap.

View File

@ -5,6 +5,8 @@ slug: "config-cheat-sheet"
weight: 30
toc: false
draft: false
aliases:
- /zh-cn/config-cheat-sheet
menu:
sidebar:
parent: "administration"
@ -41,7 +43,6 @@ menu:
- `DEFAULT_PRIVATE`: 默认创建的git工程为私有。 可以是`last`, `private``public`。默认值是 `last`表示用户最后创建的Repo的选择。
- `DEFAULT_PUSH_CREATE_PRIVATE`: **true**: 通过 ``push-to-create`` 方式创建的仓库是否默认为私有仓库.
- `MAX_CREATION_LIMIT`: 全局最大每个用户创建的git工程数目 `-1` 表示没限制。
- `PULL_REQUEST_QUEUE_LENGTH`: 小心:合并请求测试队列的长度,尽量放大。
### Repository - Release (`repository.release`)
@ -109,10 +110,6 @@ menu:
- `ISSUE_INDEXER_CONN_STR`: ****: 工单索引连接字符串,仅当 ISSUE_INDEXER_TYPE 为 `elasticsearch` 时有效。例如: http://elastic:changeme@localhost:9200
- `ISSUE_INDEXER_NAME`: **gitea_issues**: 工单索引名称,仅当 ISSUE_INDEXER_TYPE 为 `elasticsearch` 时有效。
- `ISSUE_INDEXER_PATH`: **indexers/issues.bleve**: 工单索引文件存放路径,当索引类型为 `bleve` 时有效。
- `ISSUE_INDEXER_QUEUE_TYPE`: **levelqueue**: 工单索引队列类型,当前支持 `channel` `levelqueue``redis`
- `ISSUE_INDEXER_QUEUE_DIR`: **indexers/issues.queue**: 当 `ISSUE_INDEXER_QUEUE_TYPE``levelqueue` 时,保存索引队列的磁盘路径。
- `ISSUE_INDEXER_QUEUE_CONN_STR`: **addrs=127.0.0.1:6379 db=0**: 当 `ISSUE_INDEXER_QUEUE_TYPE``redis`保存Redis队列的连接字符串。
- `ISSUE_INDEXER_QUEUE_BATCH_NUMBER`: **20**: 队列处理中批量提交数量。
- `REPO_INDEXER_ENABLED`: **false**: 是否启用代码搜索启用后会占用比较大的磁盘空间如果是bleve可能需要占用约6倍存储空间
- `REPO_INDEXER_TYPE`: **bleve**: 代码搜索引擎类型,可以为 `bleve` 或者 `elasticsearch`
@ -120,7 +117,6 @@ menu:
- `REPO_INDEXER_CONN_STR`: ****: 代码搜索引擎连接字符串,当 `REPO_INDEXER_TYPE``elasticsearch` 时有效。例如: http://elastic:changeme@localhost:9200
- `REPO_INDEXER_NAME`: **gitea_codes**: 代码搜索引擎的名字,当 `REPO_INDEXER_TYPE``elasticsearch` 时有效。
- `UPDATE_BUFFER_LEN`: **20**: 代码索引请求的缓冲区长度。
- `MAX_FILE_SIZE`: **1048576**: 进行解析的源代码文件的最大长度,小于该值时才会索引。
## Security (`security`)
@ -218,8 +214,8 @@ menu:
- `AVATAR_STORAGE_TYPE`: **local**: 头像存储类型,可以为 `local``minio`,分别支持本地文件系统和 minio 兼容的API。
- `AVATAR_UPLOAD_PATH`: **data/avatars**: 存储头像的文件系统路径。
- `AVATAR_MAX_WIDTH`: **4096**: 头像最大宽度,单位像素。
- `AVATAR_MAX_HEIGHT`: **3072**: 头像最大高度,单位像素。
- `AVATAR_MAX_FILE_SIZE`: **1048576** (1Mb): 头像最大大小。
- `AVATAR_MAX_HEIGHT`: **4096**: 头像最大高度,单位像素。
- `AVATAR_MAX_FILE_SIZE`: **1048576** (1MiB): 头像最大大小。
- `REPOSITORY_AVATAR_STORAGE_TYPE`: **local**: 仓库头像存储类型,可以为 `local``minio`,分别支持本地文件系统和 minio 兼容的API。
- `REPOSITORY_AVATAR_UPLOAD_PATH`: **data/repo-avatars**: 存储仓库头像的路径。
@ -341,7 +337,7 @@ test01.xls: application/vnd.ms-excel; charset=binary
ENABLED = false
NEED_POSTPROCESS = true
FILE_EXTENSIONS = .adoc,.asciidoc
RENDER_COMMAND = "asciidoc --out-file=- -"
RENDER_COMMAND = "asciidoctor --embedded --safe-mode=secure --out-file=- -"
IS_INPUT_FILE = false
```
@ -483,5 +479,4 @@ PROXY_HOSTS = *.github.com
## Other (`other`)
- `SHOW_FOOTER_BRANDING`: 为真则在页面底部显示Gitea的字样。
- `SHOW_FOOTER_VERSION`: 为真则在页面底部显示Gitea的版本。

View File

@ -5,6 +5,8 @@ slug: "customizing-gitea"
weight: 100
toc: false
draft: false
aliases:
- /en-us/customizing-gitea
menu:
sidebar:
parent: "administration"
@ -280,6 +282,22 @@ Place custom files in corresponding sub-folder under `custom/options`.
To add custom .gitignore, add a file with existing [.gitignore rules](https://git-scm.com/docs/gitignore) in it to `$GITEA_CUSTOM/options/gitignore`
## Customizing the git configuration
Starting with Gitea 1.20, you can customize the git configuration via the `git.config` section.
### Enabling signed git pushes
To enable signed git pushes, set these two options:
```ini
[git.config]
receive.advertisePushOptions = true
receive.certNonceSeed = <randomstring>
```
`certNonceSeed` should be set to a random string and be kept secret.
### 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`:

View File

@ -5,6 +5,8 @@ slug: "customizing-gitea"
weight: 100
toc: false
draft: false
aliases:
- /zh-cn/customizing-gitea
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "email-setup"
weight: 12
toc: false
draft: false
aliases:
- /en-us/email-setup
menu:
sidebar:
parent: "administration"

View File

@ -0,0 +1,91 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "Email 设置"
slug: "email-setup"
weight: 12
toc: false
draft: false
aliases:
- /zh-cn/email-setup
menu:
sidebar:
parent: "administration"
name: "Email 设置"
weight: 12
identifier: "email-setup"
---
# Email 设置
**目录**
{{< toc >}}
Gitea 具有邮件功能,用于发送事务性邮件(例如注册确认邮件)。它可以配置为使用 Sendmail或兼容的 MTA例如 Postfix 和 msmtp或直接使用 SMTP 服务器。
## 使用 Sendmail
使用 `sendmail` 命令作为邮件传输代理mailer
注意对于在官方Gitea Docker镜像中使用请使用SMTP版本进行配置请参考下一节
注意:对于面向互联网的网站,请查阅您的 MTA 文档以了解通过TLS发送邮件的说明。同时设置 SPF、DMARC 和 DKIM DNS 记录,以使发送的邮件被各个电子邮件提供商接受为合法邮件。
```ini
[mailer]
ENABLED = true
FROM = gitea@mydomain.com
MAILER_TYPE = sendmail
SENDMAIL_PATH = /usr/sbin/sendmail
SENDMAIL_ARGS = "--" ; 大多数 "sendmail" 程序都接受选项,使用 "--" 将防止电子邮件地址被解释为选项。
```
## 使用 SMTP
直接使用 SMTP 服务器作为中继。如果您不想在实例上设置 MTA但在电子邮件提供商那里有一个帐户这个选项非常有用。
```ini
[mailer]
ENABLED = true
FROM = gitea@mydomain.com
MAILER_TYPE = smtp
SMTP_ADDR = mail.mydomain.com
SMTP_PORT = 587
IS_TLS_ENABLED = true
USER = gitea@mydomain.com
PASSWD = `password`
```
重启 Gitea 以使配置更改生效。
要发送测试邮件以验证设置,请转到 Gitea > 站点管理 > 配置 > SMTP 邮件配置。
有关所有选项的完整列表,请查看[配置速查表](doc/administration/config-cheat-sheet.zh-cn.md)。
请注意:只有在使用 TLS 或 `HOST=localhost` 加密 SMTP 服务器通信时才支持身份验证。TLS 加密可以通过以下方式进行:
- 通过端口 587 的 STARTTLS也称为 Opportunistic TLS。初始连接是明文的但如果服务器支持则可以升级为 TLS。
- 通过默认端口 465 的 SMTPS 连接。连接到服务器从一开始就使用 TLS。
- 使用 `IS_TLS_ENABLED=true` 进行强制的 SMTPS 连接。(这两种方式都被称为 Implicit TLS
这是由于 Go 内部库对 STRIPTLS 攻击的保护机制。
请注意自2018年起[RFC8314](https://tools.ietf.org/html/rfc8314#section-3) 推荐使用 Implicit TLS。
### Gmail
以下配置应该适用于 Gmail 的 SMTP 服务器:
```ini
[mailer]
ENABLED = true
HOST = smtp.gmail.com:465 ; 对于 Gitea >= 1.18.0,删除此行
SMTP_ADDR = smtp.gmail.com
SMTP_PORT = 465
FROM = example.user@gmail.com
USER = example.user
PASSWD = `***`
MAILER_TYPE = smtp
IS_TLS_ENABLED = true
```
请注意,您需要创建并使用一个 [应用密码](https://support.google.com/accounts/answer/185833?hl=en) 并在您的 Google 帐户上启用 2FA。您将无法直接使用您的 Google 帐户密码。

View File

@ -5,6 +5,8 @@ slug: "environment-variables"
weight: 10
toc: false
draft: false
aliases:
- /en-us/environment-variables
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "environment-variables"
weight: 10
toc: false
draft: false
aliases:
- /zh-cn/environment-variables
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "external-renderers"
weight: 60
toc: false
draft: false
aliases:
- /en-us/external-renderers
menu:
sidebar:
parent: "administration"

View File

@ -0,0 +1,207 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "外部渲染器"
slug: "external-renderers"
weight: 60
toc: false
draft: false
aliases:
- /zh-cn/external-renderers
menu:
sidebar:
parent: "administration"
name: "外部渲染器"
weight: 60
identifier: "external-renderers"
---
# 自定义文件渲染配置
**目录**
{{< toc >}}
Gitea 通过外部二进制文件支持自定义文件渲染(例如 Jupyter notebooks、asciidoc 等),只需要进行以下步骤:
- 安装外部二进制文件
- 在您的 `app.ini` 文件中添加一些配置
- 重新启动 Gitea 实例
此功能支持整个文件的渲染。如果您想要在 Markdown 中渲染代码块,您需要使用 JavaScript 进行一些操作。请参阅 [自定义 Gitea 配置]({{< relref "doc/administration/customizing-gitea.zh-cn.md" >}}) 页面上的一些示例。
## 安装外部二进制文件
为了通过外部二进制文件进行文件渲染,必须安装它们的关联软件包。
如果您正在使用 Docker 镜像,则您的 `Dockerfile` 应该包含以下内容:
```docker
FROM gitea/gitea:{{< version >}}
[...]
COPY custom/app.ini /data/gitea/conf/app.ini
[...]
RUN apk --no-cache add asciidoctor freetype freetype-dev gcc g++ libpng libffi-dev py-pip python3-dev py3-pip py3-pyzmq
# 安装其他您需要的外部渲染器的软件包
RUN pip3 install --upgrade pip
RUN pip3 install -U setuptools
RUN pip3 install jupyter docutils
# 在上面添加您需要安装的任何其他 Python 软件包
```
## `app.ini` 文件配置
在您的自定义 `app.ini` 文件中为每个外部渲染器添加一个 `[markup.XXXXX]` 部分:
```ini
[markup.asciidoc]
ENABLED = true
FILE_EXTENSIONS = .adoc,.asciidoc
RENDER_COMMAND = "asciidoctor -s -a showtitle --out-file=- -"
; 输入不是标准输入而是文件
IS_INPUT_FILE = false
[markup.jupyter]
ENABLED = true
FILE_EXTENSIONS = .ipynb
RENDER_COMMAND = "jupyter nbconvert --stdin --stdout --to html --template basic"
IS_INPUT_FILE = false
[markup.restructuredtext]
ENABLED = true
FILE_EXTENSIONS = .rst
RENDER_COMMAND = "timeout 30s pandoc +RTS -M512M -RTS -f rst"
IS_INPUT_FILE = false
```
如果您的外部标记语言依赖于在生成的 HTML 元素上的额外类和属性您可能需要启用自定义的清理策略。Gitea 使用 [`bluemonday`](https://godoc.org/github.com/microcosm-cc/bluemonday) 包作为我们的 HTML 清理器。下面的示例可以用于支持从 [`pandoc`](https://pandoc.org/) 输出的服务器端 [KaTeX](https://katex.org/) 渲染结果。
```ini
[markup.sanitizer.TeX]
; Pandoc 渲染 TeX 段落为带有 "math" 类的 <span> 元素,根据上下文可能还带有 "inline" 或 "display" 类。
; - 请注意,这与我们的 Markdown 解析器中内置的数学支持不同,后者使用 <code> 元素。
ELEMENT = span
ALLOW_ATTR = class
REGEXP = ^\s*((math(\s+|$)|inline(\s+|$)|display(\s+|$)))+
[markup.markdown]
ENABLED = true
FILE_EXTENSIONS = .md,.markdown
RENDER_COMMAND = pandoc -f markdown -t html --katex
```
您必须在每个部分中定义 `ELEMENT``ALLOW_ATTR`
要定义多个条目,请添加唯一的字母数字后缀(例如,`[markup.sanitizer.1]` 和 `[markup.sanitizer.something]`)。
要仅为特定的外部渲染器应用清理规则,它们必须使用渲染器名称,例如 `[markup.sanitizer.asciidoc.rule-1]`、`[markup.sanitizer.<renderer>.rule-1]`。
**注意**:如果规则在渲染器 ini 部分之前定义,或者名称与渲染器不匹配,它将应用于所有渲染器。
完成配置更改后,请重新启动 Gitea 以使更改生效。
**注意**:在 Gitea 1.12 之前,存在一个名为 `markup.sanitiser` 的单个部分,其中的键被重新定义为多个规则,但是,这种配置方法存在重大问题,需要通过多个部分进行配置。
### 示例HTML
直接渲染 HTML 文件:
```ini
[markup.html]
ENABLED = true
FILE_EXTENSIONS = .html,.htm
RENDER_COMMAND = cat
; 输入不是标准输入,而是文件
IS_INPUT_FILE = true
[markup.sanitizer.html.1]
ELEMENT = div
ALLOW_ATTR = class
[markup.sanitizer.html.2]
ELEMENT = a
ALLOW_ATTR = class
```
请注意:此示例中的配置将允许渲染 HTML 文件,并使用 `cat` 命令将文件内容输出为 HTML。此外配置中的两个清理规则将允许 `<div>``<a>` 元素使用 `class` 属性。
在进行配置更改后,请重新启动 Gitea 以使更改生效。
### 示例Office DOCX
使用 [`pandoc`](https://pandoc.org/) 显示 Office DOCX 文件:
```ini
[markup.docx]
ENABLED = true
FILE_EXTENSIONS = .docx
RENDER_COMMAND = "pandoc --from docx --to html --self-contained --template /path/to/basic.html"
[markup.sanitizer.docx.img]
ALLOW_DATA_URI_IMAGES = true
```
在此示例中,配置将允许显示 Office DOCX 文件,并使用 `pandoc` 命令将文件转换为 HTML 格式。同时,清理规则中的 `ALLOW_DATA_URI_IMAGES` 设置为 `true`,允许使用 Data URI 格式的图片。
模板文件的内容如下:
```
$body$
```
### 示例Jupyter Notebook
使用 [`nbconvert`](https://github.com/jupyter/nbconvert) 显示 Jupyter Notebook 文件:
```ini
[markup.jupyter]
ENABLED = true
FILE_EXTENSIONS = .ipynb
RENDER_COMMAND = "jupyter-nbconvert --stdin --stdout --to html --template basic"
[markup.sanitizer.jupyter.img]
ALLOW_DATA_URI_IMAGES = true
```
在此示例中,配置将允许显示 Jupyter Notebook 文件,并使用 `nbconvert` 命令将文件转换为 HTML 格式。同样,清理规则中的 `ALLOW_DATA_URI_IMAGES` 设置为 `true`,允许使用 Data URI 格式的图片。
在进行配置更改后,请重新启动 Gitea 以使更改生效。
## 自定义 CSS
`.ini` 文件中,可以使用 `[markup.XXXXX]` 的格式指定外部渲染器,并且由外部渲染器生成的 HTML 将被包装在一个带有 `markup``XXXXX` 类的 `<div>` 中。`markup` 类提供了预定义的样式(如果 `XXXXX``markdown`,则使用 `markdown` 类)。否则,您可以使用这些类来针对渲染的 HTML 内容进行定制样式。
因此,您可以编写一些 CSS 样式:
```css
.markup.XXXXX html {
font-size: 100%;
overflow-y: scroll;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
.markup.XXXXX body {
color: #444;
font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif;
font-size: 12px;
line-height: 1.7;
padding: 1em;
margin: auto;
max-width: 42em;
background: #fefefe;
}
.markup.XXXXX p {
color: orangered;
}
```
将您的样式表添加到自定义目录中,例如 `custom/public/css/my-style-XXXXX.css`,并使用自定义的头文件 `custom/templates/custom/header.tmpl` 进行导入:
```html
<link rel="stylesheet" href="{{AppSubUrl}}/assets/css/my-style-XXXXX.css" />
```
通过以上步骤,您可以将自定义的 CSS 样式应用到特定的外部渲染器,使其具有所需的样式效果。

View File

@ -5,6 +5,8 @@ slug: "fail2ban-setup"
weight: 16
toc: false
draft: false
aliases:
- /en-us/fail2ban-setup
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "fail2ban-setup"
weight: 16
toc: false
draft: false
aliases:
- /zh-cn/fail2ban-setup
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "git-lfs-setup"
weight: 12
toc: false
draft: false
aliases:
- /en-us/git-lfs-setup
menu:
sidebar:
parent: "administration"

View File

@ -0,0 +1,32 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "Git LFS 设置"
slug: "git-lfs-setup"
weight: 12
toc: false
draft: false
aliases:
- /zh-cn/git-lfs-setup
menu:
sidebar:
parent: "administration"
name: "Git LFS 设置"
weight: 12
identifier: "git-lfs-setup"
---
# 配置 Git 大文件存储Large File StorageLFS
要使用 Gitea 内置的 LFS 支持,您需要更新 `app.ini` 文件:
```ini
[server]
; 启用 git-lfs 支持。true 或 false默认为 false。
LFS_START_SERVER = true
[lfs]
; 存放 LFS 文件的路径,默认为 data/lfs。
PATH = /home/gitea/data/lfs
```
**注意**LFS 服务器支持需要服务器上安装 Git v2.1.2 以上版本。

View File

@ -5,6 +5,8 @@ slug: "https-setup"
weight: 12
toc: false
draft: false
aliases:
- /en-us/https-setup
menu:
sidebar:
parent: "administration"

View File

@ -1,6 +1,6 @@
---
date: "2023-04-09T11:00:00+02:00"
title: "使用: HTTPS配置"
title: "HTTPS配置"
slug: "https-setup"
weight: 12
toc: false

View File

@ -0,0 +1,295 @@
---
date: "2019-04-02T17:06:00+01:00"
title: "Logging Configuration"
slug: "logging-config"
weight: 40
toc: false
draft: false
aliases:
- /en-us/logging-configuration
menu:
sidebar:
parent: "administration"
name: "Logging Configuration"
weight: 40
identifier: "logging-config"
---
# Logging Configuration
The logging configuration of Gitea mainly consists of 3 types of components:
- The `[log]` section for general configuration
- `[log.<mode-name>]` sections for the configuration of different log writers to output logs, aka: "writer mode", the mode name is also used as "writer name".
- The `[log]` section can also contain sub-logger configurations following the key schema `logger.<logger-name>.<CONFIG-KEY>`
There is a fully functional log output by default, so it is not necessary to define one.
**Table of Contents**
{{< toc >}}
## Collecting Logs for Help
To collect logs for help and issue report, see [Support Options]({{< relref "doc/help/support.en-us.md" >}}).
## The `[log]` section
Configuration of logging facilities in Gitea happen in the `[log]` section and its subsections.
In the top level `[log]` section the following configurations can be placed:
- `ROOT_PATH`: (Default: **%(GITEA_WORK_DIR)/log**): Base path for log files
- `MODE`: (Default: **console**) List of log outputs to use for the Default logger.
- `LEVEL`: (Default: **Info**) Least severe log events to persist, case-insensitive. Possible values are: `Trace`, `Debug`, `Info`, `Warn`, `Error`, `Fatal`.
- `STACKTRACE_LEVEL`: (Default: **None**) For this and more severe events the stacktrace will be printed upon getting logged.
And it can contain the following sub-loggers:
- `logger.router.MODE`: (Default: **,**): List of log outputs to use for the Router logger.
- `logger.access.MODE`: (Default: **\<empty\>**) List of log outputs to use for the Access logger. By default, the access logger is disabled.
- `logger.xorm.MODE`: (Default: **,**) List of log outputs to use for the XORM logger.
Setting a comma (`,`) to sub-logger's mode means making it use the default global `MODE`.
## Quick samples
### Default (empty) Configuration
The empty configuration is equivalent to default:
```ini
[log]
ROOT_PATH = %(GITEA_WORK_DIR)/log
MODE = console
LEVEL = Info
STACKTRACE_LEVEL = None
logger.router.MODE = ,
logger.xorm.MODE = ,
logger.access.MODE =
; this is the config options of "console" mode (used by MODE=console above)
[log.console]
MODE = console
FLAGS = stdflags
PREFIX =
COLORIZE = true
```
This is equivalent to sending all logs to the console, with default Golang log being sent to the console log too.
This is only a sample, and it is the default, do not need to write it into your configuration file.
### Disable Router logs and record some access logs to file
The Router logger is disabled, the access logs (>=Warn) goes into `access.log`:
```ini
[log]
logger.router.MODE =
logger.access.MODE = access-file
[log.access-file]
MODE = file
LEVEL = Warn
FILE_NAME = access.log
```
### Set different log levels for different modes
Default logs (>=Warn) goes into `gitea.log`, while Error logs goes into `file-error.log`:
```ini
[log]
LEVEL = Warn
MODE = file, file-error
; by default, the "file" mode will record logs to %(log.ROOT_PATH)/gitea.log, so we don't need to set it
; [log.file]
[log.file-error]
LEVEL = Error
FILE_NAME = file-error.log
```
## Log outputs (mode and writer)
Gitea provides the following log output writers:
- `console` - Log to `stdout` (or `stderr` if it is set in the config)
- `file` - Log to a file
- `conn` - Log to a socket (network or unix)
### Common configuration
Certain configuration is common to all modes of log output:
- `MODE` is the mode of the log output writer. It will default to the mode name in the ini section. Thus `[log.console]` will default to `MODE = console`.
- `LEVEL` is the lowest level that this output will log.
- `STACKTRACE_LEVEL` is the lowest level that this output will print a stacktrace.
- `COLORIZE` will default to `true` for `console` as described, otherwise it will default to `false`.
#### `EXPRESSION`
`EXPRESSION` represents a regular expression that log events must match to be logged by the output writer.
Either the log message, (with colors removed), must match or the `longfilename:linenumber:functionname` must match.
NB: the whole message or string doesn't need to completely match.
Please note this expression will be run in the writer's goroutine but not the logging event goroutine.
#### `FLAGS`
`FLAGS` represents the preceding logging context information that is
printed before each message. It is a comma-separated string set. The order of values does not matter.
It defaults to `stdflags` (= `date,time,medfile,shortfuncname,levelinitial`)
Possible values are:
- `none` or `,` - No flags.
- `date` - the date in the local time zone: `2009/01/23`.
- `time` - the time in the local time zone: `01:23:23`.
- `microseconds` - microsecond resolution: `01:23:23.123123`. Assumes time.
- `longfile` - full file name and line number: `/a/b/c/d.go:23`.
- `shortfile` - final file name element and line number: `d.go:23`.
- `funcname` - function name of the caller: `runtime.Caller()`.
- `shortfuncname` - last part of the function name. Overrides `funcname`.
- `utc` - if date or time is set, use UTC rather than the local time zone.
- `levelinitial` - initial character of the provided level in brackets eg. `[I]` for info.
- `level` - level in brackets `[INFO]`.
- `gopid` - the Goroutine-PID of the context.
- `medfile` - last 20 characters of the filename - equivalent to `shortfile,longfile`.
- `stdflags` - equivalent to `date,time,medfile,shortfuncname,levelinitial`.
### Console mode
In this mode the logger will forward log messages to the stdout and
stderr streams attached to the Gitea process.
For loggers in console mode, `COLORIZE` will default to `true` if not
on windows, or the Windows terminal can be set into ANSI mode or is a
cygwin or Msys pipe.
Settings:
- `STDERR`: **false**: Whether the logger should print to `stderr` instead of `stdout`.
### File mode
In this mode the logger will save log messages to a file.
Settings:
- `FILE_NAME`: The file to write the log events to, relative to `ROOT_PATH`, Default to `%(ROOT_PATH)/gitea.log`. Exception: access log will default to `%(ROOT_PATH)/access.log`.
- `MAX_SIZE_SHIFT`: **28**: Maximum size shift of a single file. 28 represents 256Mb. For details see below.
- `LOG_ROTATE` **true**: Whether to rotate the log files. TODO: if false, will it delete instead on daily rotate, or do nothing?.
- `DAILY_ROTATE`: **true**: Whether to rotate logs daily.
- `MAX_DAYS`: **7**: Delete rotated log files after this number of days.
- `COMPRESS`: **true**: Whether to compress old log files by default with gzip.
- `COMPRESSION_LEVEL`: **-1**: Compression level. For details see below.
`MAX_SIZE_SHIFT` defines the maximum size of a file by left shifting 1 the given number of times (`1 << x`).
The exact behavior at the time of v1.17.3 can be seen [here](https://github.com/go-gitea/gitea/blob/v1.17.3/modules/setting/log.go#L185).
The useful values of `COMPRESSION_LEVEL` are from 1 to (and including) 9, where higher numbers mean better compression.
Beware that better compression might come with higher resource usage.
Must be preceded with a `-` sign.
### Conn mode
In this mode the logger will send log messages over a network socket.
Settings:
- `ADDR`: **:7020**: Sets the address to connect to.
- `PROTOCOL`: **tcp**: Set the protocol, either "tcp", "unix" or "udp".
- `RECONNECT`: **false**: Try to reconnect when connection is lost.
- `RECONNECT_ON_MSG`: **false**: Reconnect host for every single message.
### The "Router" logger
The Router logger logs the following message types when Gitea's route handlers work:
- `started` messages will be logged at TRACE level
- `polling`/`completed` routers will be logged at INFO. Exception: "/assets" static resource requests are also logged at TRACE.
- `slow` routers will be logged at WARN
- `failed` routers will be logged at WARN
### The "XORM" logger
To make XORM outputs SQL logs, the `LOG_SQL` in `[database]` section should also be set to `true`.
### The "Access" logger
The Access logger is a new logger since Gitea 1.9. It provides a NCSA
Common Log compliant log format. It's highly configurable but caution
should be taken when changing its template. The main benefit of this
logger is that Gitea can now log accesses in a standard log format so
standard tools may be used.
You can enable this logger using `logger.access.MODE = ...`.
If desired the format of the Access logger can be changed by changing
the value of the `ACCESS_LOG_TEMPLATE`.
Please note, the access logger will log at `INFO` level, setting the
`LEVEL` of this logger to `WARN` or above will result in no access logs.
#### The ACCESS_LOG_TEMPLATE
This value represents a go template. Its default value is
```tmpl
{{.Ctx.RemoteHost}} - {{.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}}"`
```
The template is passed following options:
- `Ctx` is the `context.Context`
- `Identity` is the `SignedUserName` or `"-"` if the user is not logged in
- `Start` is the start time of the request
- `ResponseWriter` is the `http.ResponseWriter`
Caution must be taken when changing this template as it runs outside of
the standard panic recovery trap. The template should also be as simple
as it runs for every request.
## Releasing-and-Reopening, Pausing and Resuming logging
If you are running on Unix you may wish to release-and-reopen logs in order to use `logrotate` or other tools.
It is possible force Gitea to release and reopen it's logging files and connections by sending `SIGUSR1` to the
running process, or running `gitea manager logging release-and-reopen`.
Alternatively, you may wish to pause and resume logging - this can be accomplished through the use of the
`gitea manager logging pause` and `gitea manager logging resume` commands. Please note that whilst logging
is paused log events below INFO level will not be stored and only a limited number of events will be stored.
Logging may block, albeit temporarily, slowing Gitea considerably whilst paused - therefore it is
recommended that pausing only done for a very short period of time.
## Adding and removing logging whilst Gitea is running
It is possible to add and remove logging whilst Gitea is running using the `gitea manager logging add` and `remove` subcommands.
This functionality can only adjust running log systems and cannot be used to start the access or router loggers if they
were not already initialized. If you wish to start these systems you are advised to adjust the app.ini and (gracefully) restart
the Gitea service.
The main intention of these commands is to easily add a temporary logger to investigate problems on running systems where a restart
may cause the issue to disappear.
## Using `logrotate` instead of built-in log rotation
Gitea includes built-in log rotation, which should be enough for most deployments. However, if you instead want to use the `logrotate` utility:
- Disable built-in log rotation by setting `LOG_ROTATE` to `false` in your `app.ini`.
- Install `logrotate`.
- Configure `logrotate` to match your deployment requirements, see `man 8 logrotate` for configuration syntax details.
In the `postrotate/endscript` block send Gitea a `USR1` signal via `kill -USR1` or `kill -10` to the `gitea` process itself,
or run `gitea manager logging release-and-reopen` (with the appropriate environment).
Ensure that your configurations apply to all files emitted by Gitea loggers as described in the above sections.
- Always do `logrotate /etc/logrotate.conf --debug` to test your configurations.
- If you are using docker and are running from outside the container you can use
`docker exec -u $OS_USER $CONTAINER_NAME sh -c 'gitea manager logging release-and-reopen'`
or `docker exec $CONTAINER_NAME sh -c '/bin/s6-svc -1 /etc/s6/gitea/'` or send `USR1` directly to the Gitea process itself.
The next `logrotate` jobs will include your configurations, so no restart is needed.
You can also immediately reload `logrotate` with `logrotate /etc/logrotate.conf --force`.

View File

@ -0,0 +1,276 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "日志配置"
slug: "logging-config"
weight: 40
toc: false
draft: false
aliases:
- /zh-cn/logging-configuration
menu:
sidebar:
parent: "administration"
name: "日志配置"
weight: 40
identifier: "logging-config"
---
# 日志配置
Gitea 的日志配置主要由以下三种类型的组件组成:
- `[log]` 部分用于一般配置
- `[log.<mode-name>]` 部分用于配置不同的日志输出方式,也称为 "writer mode",模式名称同时也作为 "writer name"
- `[log]` 部分还可以包含遵循 `logger.<logger-name>.<CONFIG-KEY>` 模式的子日志记录器的配置
默认情况下,已经有一个完全功能的日志输出,因此不需要重新定义。
**目录**
{{< toc >}}
## 收集日志以获取帮助
要收集日志以获取帮助和报告问题,请参阅 [需要帮助]({{< relref "doc/help/support.zh-cn.md" >}})。
## `[log]` 部分
在 Gitea 中,日志设施的配置在 `[log]` 部分及其子部分。
在顶层的 `[log]` 部分,可以放置以下配置项:
- `ROOT_PATH`:(默认值:**%(GITEA_WORK_DIR)/log**):日志文件的基本路径。
- `MODE`:(默认值:**console**):要用于默认日志记录器的日志输出列表。
- `LEVEL`:(默认值:**Info**):要持久化的最严重的日志事件,不区分大小写。可能的值为:`Trace`、`Debug`、`Info`、`Warn`、`Error`、`Fatal`。
- `STACKTRACE_LEVEL`:(默认值:**None**):对于此类及更严重的事件,将在记录时打印堆栈跟踪。
它还可以包含以下子日志记录器:
- `logger.router.MODE`:(默认值:**,**):用于路由器日志记录器的日志输出列表。
- `logger.access.MODE`:(默认值:**\<empty\>**):用于访问日志记录器的日志输出列表。默认情况下,访问日志记录器被禁用。
- `logger.xorm.MODE`:(默认值:**,**):用于 XORM 日志记录器的日志输出列表。
将子日志记录器的模式设置为逗号(`,`)表示使用默认的全局 `MODE`
## 快速示例
### 默认(空)配置
空配置等同于默认配置:
```ini
[log]
ROOT_PATH = %(GITEA_WORK_DIR)/log
MODE = console
LEVEL = Info
STACKTRACE_LEVEL = None
logger.router.MODE = ,
logger.xorm.MODE = ,
logger.access.MODE =
; 这是“控制台”模式的配置选项(由上面的 MODE=console 使用)
[log.console]
MODE = console
FLAGS = stdflags
PREFIX =
COLORIZE = true
```
这等同于将所有日志发送到控制台,并将默认的 Golang 日志也发送到控制台日志中。
这只是一个示例,默认情况下不需要将其写入配置文件中。
### 禁用路由日志并将一些访问日志记录到文件中
禁用路由日志,将访问日志(>=Warn记录到 `access.log` 中:
```ini
[log]
logger.router.MODE =
logger.access.MODE = access-file
[log.access-file]
MODE = file
LEVEL = Warn
FILE_NAME = access.log
```
### 为不同的模式设置不同的日志级别
将默认日志(>=Warn记录到 `gitea.log` 中,将错误日志记录到 `file-error.log` 中:
```ini
[log]
LEVEL = Warn
MODE = file, file-error
; 默认情况下,"file" 模式会将日志记录到 %(log.ROOT_PATH)/gitea.log因此我们不需要设置它
; [log.file]
[log.file-error]
LEVEL = Error
FILE_NAME = file-error.log
```
## 日志输出(模式和写入器)
Gitea 提供以下日志写入器:
- `console` - 输出日志到 `stdout`(或 `stderr`,如果已在配置中设置)
- `file` - 输出日志到文件
- `conn` - 输出日志到套接字(网络或 Unix 套接字)
### 公共配置
某些配置适用于所有日志输出模式:
- `MODE` 是日志输出写入器的模式。它将默认为 ini 部分的模式名称。因此,`[log.console]` 将默认为 `MODE = console`
- `LEVEL` 是此输出将记录的最低日志级别。
- `STACKTRACE_LEVEL` 是此输出将打印堆栈跟踪的最低日志级别。
- `COLORIZE` 对于 `console`,默认为 `true`,否则默认为 `false`
#### `EXPRESSION`
`EXPRESSION` 表示日志事件必须匹配才能被输出写入器记录的正则表达式。
日志消息(去除颜色)或 `longfilename:linenumber:functionname` 必须匹配其中之一。
注意:整个消息或字符串不需要完全匹配。
请注意,此表达式将在写入器的 goroutine 中运行,而不是在日志事件的 goroutine 中运行。
#### `FLAGS`
`FLAGS` 表示在每条消息之前打印的前置日志上下文信息。
它是一个逗号分隔的字符串集。值的顺序无关紧要。
默认值为 `stdflags`= `date,time,medfile,shortfuncname,levelinitial`)。
可能的值为:
- `none``,` - 无标志。
- `date` - 当地时区的日期:`2009/01/23`。
- `time` - 当地时区的时间:`01:23:23`。
- `microseconds` - 微秒精度:`01:23:23.123123`。假定有时间。
- `longfile` - 完整的文件名和行号:`/a/b/c/d.go:23`。
- `shortfile` - 文件名的最后一个部分和行号:`d.go:23`。
- `funcname` - 调用者的函数名:`runtime.Caller()`。
- `shortfuncname` - 函数名的最后一部分。覆盖 `funcname`
- `utc` - 如果设置了日期或时间,则使用 UTC 而不是本地时区。
- `levelinitial` - 提供的级别的初始字符,放在方括号内,例如 `[I]` 表示 info。
- `level` - 在方括号内的级别,例如 `[INFO]`
- `gopid` - 上下文的 Goroutine-PID。
- `medfile` - 文件名的最后 20 个字符 - 相当于 `shortfile,longfile`
- `stdflags` - 相当于 `date,time,medfile,shortfuncname,levelinitial`
### Console 模式
在此模式下,日志记录器将将日志消息转发到 Gitea 进程附加的 stdout 和 stderr 流。
对于 console 模式的日志记录器,如果不在 Windows 上,或者 Windows 终端可以设置为 ANSI 模式,或者是 cygwin 或 Msys 管道,则 `COLORIZE` 默认为 `true`
设置:
- `STDERR`**false**:日志记录器是否应将日志打印到 `stderr` 而不是 `stdout`
### File 模式
在此模式下,日志记录器将将日志消息保存到文件中。
设置:
- `FILE_NAME`:要将日志事件写入的文件,相对于 `ROOT_PATH`,默认为 `%(ROOT_PATH)/gitea.log`。异常情况:访问日志默认为 `%(ROOT_PATH)/access.log`
- `MAX_SIZE_SHIFT`**28**单个文件的最大大小位移。28 表示 256Mb。详细信息见下文。
- `LOG_ROTATE` **true**:是否轮转日志文件。
- `DAILY_ROTATE`**true**:是否每天旋转日志。
- `MAX_DAYS`**7**:在此天数之后删除旋转的日志文件。
- `COMPRESS`**true**:默认情况下是否使用 gzip 压缩旧的日志文件。
- `COMPRESSION_LEVEL`**-1**:压缩级别。详细信息见下文。
`MAX_SIZE_SHIFT` 通过将给定次数左移 1 (`1 << x`) 来定义文件的最大大小
在 v1.17.3 版本时的确切行为可以在[这里](https://github.com/go-gitea/gitea/blob/v1.17.3/modules/setting/log.go#L185)中查看。
`COMPRESSION_LEVEL` 的有用值范围从 1 到包括9其中较高的数字表示更好的压缩。
请注意,更好的压缩可能会带来更高的资源使用。
必须在前面加上 `-` 符号。
### Conn 模式
在此模式下,日志记录器将通过网络套接字发送日志消息。
设置:
- `ADDR`**:7020**:设置要连接的地址。
- `PROTOCOL`**tcp**:设置协议,可以是 "tcp"、"unix" 或 "udp"。
- `RECONNECT`**false**:在连接丢失时尝试重新连接。
- `RECONNECT_ON_MSG`**false**:为每条消息重新连接主机。
### "Router" 日志记录器
当 Gitea 的路由处理程序工作时Router 日志记录器记录以下消息类型:
- `started` 消息将以 TRACE 级别记录
- `polling`/`completed` 路由将以 INFO 级别记录。异常情况:"/assets" 静态资源请求也会以 TRACE 级别记录。
- `slow` 路由将以 WARN 级别记录
- `failed` 路由将以 WARN 级别记录
### "XORM" 日志记录器
为了使 XORM 输出 SQL 日志,还应将 `[database]` 部分中的 `LOG_SQL` 设置为 `true`
### "Access" 日志记录器
"Access" 日志记录器是自 Gitea 1.9 版本以来的新日志记录器。它提供了符合 NCSA Common Log 标准的日志格式。虽然它具有高度可配置性但在更改其模板时应谨慎。此日志记录器的主要好处是Gitea 现在可以使用标准日志格式记录访问日志,因此可以使用标准工具进行分析。
您可以通过使用 `logger.access.MODE = ...` 来启用此日志记录器。
如果需要,可以通过更改 `ACCESS_LOG_TEMPLATE` 的值来更改 "Access" 日志记录器的格式。
请注意,访问日志记录器将以 `INFO` 级别记录,将此日志记录器的 `LEVEL` 设置为 `WARN` 或更高级别将导致不记录访问日志。
#### ACCESS_LOG_TEMPLATE
此值表示一个 Go 模板。其默认值为
```tmpl
{{.Ctx.RemoteHost}} - {{.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``context.Context`
- `Identity``SignedUserName`,如果用户未登录,则为 "-"
- `Start` 是请求的开始时间
- `ResponseWriter``http.ResponseWriter`
更改此模板时必须小心,因为它在标准的 panic 恢复陷阱之外运行。此模板应该尽可能简单,因为它会为每个请求运行一次。
## 释放和重新打开、暂停和恢复日志记录
如果您在 Unix 上运行,您可能希望释放和重新打开日志以使用 `logrotate` 或其他工具。
可以通过向运行中的进程发送 `SIGUSR1` 信号或运行 `gitea manager logging release-and-reopen` 命令来强制 Gitea 释放并重新打开其日志文件和连接。
或者,您可能希望暂停和恢复日志记录 - 可以通过使用 `gitea manager logging pause``gitea manager logging resume` 命令来实现。请注意,当日志记录暂停时,低于 INFO 级别的日志事件将不会存储,并且只会存储有限数量的事件。在暂停时,日志记录可能会阻塞,尽管是暂时性的,但会大大减慢 Gitea 的运行速度,因此建议仅暂停很短的时间。
### 在 Gitea 运行时添加和删除日志记录
可以使用 `gitea manager logging add``remove` 子命令在 Gitea 运行时添加和删除日志记录。
此功能只能调整正在运行的日志系统,不能用于启动未初始化的访问或路由日志记录器。如果您希望启动这些系统,建议调整 app.ini 并(优雅地)重新启动 Gitea 服务。
这些命令的主要目的是在运行中的系统上轻松添加临时日志记录器,以便调查问题,因为重新启动可能会导致问题消失。
## 使用 `logrotate` 而不是内置的日志轮转
Gitea 包含内置的日志轮转功能,对于大多数部署来说应该已经足够了。但是,如果您想使用 `logrotate` 工具:
- 在 `app.ini` 中将 `LOG_ROTATE` 设置为 `false`,禁用内置的日志轮转。
- 安装 `logrotate`
- 根据部署要求配置 `logrotate`,有关配置语法细节,请参阅 `man 8 logrotate`
`postrotate/endscript` 块中通过 `kill -USR1``kill -10``gitea` 进程本身发送 `USR1` 信号,
或者运行 `gitea manager logging release-and-reopen`(使用适当的环境设置)。
确保配置适用于由 Gitea 日志记录器生成的所有文件,如上述部分所述。
- 始终使用 `logrotate /etc/logrotate.conf --debug` 来测试您的配置。
- 如果您正在使用 Docker 并从容器外部运行,您可以使用
`docker exec -u $OS_USER $CONTAINER_NAME sh -c 'gitea manager logging release-and-reopen'`
`docker exec $CONTAINER_NAME sh -c '/bin/s6-svc -1 /etc/s6/gitea/'`,或直接向 Gitea 进程本身发送 `USR1` 信号。
下一个 `logrotate` 作业将包括您的配置,因此不需要重新启动。
您还可以立即使用 `logrotate /etc/logrotate.conf --force` 重新加载 `logrotate`

View File

@ -1,522 +0,0 @@
---
date: "2019-04-02T17:06:00+01:00"
title: "Logging Configuration"
slug: "logging-configuration"
weight: 40
toc: false
draft: false
menu:
sidebar:
parent: "administration"
name: "Logging Configuration"
weight: 40
identifier: "logging-configuration"
---
# Logging Configuration
The logging configuration of Gitea mainly consists of 3 types of components:
- The `[log]` section for general configuration
- `[log.<sublogger>]` sections for the configuration of different log outputs
- `[log.<sublogger>.<group>]` sections for output specific configuration of a log group
As mentioned below, there is a fully functional log output by default, so it is not necessary to define one.
**Table of Contents**
{{< toc >}}
## Collecting Logs for Help
To collect logs for help and issue report, see [Support Options]({{< relref "doc/help/seek-help.en-us.md" >}}).
## The `[log]` section
Configuration of logging facilities in Gitea happen in the `[log]` section and it's subsections.
In the top level `[log]` section the following configurations can be placed:
- `ROOT_PATH`: (Default: **%(GITEA_WORK_DIR)/log**): Base path for log files
- `MODE`: (Default: **console**) List of log outputs to use for the Default logger.
- `ROUTER`: (Default: **console**): List of log outputs to use for the Router logger.
- `ACCESS`: List of log outputs to use for the Access logger.
- `XORM`: (Default: **,**) List of log outputs to use for the XORM logger.
- `ENABLE_ACCESS_LOG`: (Default: **false**): whether the Access logger is allowed to emit logs
- `ENABLE_XORM_LOG`: (Default: **true**): whether the XORM logger is allowed to emit logs
For details on the loggers check the "Log Groups" section.
Important: log outputs won't be used if you don't enable them for the desired loggers in the corresponding list value.
Lists are specified as comma separated values. This format also works in subsection.
This section may be used for defining default values for subsections.
Examples:
- `LEVEL`: (Default: **Info**) Least severe log events to persist. Case insensitive. The full list of levels as of v1.17.3 can be read [here](https://github.com/go-gitea/gitea/blob/v1.17.3/custom/conf/app.example.ini#L507).
- `STACKTRACE_LEVEL`: (Default: **None**) For this and more severe events the stacktrace will be printed upon getting logged.
Some values are not inherited by subsections. For details see the "Non-inherited default values" section.
## Log outputs
Log outputs are the targets to which log messages will be sent.
The content and the format of the log messages to be saved can be configured in these.
Log outputs are also called subloggers.
Gitea provides 4 possible log outputs:
- `console` - Log to `os.Stdout` or `os.Stderr`
- `file` - Log to a file
- `conn` - Log to a socket (network or unix)
- `smtp` - Log via email
By default, Gitea has a `console` output configured, which is used by the loggers as seen in the section "The log section" above.
### Common configuration
Certain configuration is common to all modes of log output:
- `MODE` is the mode of the log output. It will default to the sublogger
name, thus `[log.console.router]` will default to `MODE = console`.
For mode specific confgurations read further.
- `LEVEL` is the lowest level that this output will log. This value
is inherited from `[log]` and in the case of the non-default loggers
from `[log.sublogger]`.
- `STACKTRACE_LEVEL` is the lowest level that this output will print
a stacktrace. This value is inherited.
- `COLORIZE` will default to `true` for `console` as
described, otherwise it will default to `false`.
### Non-inherited default values
There are several values which are not inherited as described above but
rather default to those specific to type of logger, these are:
`EXPRESSION`, `FLAGS`, `PREFIX` and `FILE_NAME`.
#### `EXPRESSION`
`EXPRESSION` represents a regular expression that log events must match to be logged by the sublogger. Either the log message, (with colors removed), must match or the `longfilename:linenumber:functionname` must match. NB: the whole message or string doesn't need to completely match.
Please note this expression will be run in the sublogger's goroutine
not the logging event subroutine. Therefore it can be complicated.
#### `FLAGS`
`FLAGS` represents the preceding logging context information that is
printed before each message. It is a comma-separated string set. The order of values does not matter.
Possible values are:
- `none` or `,` - No flags.
- `date` - the date in the local time zone: `2009/01/23`.
- `time` - the time in the local time zone: `01:23:23`.
- `microseconds` - microsecond resolution: `01:23:23.123123`. Assumes
time.
- `longfile` - full file name and line number: `/a/b/c/d.go:23`.
- `shortfile` - final file name element and line number: `d.go:23`.
- `funcname` - function name of the caller: `runtime.Caller()`.
- `shortfuncname` - last part of the function name. Overrides
`funcname`.
- `utc` - if date or time is set, use UTC rather than the local time
zone.
- `levelinitial` - Initial character of the provided level in brackets eg. `[I]` for info.
- `level` - Provided level in brackets `[INFO]`
- `medfile` - Last 20 characters of the filename - equivalent to
`shortfile,longfile`.
- `stdflags` - Equivalent to `date,time,medfile,shortfuncname,levelinitial`
### Console mode
In this mode the logger will forward log messages to the stdout and
stderr streams attached to the Gitea process.
For loggers in console mode, `COLORIZE` will default to `true` if not
on windows, or the windows terminal can be set into ANSI mode or is a
cygwin or Msys pipe.
Settings:
- `STDERR`: **false**: Whether the logger should print to `stderr` instead of `stdout`.
### File mode
In this mode the logger will save log messages to a file.
Settings:
- `FILE_NAME`: The file to write the log events to. For details see below.
- `MAX_SIZE_SHIFT`: **28**: Maximum size shift of a single file. 28 represents 256Mb. For details see below.
- `LOG_ROTATE` **true**: Whether to rotate the log files. TODO: if false, will it delete instead on daily rotate, or do nothing?.
- `DAILY_ROTATE`: **true**: Whether to rotate logs daily.
- `MAX_DAYS`: **7**: Delete rotated log files after this number of days.
- `COMPRESS`: **true**: Whether to compress old log files by default with gzip.
- `COMPRESSION_LEVEL`: **-1**: Compression level. For details see below.
The default value of `FILE_NAME` depends on the respective logger facility.
If unset, their own default will be used.
If set it will be relative to the provided `ROOT_PATH` in the master `[log]` section.
`MAX_SIZE_SHIFT` defines the maximum size of a file by left shifting 1 the given number of times (`1 << x`).
The exact behavior at the time of v1.17.3 can be seen [here](https://github.com/go-gitea/gitea/blob/v1.17.3/modules/setting/log.go#L185).
The useful values of `COMPRESSION_LEVEL` are from 1 to (and including) 9, where higher numbers mean better compression.
Beware that better compression might come with higher resource usage.
Must be preceded with a `-` sign.
### Conn mode
In this mode the logger will send log messages over a network socket.
Settings:
- `ADDR`: **:7020**: Sets the address to connect to.
- `PROTOCOL`: **tcp**: Set the protocol, either "tcp", "unix" or "udp".
- `RECONNECT`: **false**: Try to reconnect when connection is lost.
- `RECONNECT_ON_MSG`: **false**: Reconnect host for every single message.
### SMTP mode
In this mode the logger will send log messages in email.
It is not recommended to use this logger to send general logging
messages. However, you could perhaps set this logger to work on `FATAL` messages only.
Settings:
- `HOST`: **127.0.0.1:25**: The SMTP host to connect to.
- `USER`: User email address to send from.
- `PASSWD`: Password for the smtp server.
- `RECEIVERS`: Email addresses to send to.
- `SUBJECT`: **Diagnostic message from Gitea**. The content of the email's subject field.
## Log Groups
The fundamental thing to be aware of in Gitea is that there are several
log groups:
- The "Default" logger
- The Router logger
- The Access logger
- The XORM logger
There is also the go log logger.
### The go log logger
Go provides its own extremely basic logger in the `log` package,
however, this is not sufficient for our purposes as it does not provide
a way of logging at multiple levels, nor does it provide a good way of
controlling where these logs are logged except through setting of a
writer.
We have therefore redirected this logger to our Default logger, and we
will log anything that is logged using the go logger at the INFO level.
### The "Default" logger
Calls to `log.Info`, `log.Debug`, `log.Error` etc. from the `code.gitea.io/gitea/modules/log` package will log to this logger.
You can configure the outputs of this logger by setting the `MODE`
value in the `[log]` section of the configuration.
Each output sublogger is configured in a separate `[log.sublogger.default]`
which inherits from the sublogger `[log.sublogger]` section and from the
generic `[log]` section, but there are certain default values. These will
not be inherited from the `[log]` section:
- `FLAGS` is `stdflags` (Equal to
`date,time,medfile,shortfuncname,levelinitial`)
- `FILE_NAME` will default to `%(ROOT_PATH)/gitea.log`
- `EXPRESSION` will default to `""`
- `PREFIX` will default to `""`
The provider type of the sublogger can be set using the `MODE` value in
its subsection, but will default to the name. This allows you to have
multiple subloggers that will log to files.
### The "Router" logger
The Router logger has been substantially changed in v1.17. If you are using the router logger for fail2ban or other monitoring
you will need to update this configuration.
You can disable Router log by setting `DISABLE_ROUTER_LOG` or by setting all of its sublogger configurations to `none`.
You can configure the outputs of this
router log by setting the `ROUTER` value in the `[log]` section of the
configuration. `ROUTER` will default to `console` if unset and will default to same level as main logger.
The Router logger logs the following:
- `started` messages will be logged at TRACE level
- `polling`/`completed` routers will be logged at INFO
- `slow` routers will be logged at WARN
- `failed` routers will be logged at WARN
The logging level for the router will default to that of the main configuration. Set `[log.<mode>.router]` `LEVEL` to change this.
Each output sublogger for this logger is configured in
`[log.sublogger.router]` sections. There are certain default values
which will not be inherited from the `[log]` or relevant
`[log.sublogger]` sections:
- `FILE_NAME` will default to `%(ROOT_PATH)/router.log`
- `FLAGS` defaults to `date,time`
- `EXPRESSION` will default to `""`
- `PREFIX` will default to `""`
NB: You can redirect the router logger to send its events to the Gitea
log using the value: `ROUTER = ,`
### The "Access" logger
The Access logger is a new logger for version 1.9. It provides a NCSA
Common Log compliant log format. It's highly configurable but caution
should be taken when changing its template. The main benefit of this
logger is that Gitea can now log accesses in a standard log format so
standard tools may be used.
You can enable this logger using `ENABLE_ACCESS_LOG`. Its outputs are
configured by setting the `ACCESS` value in the `[log]` section of the
configuration. `ACCESS` defaults to `file` if unset.
Each output sublogger for this logger is configured in
`[log.sublogger.access]` sections. There are certain default values
which will not be inherited from the `[log]` or relevant
`[log.sublogger]` sections:
- `FILE_NAME` will default to `%(ROOT_PATH)/access.log`
- `FLAGS` defaults to `` or None
- `EXPRESSION` will default to `""`
- `PREFIX` will default to `""`
If desired the format of the Access logger can be changed by changing
the value of the `ACCESS_LOG_TEMPLATE`.
Please note, the access logger will log at `INFO` level, setting the
`LEVEL` of this logger to `WARN` or above will result in no access logs.
NB: You can redirect the access logger to send its events to the Gitea
log using the value: `ACCESS = ,`
#### The ACCESS_LOG_TEMPLATE
This value represent a go template. It's default value is:
`{{.Ctx.RemoteHost}} - {{.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}}"`
The template is passed following options:
- `Ctx` is the `context.Context`
- `Identity` is the `SignedUserName` or `"-"` if the user is not logged
in
- `Start` is the start time of the request
- `ResponseWriter` is the `http.ResponseWriter`
Caution must be taken when changing this template as it runs outside of
the standard panic recovery trap. The template should also be as simple
as it runs for every request.
### The "XORM" logger
The XORM logger is a long-standing logger that exists to collect XORM
log events. It is enabled by default but can be switched off by setting
`ENABLE_XORM_LOG` to `false` in the `[log]` section. Its outputs are
configured by setting the `XORM` value in the `[log]` section of the
configuration. `XORM` defaults to `,` if unset, meaning it is redirected
to the main Gitea log.
XORM will log SQL events by default. This can be changed by setting
the `LOG_SQL` value to `false` in the `[database]` section.
Each output sublogger for this logger is configured in
`[log.sublogger.xorm]` sections. There are certain default values
which will not be inherited from the `[log]` or relevant
`[log.sublogger]` sections:
- `FILE_NAME` will default to `%(ROOT_PATH)/xorm.log`
- `FLAGS` defaults to `date,time`
- `EXPRESSION` will default to `""`
- `PREFIX` will default to `""`
## Debugging problems
When submitting logs in Gitea issues it is often helpful to submit
merged logs obtained by either by redirecting the console log to a file or
copying and pasting it. To that end it is recommended to set your logging to:
```ini
[database]
LOG_SQL = false ; SQL logs are rarely helpful unless we specifically ask for them
...
[log]
MODE = console
LEVEL = debug ; please set the level to debug when we are debugging a problem
ROUTER = console
COLORIZE = false ; this can be true if you can strip out the ansi coloring
ENABLE_SSH_LOG = true ; shows logs related to git over SSH.
```
Sometimes it will be helpful get some specific `TRACE` level logging restricted
to messages that match a specific `EXPRESSION`. Adjusting the `MODE` in the
`[log]` section to `MODE = console,traceconsole` to add a new logger output
`traceconsole` and then adding its corresponding section would be helpful:
```ini
[log.traceconsole] ; traceconsole here is just a name
MODE = console ; this is the output that the traceconsole writes to
LEVEL = trace
EXPRESSION = ; putting a string here will restrict this logger to logging only those messages that match this expression
```
(It's worth noting that log messages that match the expression at or above debug
level will get logged twice so don't worry about that.)
`STACKTRACE_LEVEL` should generally be left unconfigured (and hence kept at
`none`). There are only very specific occasions when it useful.
## Empty Configuration
The empty configuration is equivalent to:
```ini
[log]
ROOT_PATH = %(GITEA_WORK_DIR)/log
MODE = console
LEVEL = Info
STACKTRACE_LEVEL = None
ENABLE_ACCESS_LOG = false
ENABLE_XORM_LOG = true
XORM = ,
[log.console]
MODE = console
LEVEL = %(LEVEL)
STACKTRACE_LEVEL = %(STACKTRACE_LEVEL)
FLAGS = stdflags
PREFIX =
COLORIZE = true # Or false if your windows terminal cannot color
```
This is equivalent to sending all logs to the console, with default go log being sent to the console log too.
## Releasing-and-Reopening, Pausing and Resuming logging
If you are running on Unix you may wish to release-and-reopen logs in order to use `logrotate` or other tools.
It is possible force Gitea to release and reopen it's logging files and connections by sending `SIGUSR1` to the
running process, or running `gitea manager logging release-and-reopen`.
Alternatively, you may wish to pause and resume logging - this can be accomplished through the use of the
`gitea manager logging pause` and `gitea manager logging resume` commands. Please note that whilst logging
is paused log events below INFO level will not be stored and only a limited number of events will be stored.
Logging may block, albeit temporarily, slowing Gitea considerably whilst paused - therefore it is
recommended that pausing only done for a very short period of time.
## Adding and removing logging whilst Gitea is running
It is possible to add and remove logging whilst Gitea is running using the `gitea manager logging add` and `remove` subcommands.
This functionality can only adjust running log systems and cannot be used to start the access or router loggers if they
were not already initialized. If you wish to start these systems you are advised to adjust the app.ini and (gracefully) restart
the Gitea service.
The main intention of these commands is to easily add a temporary logger to investigate problems on running systems where a restart
may cause the issue to disappear.
## Log colorization
Logs to the console will be colorized by default when not running on
Windows. Terminal sniffing will occur on Windows and if it is
determined that we are running on a terminal capable of color we will
colorize.
Further, on \*nix it is becoming common to have file logs that are
colored by default. Therefore file logs will be colorised by default
when not running on Windows.
You can switch on or off colorization by using the `COLORIZE` value.
From a development point of view. If you write
`log.Info("A %s string", "formatted")` the `formatted` part of the log
message will be Bolded on colorized logs.
You can change this by either rendering the formatted string yourself.
Or you can wrap the value in a `log.ColoredValue` struct.
The `log.ColoredValue` struct contains a pointer to value, a pointer to
string of bytes which should represent a color and second set of reset
bytes. Pointers were chosen to prevent copying of large numbers of
values. There are several helper methods:
- `log.NewColoredValue` takes a value and 0 or more color attributes
that represent the color. If 0 are provided it will default to a cached
bold. Note, it is recommended that color bytes constructed from
attributes should be cached if this is a commonly used log message.
- `log.NewColoredValuePointer` takes a pointer to a value, and
0 or more color attributes that represent the color.
- `log.NewColoredValueBytes` takes a value and a pointer to an array
of bytes representing the color.
These functions will not double wrap a `log.ColoredValue`. They will
also set the `resetBytes` to the cached `resetBytes`.
The `colorBytes` and `resetBytes` are not exported to prevent
accidental overwriting of internal values.
## ColorFormat & ColorFormatted
Structs may implement the `log.ColorFormatted` interface by implementing the `ColorFormat(fmt.State)` function.
If a `log.ColorFormatted` struct is logged with `%-v` format, its `ColorFormat` will be used instead of the usual `%v`. The full `fmt.State` will be passed to allow implementers to look at additional flags.
In order to help implementers provide `ColorFormat` methods. There is a
`log.ColorFprintf(...)` function in the log module that will wrap values in `log.ColoredValue` and recognise `%-v`.
In general it is recommended not to make the results of this function too verbose to help increase its versatility. Usually this should simply be an `ID`:`Name`. If you wish to make a more verbose result, it is recommended to use `%-+v` as your marker.
## Log Spoofing protection
In order to protect the logs from being spoofed with cleverly
constructed messages. Newlines are now prefixed with a tab and control
characters except those used in an ANSI CSI are escaped with a
preceding `\` and their octal value.
## Creating a new named logger group
Should a developer wish to create a new named logger, `NEWONE`. It is
recommended to add an `ENABLE_NEWONE_LOG` value to the `[log]`
section, and to add a new `NEWONE` value for the modes.
A function like `func newNewOneLogService()` is recommended to manage
construction of the named logger. e.g.
```go
func newNewoneLogService() {
EnableNewoneLog = Cfg.Section("log").Key("ENABLE_NEWONE_LOG").MustBool(false)
Cfg.Section("log").Key("NEWONE").MustString("file") // or console? or "," if you want to send this to default logger by default
if EnableNewoneLog {
options := newDefaultLogOptions()
options.filename = filepath.Join(LogRootPath, "newone.log")
options.flags = "stdflags"
options.bufferLength = Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000)
generateNamedLogger("newone", options)
}
}
```
You should then add `newOneLogService` to `NewServices()` in
`modules/setting/setting.go`
## Using `logrotate` instead of built-in log rotation
Gitea includes built-in log rotation, which should be enough for most deployments. However, if you instead want to use the `logrotate` utility:
- Disable built-in log rotation by setting `LOG_ROTATE` to `false` in your `app.ini`.
- Install `logrotate`.
- Configure `logrotate` to match your deployment requirements, see `man 8 logrotate` for configuration syntax details. In the `postrotate/endscript` block send Gitea a `USR1` signal via `kill -USR1` or `kill -10` to the `gitea` process itself, or run `gitea manager logging release-and-reopen` (with the appropriate environment). Ensure that your configurations apply to all files emitted by Gitea loggers as described in the above sections.
- Always do `logrotate /etc/logrotate.conf --debug` to test your configurations.
- If you are using docker and are running from outside of the container you can use `docker exec -u $OS_USER $CONTAINER_NAME sh -c 'gitea manager logging release-and-reopen'` or `docker exec $CONTAINER_NAME sh -c '/bin/s6-svc -1 /etc/s6/gitea/'` or send `USR1` directly to the Gitea process itself.
The next `logrotate` jobs will include your configurations, so no restart is needed. You can also immediately reload `logrotate` with `logrotate /etc/logrotate.conf --force`.

View File

@ -5,6 +5,8 @@ slug: "mail-templates"
weight: 45
toc: false
draft: false
aliases:
- /en-us/mail-templates
menu:
sidebar:
parent: "administration"

View File

@ -0,0 +1,265 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "邮件模板"
slug: "mail-templates"
weight: 45
toc: false
draft: false
aliases:
- /zh-cn/mail-templates
menu:
sidebar:
parent: "administration"
name: "邮件模板"
weight: 45
identifier: "mail-templates"
---
# 邮件模板
**目录**
{{< toc >}}
为了定制特定操作的电子邮件主题和内容,可以使用模板来自定义 Gitea。这些功能的模板位于 [`custom` 目录](https://docs.gitea.io/en-us/customizing-gitea/) 下。
如果没有自定义的替代方案Gitea 将使用内部模板作为默认模板。
自定义模板在 Gitea 启动时加载。对它们的更改在 Gitea 重新启动之前不会被识别。
## 支持模板的邮件通知
目前,以下通知事件使用模板:
| 操作名称 | 用途 |
| ----------- | ------------------------------------------------------------------------------------------------------------ |
| `new` | 创建了新的工单或合并请求。 |
| `comment` | 在现有工单或合并请求中创建了新的评论。 |
| `close` | 关闭了工单或合并请求。 |
| `reopen` | 重新打开了工单或合并请求。 |
| `review` | 在合并请求中进行审查的首要评论。 |
| `approve` | 对合并请求进行批准的首要评论。 |
| `reject` | 对合并请求提出更改请求的审查的首要评论。 |
| `code` | 关于合并请求的代码的单个评论。 |
| `assigned` | 用户被分配到工单或合并请求。 |
| `default` | 未包括在上述类别中的任何操作,或者当对应类别的模板不存在时使用的模板。 |
特定消息类型的模板路径为:
```sh
custom/templates/mail/{操作类型}/{操作名称}.tmpl
```
其中 `{操作类型}``issue``pull`(针对合并请求),`{操作名称}` 是上述列出的操作名称之一。
例如,有关合并请求中的评论的电子邮件的特定模板是:
```sh
custom/templates/mail/pull/comment.tmpl
```
然而,并不需要为每个操作类型/名称组合创建模板。
使用回退系统来选择适当的模板。在此列表中,将使用 _第一个存在的_ 模板:
- 所需**操作类型**和**操作名称**的特定模板。
- 操作类型为 `issue` 和所需**操作名称**的模板。
- 所需**操作类型**和操作名称为 `default` 的模板。
- 操作类型为` issue` 和操作名称为 `default` 的模板。
唯一必需的模板是操作类型为 `issue` 操作名称为 `default` 的模板,除非用户在 `custom` 目录中覆盖了它。
## 模板语法
邮件模板是 UTF-8 编码的文本文件,需要遵循以下格式之一:
```
用于主题行的文本和宏
------------
用于邮件正文的文本和宏
```
或者
```
用于邮件正文的文本和宏
```
指定 _主题_ 部分是可选的因此也是虚线分隔符。在使用时_主题_ 和 _邮件正文_ 模板之间的分隔符需要至少三个虚线;分隔符行中不允许使用其他字符。
_主题_ 和 _邮件正文_ 由 [Golang的模板引擎](https://golang.org/pkg/text/template/) 解析,并提供了为每个通知组装的 _元数据上下文_。上下文包含以下元素:
| 名称 | 类型 | 可用性 | 用途 |
| -------------------- | ------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `.FallbackSubject` | string | 始终可用 | 默认主题行。参见下文。 |
| `.Subject` | string | 仅在正文中可用 | 解析后的 _主题_。 |
| `.Body` | string | 始终可用 | 工单、合并请求或评论的消息,从 Markdown 解析为 HTML 并进行了清理。请勿与 _邮件正文_ 混淆。 |
| `.Link` | string | 始终可用 | 源工单、合并请求或评论的地址。 |
| `.Issue` | models.Issue | 始终可用 | 产生通知的工单(或合并请求)。要获取特定于合并请求的数据(例如 `HasMerged`),可以使用 `.Issue.PullRequest`,但需要注意,如果工单 _不是_ 合并请求,则该字段将为 `nil`。 |
| `.Comment` | models.Comment | 如果适用 | 如果通知是针对添加到工单或合并请求的评论,则其中包含有关评论的信息。 |
| `.IsPull` | bool | 始终可用 | 如果邮件通知与合并请求关联(即 `.Issue.PullRequest` 不为 `nil` ),则为 `true`。 |
| `.Repo` | string | 始终可用 | 仓库的名称,包括所有者名称(例如 `mike/stuff` |
| `.User` | models.User | 始终可用 | 事件来源仓库的所有者。要获取用户名(例如 `mike`),可以使用 `.User.Name`。 |
| `.Doer` | models.User | 始终可用 | 执行触发通知事件的操作的用户。要获取用户名(例如 `rhonda`),可以使用 `.Doer.Name`。 |
| `.IsMention` | bool | 始终可用 | 如果此通知仅是因为在评论中提到了用户而生成的,并且收件人未订阅源,则为 `true`。如果收件人已订阅工单或仓库,则为 `false`。 |
| `.SubjectPrefix` | string | 始终可用 | 如果通知是关于除工单或合并请求创建之外的其他内容,则为 `Re`;否则为空字符串。 |
| `.ActionType` | string | 始终可用 | `"issue"``"pull"`。它将与实际的 _操作类型_ 对应,与选择的模板无关。 |
| `.ActionName` | string | 始终可用 | 它将是上述操作类型之一(`new` `comment` 等),并与选择的模板对应。 |
| `.ReviewComments` | []models.Comment | 始终可用 | 审查中的代码评论列表。评论文本将在 `.RenderedContent` 中,引用的代码将在 `.Patch` 中。 |
所有名称区分大小写。
### 模板中的主题部分
用于邮件主题的模板引擎是 Golang 的 [`text/template`](https://golang.org/pkg/text/template/)。
有关语法的详细信息,请参阅链接的文档。
主题构建的步骤如下:
- 根据通知类型和可用的模板选择一个模板。
- 解析并解析模板(例如,将 `{{.Issue.Index}}` 转换为工单或合并请求的编号)。
- 将所有空格字符(例如 `TAB``LF` 等)转换为普通空格。
- 删除所有前导、尾随和多余的空格。
- 将字符串截断为前 256 个字母(字符)。
如果最终结果为空字符串,**或者**没有可用的主题模板即所选模板不包含主题部分将使用Gitea的**内部默认值**。
内部默认(回退)主题相当于:
```
{{.SubjectPrefix}}[{{.Repo}}] {{.Issue.Title}} (#{{.Issue.Index}})
```
例如:`Re: [mike/stuff] New color palette (#38)`
即使存在有效的主题模板Gitea的默认主题也可以在模板的元数据中作为 `.FallbackSubject` 找到。
### 模板中的邮件正文部分
用于邮件正文的模板引擎是 Golang 的 [`html/template`](https://golang.org/pkg/html/template/)。
有关语法的详细信息,请参阅链接的文档。
邮件正文在邮件主题之后进行解析,因此还有一个额外的 _元数据_ 字段,即在考虑所有情况之后实际呈现的主题。
期望的结果是 HTML包括结构元素如`<html>``<body>`等)。可以通过 `<style>` 块、`class` 和 `style` 属性进行样式设置。但是,`html/template` 会进行一些 [自动转义](https://golang.org/pkg/html/template/#hdr-Contexts),需要考虑这一点。
不支持附件(例如图像或外部样式表)。但是,也可以引用其他模板,例如以集中方式提供 `<style>` 元素的内容。外部模板必须放置在 `custom/mail` 下,并相对于该目录引用。例如,可以使用 `{{template styles/base}}` 包含 `custom/mail/styles/base.tmpl`
邮件以 `Content-Type: multipart/alternative` 发送,因此正文以 HTML 和文本格式发送。通过剥离 HTML 标记来获取文本版本。
## 故障排除
邮件的呈现方式直接取决于邮件应用程序的功能。许多邮件客户端甚至不支持 HTML因此显示生成邮件中包含的文本版本。
如果模板无法呈现,则只有在发送邮件时才会注意到。
如果主题模板失败,将使用默认主题,如果从 _邮件正文_ 中成功呈现了任何内容,则将使用该内容,忽略其他内容。
如果遇到问题,请检查 [Gitea的日志](https://docs.gitea.io/en-us/logging-configuration/) 以获取错误消息。
## 示例
`custom/templates/mail/issue/default.tmpl`:
```html
[{{.Repo}}] @{{.Doer.Name}}
{{if eq .ActionName "new"}}
创建了
{{else if eq .ActionName "comment"}}
评论了
{{else if eq .ActionName "close"}}
关闭了
{{else if eq .ActionName "reopen"}}
重新打开了
{{else}}
更新了
{{end}}
{{if eq .ActionType "issue"}}
工单
{{else}}
合并请求
{{end}}
#{{.Issue.Index}}: {{.Issue.Title}}
------------
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{{.Subject}}</title>
</head>
<body>
{{if .IsMention}}
<p>
您收到此邮件是因为 @{{.Doer.Name}} 提到了您。
</p>
{{end}}
<p>
<p>
<a href="{{AppUrl}}/{{.Doer.LowerName}}">@{{.Doer.Name}}</a>
{{if not (eq .Doer.FullName "")}}
({{.Doer.FullName}})
{{end}}
{{if eq .ActionName "new"}}
创建了
{{else if eq .ActionName "close"}}
关闭了
{{else if eq .ActionName "reopen"}}
重新打开了
{{else}}
更新了
{{end}}
<a href="{{.Link}}">{{.Repo}}#{{.Issue.Index}}</a>
</p>
{{if not (eq .Body "")}}
<h3>消息内容:</h3>
<hr>
{{.Body | Str2html}}
{{end}}
</p>
<hr>
<p>
<a href="{{.Link}}">在 Gitea 上查看</a>
</p>
</body>
</html>
```
该模板将生成以下内容:
### 主题
> [mike/stuff] @rhonda 在合并请求 #38 上进行了评论New color palette
### 邮件正文
> [@rhonda](#)Rhonda Myers更新了 [mike/stuff#38](#)。
>
> #### 消息内容:
>
> \_********************************\_********************************
>
> Mike, I think we should tone down the blues a little.
>
> \_********************************\_********************************
>
> [在 Gitea 上查看](#)。
## 高级用法
模板系统包含一些函数,可用于进一步处理和格式化消息。以下是其中一些函数的列表:
| 函数名 | 参数 | 可用于 | 用法 |
| ----------------- | ----------- | ------------ | --------------------------------------------------------------------------------- |
| `AppUrl` | - | 任何地方 | Gitea 的 URL |
| `AppName` | - | 任何地方 | 从 `app.ini` 中设置,通常为 "Gitea" |
| `AppDomain` | - | 任何地方 | Gitea 的主机名 |
| `EllipsisString` | string, int | 任何地方 | 将字符串截断为指定长度;根据需要添加省略号 |
| `Str2html` | string | 仅正文部分 | 通过删除其中的 HTML 标签对文本进行清理 |
| `Safe` | string | 仅正文部分 | 将输入作为 HTML 处理;可用于 `.ReviewComments.RenderedContent` 等字段 |
这些都是 _函数_,而不是元数据,因此必须按以下方式使用:
```html
像这样使用: {{Str2html "Escape<my>text"}}
或者这样使用: {{"Escape<my>text" | Str2html}}
或者这样使用: {{AppUrl}}
但不要像这样使用: {{.AppUrl}}
```

View File

@ -5,6 +5,8 @@ slug: "repo-indexer"
weight: 45
toc: false
draft: false
aliases:
- /en-us/repo-indexer
menu:
sidebar:
parent: "administration"
@ -28,7 +30,6 @@ Gitea can search through the files of the repositories by enabling this function
; ...
REPO_INDEXER_ENABLED = true
REPO_INDEXER_PATH = indexers/repos.bleve
UPDATE_BUFFER_LEN = 20
MAX_FILE_SIZE = 1048576
REPO_INDEXER_INCLUDE =
REPO_INDEXER_EXCLUDE = resources/bin/**

View File

@ -0,0 +1,63 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "仓库索引器"
slug: "repo-indexer"
weight: 45
toc: false
draft: false
aliases:
- /zh-cn/repo-indexer
menu:
sidebar:
parent: "administration"
name: "仓库索引器"
weight: 45
identifier: "repo-indexer"
---
# 仓库索引器
**目录**
{{< toc >}}
## 设置仓库索引器
通过在您的 [`app.ini`](https://docs.gitea.io/en-us/config-cheat-sheet/) 中启用此功能Gitea 可以通过仓库的文件进行搜索:
```ini
[indexer]
; ...
REPO_INDEXER_ENABLED = true
REPO_INDEXER_PATH = indexers/repos.bleve
MAX_FILE_SIZE = 1048576
REPO_INDEXER_INCLUDE =
REPO_INDEXER_EXCLUDE = resources/bin/**
```
请记住,索引内容可能会消耗大量系统资源,特别是在首次创建索引或全局更新索引时(例如升级 Gitea 之后)。
### 按大小选择要索引的文件
`MAX_FILE_SIZE` 选项将使索引器跳过所有大于指定值的文件。
### 按路径选择要索引的文件
Gitea使用 [`gobwas/glob` 库](https://github.com/gobwas/glob) 中的 glob 模式匹配来选择要包含在索引中的文件。
限制文件列表可以防止索引被派生或无关的文件(例如 lss、sym、map 等)污染,从而使搜索结果更相关。这还有助于减小索引的大小。
`REPO_INDEXER_EXCLUDE_VENDORED`(默认值为 true将排除供应商文件不包含在索引中。
`REPO_INDEXER_INCLUDE`(默认值为空)是一个逗号分隔的 glob 模式列表,用于在索引中**包含**的文件。空列表表示“_包含所有文件_”。
`REPO_INDEXER_EXCLUDE`(默认值为空)是一个逗号分隔的 glob 模式列表,用于从索引中**排除**的文件。与该列表匹配的文件将不会被索引。`REPO_INDEXER_EXCLUDE` 优先于 `REPO_INDEXER_INCLUDE`
模式匹配工作方式如下:
- 要匹配所有带有 `.txt` 扩展名的文件,无论在哪个目录中,请使用 `**.txt`
- 要匹配仅在仓库的根级别中具有 `.txt` 扩展名的所有文件,请使用 `*.txt`
- 要匹配 `resources/bin` 目录及其子目录中的所有文件,请使用 `resources/bin/**`
- 要匹配位于 `resources/bin` 目录下的所有文件,请使用 `resources/bin/*`
- 要匹配所有名为 `Makefile` 的文件,请使用 `**Makefile`
- 匹配目录没有效果;模式 `resources/bin` 不会包含/排除该目录中的文件;`resources/bin/**` 会。
- 所有文件和模式都规范化为小写,因此 `**Makefile`、`**makefile` 和 `**MAKEFILE` 是等效的。

View File

@ -5,6 +5,8 @@ slug: "reverse-proxies"
weight: 16
toc: false
draft: false
aliases:
- /en-us/reverse-proxies
menu:
sidebar:
parent: "administration"
@ -23,12 +25,13 @@ menu:
If you want Nginx to serve your Gitea instance, add the following `server` section to the `http` section of `nginx.conf`:
```apacheconf
```
server {
listen 80;
server_name git.example.com;
location / {
client_max_body_size 512M;
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
@ -38,23 +41,32 @@ server {
}
```
### Resolving Error: 413 Request Entity Too Large
This error indicates nginx is configured to restrict the file upload size,
it affects attachment uploading, form posting, package uploading and LFS pushing, etc.
You can fine tune the `client_max_body_size` option according to [nginx document](http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size).
## Nginx with a sub-path
In case you already have a site, and you want Gitea to share the domain name, you can setup Nginx to serve Gitea under a sub-path by adding the following `server` section inside the `http` section of `nginx.conf`:
```apacheconf
```
server {
listen 80;
server_name git.example.com;
# Note: Trailing slash
location /git/ {
# Note: Trailing slash
proxy_pass http://localhost:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
location /gitea/ {
client_max_body_size 512M;
# make nginx use unescaped URI, keep "%2F" as is
rewrite ^ $request_uri;
rewrite ^/gitea(/.*) $1 break;
proxy_pass http://127.0.0.1:3000$uri;
# other common HTTP headers, see the "Nginx" config section above
proxy_set_header ...
}
}
```
@ -130,14 +142,6 @@ server {
}
```
## Resolving Error: 413 Request Entity Too Large
This error indicates nginx is configured to restrict the file upload size.
In your nginx config file containing your Gitea proxy directive, find the `location { ... }` block for Gitea and add the line
`client_max_body_size 16M;` to set this limit to 16 megabytes or any other number of choice.
If you use Git LFS, this will also limit the size of the largest file you will be able to push.
## Apache HTTPD
If you want Apache HTTPD to serve your Gitea instance, you can add the following to your Apache HTTPD configuration (usually located at `/etc/apache2/httpd.conf` in Ubuntu):
@ -187,14 +191,6 @@ git.example.com {
}
```
If you still use Caddy v1, use:
```apacheconf
git.example.com {
proxy / localhost:3000
}
```
## Caddy with a sub-path
In case you already have a site, and you want Gitea to share the domain name, you can setup Caddy to serve Gitea under a sub-path by adding the following to your server block in your Caddyfile:
@ -208,14 +204,6 @@ git.example.com {
}
```
Or, for Caddy v1:
```apacheconf
git.example.com {
proxy /git/ localhost:3000
}
```
Then set `[server] ROOT_URL = http://git.example.com/git/` in your configuration.
## IIS
@ -385,3 +373,13 @@ gitea:
This config assumes that you are handling HTTPS on the traefik side and using HTTP between Gitea and traefik.
Then you **MUST** set something like `[server] ROOT_URL = http://example.com/gitea/` correctly in your configuration.
## General sub-path configuration
Usually it's not recommended to put Gitea in a sub-path, it's not widely used and may have some issues in rare cases.
If you really need to do so, to make Gitea works with sub-path (eg: `http://example.com/gitea/`), here are the requirements:
1. Set `[server] ROOT_URL = http://example.com/gitea/` in your `app.ini` file.
2. Make the reverse-proxy pass `http://example.com/gitea/foo` to `http://gitea-server:3000/foo`.
3. Make sure the reverse-proxy not decode the URI, the request `http://example.com/gitea/a%2Fb` should be passed as `http://gitea-server:3000/a%2Fb`.

View File

@ -1,10 +1,12 @@
---
date: "2018-05-22T11:00:00+00:00"
title: "使用:反向代理"
title: "反向代理"
slug: "reverse-proxies"
weight: 16
toc: false
draft: false
aliases:
- /zh-cn/reverse-proxies
menu:
sidebar:
parent: "administration"

View File

@ -5,6 +5,8 @@ slug: "search-engines-indexation"
weight: 60
toc: false
draft: false
aliases:
- /en-us/search-engines-indexation
menu:
sidebar:
parent: "administration"

View File

@ -0,0 +1,39 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "搜索引擎索引"
slug: "search-engines-indexation"
weight: 60
toc: false
draft: false
aliases:
- /zh-cn/search-engines-indexation
menu:
sidebar:
parent: "administration"
name: "搜索引擎索引"
weight: 60
identifier: "search-engines-indexation"
---
# Gitea 安装的搜索引擎索引
默认情况下,您的 Gitea 安装将被搜索引擎索引。
如果您不希望您的仓库对搜索引擎可见,请进一步阅读。
## 使用 robots.txt 阻止搜索引擎索引
为了使 Gitea 为顶级安装提供自定义的`robots.txt`(默认为空的 404请在[`custom`文件夹或`CustomPath`]{{< relref "doc/administration/customizing-gitea.zh-cn.md" >}})中创建一个名为 `robots.txt` 的文件。
有关如何配置 `robots.txt` 的示例,请参考 [https://moz.com/learn/seo/robotstxt](https://moz.com/learn/seo/robotstxt)。
```txt
User-agent: *
Disallow: /
```
如果您将Gitea安装在子目录中则需要在顶级目录中创建或编辑 `robots.txt`
```txt
User-agent: *
Disallow: /gitea/
```

View File

@ -5,6 +5,8 @@ slug: "signing"
weight: 50
toc: false
draft: false
aliases:
- /en-us/signing
menu:
sidebar:
parent: "administration"

View File

@ -0,0 +1,146 @@
---
date: "2023-05-23T09:00:00+08:00"
title: "GPG 提交签名"
slug: "signing"
weight: 50
toc: false
draft: false
aliases:
- /zh-cn/signing
menu:
sidebar:
parent: "administration"
name: "GPG 提交签名"
weight: 50
identifier: "signing"
---
# GPG 提交签名
**目录**
{{< toc >}}
Gitea 将通过检查提交是否由 Gitea 数据库中的密钥签名,或者提交是否与 Git 的默认密钥匹配,来验证提供的树中的 GPG 提交签名。
密钥不会被检查以确定它们是否已过期或撤销。密钥也不会与密钥服务器进行检查。
如果找不到用于验证提交的密钥,提交将被标记为灰色的未锁定图标。如果提交被标记为红色的未锁定图标,则表示它使用带有 ID 的密钥签名。
请注意:提交的签署者不必是提交的作者或提交者。
此功能要求 Git >= 1.7.9,但要实现全部功能,需要 Git >= 2.0.0。
## 自动签名
有许多地方 Gitea 会生成提交:
- 仓库初始化
- Wiki 更改
- 使用编辑器或 API 进行的 CRUD 操作
- 从合并请求进行合并
根据配置和服务器信任,您可能希望 Gitea 对这些提交进行签名。
## 安装和生成 Gitea 的 GPG 密钥
如何安装签名密钥由服务器管理员决定。Gitea 目前使用服务器的 `git` 命令生成所有提交,因此将使用服务器的 `gpg` 进行签名(如果配置了)。管理员应该审查 GPG 的最佳实践 - 特别是可能建议仅安装签名的子密钥,而不是主签名和认证的密钥。
## 通用配置
Gitea 的签名配置可以在 `app.ini``[repository.signing]` 部分找到:
```ini
...
[repository.signing]
SIGNING_KEY = default
SIGNING_NAME =
SIGNING_EMAIL =
INITIAL_COMMIT = always
CRUD_ACTIONS = pubkey, twofa, parentsigned
WIKI = never
MERGES = pubkey, twofa, basesigned, commitssigned
...
```
### `SIGNING_KEY`
首先讨论的选项是 `SIGNING_KEY`。有三个主要选项:
- `none` - 这将阻止 Gitea 对任何提交进行签名
- `default` - Gitea 将使用 `git config` 中配置的默认密钥
- `KEYID` - Gitea 将使用具有 ID `KEYID` 的 GPG 密钥对提交进行签名。在这种情况下,您应该提供 `SIGNING_NAME``SIGNING_EMAIL`,以便显示此密钥的信息。
`default` 选项将读取 `git config` 中的 `commit.gpgsign` 选项 - 如果设置了该选项,它将使用 `user.signingkey`、`user.name` 和 `user.email` 的结果。
请注意:通过在 Gitea 的仓库中调整 Git 的 `config` 文件,可以使用 `SIGNING_KEY=default` 为每个仓库提供不同的签名密钥。然而,这显然不是一个理想的用户界面,因此可能会发生更改。
**自 1.17 起**Gitea 在自己的主目录 `[git].HOME_PATH`(默认为 `%(APP_DATA_PATH)/home`)中运行 git并使用自己的配置文件 `{[git].HOME_PATH}/.gitconfig`
如果您有自己定制的 Gitea git 配置,您应该将这些配置设置在系统 git 配置文件中(例如 `/etc/gitconfig`)或者 Gitea 的内部 git 配置文件 `{[git].HOME_PATH}/.gitconfig` 中。
与 git 命令相关的主目录文件(如 `.gnupg`)也应该放在 Gitea 的 git 主目录 `[git].HOME_PATH` 中。
如果您希望将 `.gnupg` 目录放在 `{[git].HOME_PATH}/` 之外的位置,请考虑设置 `$GNUPGHOME` 环境变量为您首选的位置。
### `INITIAL_COMMIT`
此选项确定在创建仓库时Gitea 是否应该对初始提交进行签名。可能的取值有:
- `never`:从不签名
- `pubkey`:仅在用户拥有公钥时进行签名
- `twofa`:仅在用户使用 2FA 登录时进行签名
- `always`:始终签名
除了 `never``always` 之外的选项可以组合为逗号分隔的列表。如果所有选择的选项都为 true则提交将被签名。
### `WIKI`
此选项确定 Gitea 是否应该对 Wiki 的提交进行签名。可能的取值有:
- `never`:从不签名
- `pubkey`:仅在用户拥有公钥时进行签名
- `twofa`:仅在用户使用 2FA 登录时进行签名
- `parentsigned`:仅在父提交已签名时进行签名。
- `always`:始终签名
除了 `never``always` 之外的选项可以组合为逗号分隔的列表。如果所有选择的选项都为 true则提交将被签名。
### `CRUD_ACTIONS`
此选项确定 Gitea 是否应该对 Web 编辑器或 API CRUD 操作的提交进行签名。可能的取值有:
- `never`:从不签名
- `pubkey`:仅在用户拥有公钥时进行签名
- `twofa`:仅在用户使用 2FA 登录时进行签名
- `parentsigned`:仅在父提交已签名时进行签名。
- `always`:始终签名
除了 `never``always` 之外的选项可以组合为逗号分隔的列表。如果所有选择的选项都为 true则更改将被签名。
### `MERGES`
此选项确定 Gitea 是否应该对 PR 的合并提交进行签名。可能的选项有:
- `never`:从不签名
- `pubkey`:仅在用户拥有公钥时进行签名
- `twofa`:仅在用户使用 2FA 登录时进行签名
- `basesigned`:仅在基础仓库中的父提交已签名时进行签名。
- `headsigned`:仅在头分支中的头提交已签名时进行签名。
- `commitssigned`:仅在头分支中的所有提交到合并点的提交都已签名时进行签名。
- `approved`:仅对已批准的合并到受保护分支的提交进行签名。
- `always`:始终签名
除了 `never``always` 之外的选项可以组合为逗号分隔的列表。如果所有选择的选项都为 true则合并将被签名。
## 获取签名密钥的公钥
用于签署 Gitea 提交的公钥可以通过 API 获取:
```sh
/api/v1/signing-key.gpg
```
在存在特定于仓库的密钥的情况下,可以通过以下方式获取:
```sh
/api/v1/repos/:username/:reponame/signing-key.gpg
```

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