Skip to content

Commit 97a3818

Browse files
authored
Merge branch 'main' into improve-push-memory
2 parents 910d4df + 9450410 commit 97a3818

24 files changed

+159
-38
lines changed

docs/content/doc/developers.zh-cn.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
date: "2016-12-01T16:00:00+02:00"
3+
title: "开发者"
4+
slug: "developers"
5+
weight: 40
6+
toc: false
7+
draft: false
8+
menu:
9+
sidebar:
10+
name: "开发者"
11+
weight: 50
12+
identifier: "developers"
13+
---
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
---
2+
date: "2021-11-01T23:41:00+08:00"
3+
title: "Guidelines for Backend Development"
4+
slug: "guidelines-backend"
5+
weight: 20
6+
toc: false
7+
draft: false
8+
menu:
9+
sidebar:
10+
parent: "developers"
11+
name: "Guidelines for Backend"
12+
weight: 20
13+
identifier: "guidelines-backend"
14+
---
15+
16+
# Guidelines for Backend Development
17+
18+
**Table of Contents**
19+
20+
{{< toc >}}
21+
22+
## Background
23+
24+
Gitea uses Golang as the backend programming language. It uses many third-party packages and also write some itself.
25+
For example, Gitea uses [Chi](https://github.com/go-chi/chi) as basic web framework. [Xorm](https://xorm.io) is an ORM framework that is used to interact with the database.
26+
So it's very important to manage these packages. Please take the below guidelines before you start to write backend code.
27+
28+
## Package Design Guideline
29+
30+
### Packages List
31+
32+
To maintain understandable code and avoid circular dependencies it is important to have a good code structure. The Gitea backend is divided into the following parts:
33+
34+
- `build`: Scripts to help build Gitea.
35+
- `cmd`: All Gitea actual sub commands includes web, doctor, serv, hooks, admin and etc. `web` will start the web service. `serv` and `hooks` will be invoked by git or openSSH. Other sub commands could help to mantain Gitea.
36+
- `integrations`: Integration tests
37+
- `models`: Contains the data structures used by xorm to construct database tables. It also contains functions to query and update the database. Dependencies to other Gitea code should be avoided. You can make exceptions in cases such as logging.
38+
- `models/db`: Basic database operations. All other `models/xxx` packages should depend on this package. The `GetEngine` function should only be invoked from `models/`.
39+
- `models/fixtures`: Sample data used in unit tests and integration tests. One `yml` file means one table which will be loaded into database when beginning the tests.
40+
- `models/migrations`: Stores database migrations between versions. PRs that change a database structure **MUST** also have a migration step.
41+
- `modules`: Different modules to handle specific functionality in Gitea. Work in Progress: Some of them should be moved to `services`.
42+
- `modules/setting`: Store all system configurations read from ini files and has been referenced by everywhere. But they should be used as function parameters when possible.
43+
- `modules/git`: Package to interactive with `Git` command line or Gogit package.
44+
- `public`: Compiled frontend files (javascript, images, css, etc.)
45+
- `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.
46+
- `routers/api` Conatins routers for `/api/v1` aims to handle RESTful API requests.
47+
- `routers/install` Could only reponse when system is INSTALL mode.
48+
- `routers/private` will only be invoked by internal sub commands, especially `serv` and `hooks`.
49+
- `routers/web` will handle HTTP requests from web browsers or Git SMART HTTP protocols.
50+
- `services`: Support functions for common routing operations or command executions. Uses `models` and `modules` to handle the requests.
51+
- `templates`: Golang templates for generating the html output.
52+
53+
### Package Dependencies
54+
55+
Since Golang don't support import cycles, we have to decide the package dependencies carefully. There are some levels between those packages. Below is the ideal package dependencies direction.
56+
57+
`cmd` -> `routers` -> `services` -> `models` -> `modules`
58+
59+
From left to right, left packages could depend on right packages, but right packages MUST not depend on left packages. The sub packages on the same level could depend on according this level's rules.
60+
61+
**NOTICE**
62+
63+
Why do we need database transactions outside of `models`? And how?
64+
Some actions should allow for rollback when database record insertion/update/deletion failed.
65+
So services must be allowed to create a database transaction. Here is some example,
66+
67+
```go
68+
// servcies/repository/repo.go
69+
func CreateXXXX() error {\
70+
ctx, committer, err := db.TxContext()
71+
if err != nil {
72+
return err
73+
}
74+
defer committer.Close()
75+
76+
// do something, if return err, it will rollback automatically when `committer.Close()` is invoked.
77+
if err := issues.UpdateIssue(ctx, repoID); err != nil {
78+
// ...
79+
}
80+
81+
// ......
82+
83+
return committer.Commit()
84+
}
85+
```
86+
87+
You should **not** use `db.GetEngine(ctx)` in `services` directly, but just write a function under `models/`.
88+
If the function will be used in the transaction, just let `context.Context` as the function's first parameter.
89+
90+
```go
91+
// models/issues/issue.go
92+
func UpdateIssue(ctx context.Context, repoID int64) error {
93+
e := db.GetEngine(ctx)
94+
95+
// ......
96+
}
97+
```
98+
99+
### Package Name
100+
101+
For the top level package, use a plural as package name, i.e. `services`, `models`, for sub packages, use singular,
102+
i.e. `servcies/user`, `models/repository`.
103+
104+
### Import Alias
105+
106+
Since there are many package levels and sub packages, so you will find `modules/user`, `models/user`, `services/user`. When these packages are import into one Go file, it's difficult to know which package we are using and if it's a variable name or an import name. So we recommand to always use import alias. To differ from package variables which are commonly use camelCase, just use **snake_case** as import package alias.
107+
i.e. `import user_service "code.Gitea.io/Gitea/services/user"`
108+
109+
### Future Tasks
110+
111+
Currently, we are creating some refactors to do the following things:
112+
113+
- Correct that codes which doesn't follow the rules.
114+
- There are too many files in `models`, so we are moving some of them into a sub package `models/xxx`.
115+
- Some `modules` sub packages should be moved to `services` because they depends on `models`.

models/ssh_key_authorized_keys.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import (
3939

4040
const (
4141
tplCommentPrefix = `# gitea public key`
42-
tplPublicKey = tplCommentPrefix + "\n" + `command=%s,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
42+
tplPublicKey = tplCommentPrefix + "\n" + `command=%s,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,no-user-rc,restrict %s` + "\n"
4343
)
4444

4545
var sshOpLocker sync.Mutex

options/locale/locale_cs-CZ.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -858,8 +858,6 @@ migrate.clone_address=Migrovat / klonovat z URL
858858
migrate.clone_address_desc=HTTP(S) nebo URL pro klonování existujícího repozitáře
859859
migrate.clone_local_path=nebo místní cesta serveru
860860
migrate.permission_denied=Není dovoleno importovat místní repozitáře.
861-
migrate.permission_denied_blocked=Nemáte oprávnění provést import z blokovaných serverů.
862-
migrate.permission_denied_private_ip=Nemáte oprávnění provést import ze soukromých IP adres.
863861
migrate.invalid_local_path=Místní cesta je neplatná, buď neexistuje nebo není adresářem.
864862
migrate.invalid_lfs_endpoint=Koncový bod LFS není platný.
865863
migrate.failed=Přenesení selhalo: %v

options/locale/locale_de-DE.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -884,8 +884,6 @@ migrate.clone_address=Migrations- / Klon-URL
884884
migrate.clone_address_desc=Die HTTP(S)- oder „git clone“-URL eines bereits existierenden Repositorys
885885
migrate.clone_local_path=oder ein lokaler Serverpfad
886886
migrate.permission_denied=Du hast keine Berechtigung zum Importieren lokaler Repositories.
887-
migrate.permission_denied_blocked=Du darfst nicht von geblockten Hosts importieren.
888-
migrate.permission_denied_private_ip=Du darfst nicht von privaten IP-Addressen importieren.
889887
migrate.invalid_local_path=Der lokale Pfad ist ungültig, existiert nicht oder ist kein Ordner.
890888
migrate.invalid_lfs_endpoint=Ungültiger LFS Endpunkt.
891889
migrate.failed=Fehler bei der Migration: %v

options/locale/locale_el-GR.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -899,8 +899,6 @@ migrate.clone_address_desc=Το HTTP(S) ή Git URL 'κλωνοποίησης' ε
899899
migrate.github_token_desc=Μπορείτε να βάλετε ένα ή περισσότερα διακριτικά χωρίζοντας τα με κόμμα, ώστε να κάνετε τη μεταφορά γρηγορότερη, επειδή το API του Github έχει όριο ρυθμού. ΠΡΟΣΟΧΗ: Η κατάχρηση αυτής της δυνατότητας μπορεί να παραβιάσει την πολιτική του παρόχου υπηρεσιών και να οδηγήσει σε αποκλεισμό λογαριασμού.
900900
migrate.clone_local_path=ή μια διαδρομή τοπικού διακομιστή
901901
migrate.permission_denied=Δεν επιτρέπεται η εισαγωγή τοπικών αποθετηρίων.
902-
migrate.permission_denied_blocked=Δεν επιτρέπεται η εισαγωγή από αποκλεισμένους υπολογιστές.
903-
migrate.permission_denied_private_ip=Δεν επιτρέπεται η εισαγωγή από ιδιωτικές IPs.
904902
migrate.invalid_local_path=Η τοπική διαδρομή δεν είναι έγκυρη. Δεν υπάρχει ή δεν είναι φάκελος.
905903
migrate.invalid_lfs_endpoint=Η διεύθυνση LFS δεν είναι έγκυρο.
906904
migrate.failed=Η μεταφορά απέτυχε: %v

options/locale/locale_es-ES.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -895,8 +895,6 @@ migrate.clone_address_desc=La URL HTTP(S) o de Git 'clone' de un repositorio exi
895895
migrate.github_token_desc=Puedes poner uno o más tokens con comas separadas aquí para hacer migrar más rápido debido al límite de velocidad de Github API. PRECAUCIÓN: Abusar esta característica puede violar la política del proveedor de servicios y llevar a bloquear la cuenta.
896896
migrate.clone_local_path=o una ruta local del servidor
897897
migrate.permission_denied=No te está permitido importar repositorios locales.
898-
migrate.permission_denied_blocked=No está permitido importar desde hosts bloqueados.
899-
migrate.permission_denied_private_ip=No está permitido importar desde direcciones IP privadas.
900898
migrate.invalid_local_path=La ruta local es inválida. No existe o no es un directorio.
901899
migrate.invalid_lfs_endpoint=El punto final de LFS no es válido.
902900
migrate.failed=Migración fallida: %v

options/locale/locale_fr-FR.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -833,8 +833,6 @@ migrate.clone_address=Migrer/Cloner depuis une URL
833833
migrate.clone_address_desc=L'URL HTTP(S) ou Git "clone" d'un dépôt existant
834834
migrate.clone_local_path=ou un chemin serveur local
835835
migrate.permission_denied=Vous n'êtes pas autorisé à importer des dépôts locaux.
836-
migrate.permission_denied_blocked=Vous n'êtes pas autorisé à importer à partir d'hôtes bloqués.
837-
migrate.permission_denied_private_ip=Vous n'êtes pas autorisé à importer depuis des adresses IP privées.
838836
migrate.invalid_local_path=Chemin local non valide, non existant ou n'étant pas un dossier.
839837
migrate.invalid_lfs_endpoint=Le point d'accès LFS n'est pas valide.
840838
migrate.failed=Echec de migration: %v

options/locale/locale_ja-JP.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -899,8 +899,6 @@ migrate.clone_address_desc=既存リポジトリの、HTTP(S)またはGit形式
899899
migrate.github_token_desc=Github APIはレート制限がありますが、移行をより速くするため、ここにカンマ区切りで複数のトークンを入力することができます。 警告: この機能を悪用すると、サービスプロバイダのポリシーに違反し、アカウントがブロックされる可能性があります。
900900
migrate.clone_local_path=、またはローカルサーバー上のパス
901901
migrate.permission_denied=ローカルリポジトリをインポートする権限がありません。
902-
migrate.permission_denied_blocked=ブロックしているホストからのインポートは禁止されています。
903-
migrate.permission_denied_private_ip=プライベートIPからのインポートは禁止されています。
904902
migrate.invalid_local_path=ローカルパスが無効です。 存在しないかディレクトリではありません。
905903
migrate.invalid_lfs_endpoint=LFS エンドポイントが無効です。
906904
migrate.failed=移行に失敗しました: %v

options/locale/locale_lv-LV.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -880,8 +880,6 @@ migrate.clone_address=Klonēšanas adrese
880880
migrate.clone_address_desc=Tā var būt HTTP(S) adrese vai Git 'clone' URL eksistējošam repozitorijam
881881
migrate.clone_local_path=vai servera lokālais ceļš
882882
migrate.permission_denied=Jums nav tiesību importēt lokālu repozitoriju.
883-
migrate.permission_denied_blocked=Nav atļauts veikt importu no bloķētiem serveriem.
884-
migrate.permission_denied_private_ip=Nav atļauts veikt importu no bloķētiem no privātām IP adresēm.
885883
migrate.invalid_local_path=Nederīgs lokālais ceļš. Tas neeksistē vai nav direktorija.
886884
migrate.invalid_lfs_endpoint=LFS galapunkts nav korekts.
887885
migrate.failed=Migrācija neizdevās: %v

options/locale/locale_pt-BR.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -840,8 +840,6 @@ migrate.clone_address_desc=URL HTTP (S) ou Git 'clone' de um repositório existe
840840
migrate.github_token_desc=Você pode colocar aqui um ou mais tokens separados com vírgula para tornar a migração mais rápida devido ao limite de taxa de API do Github. AVISO: abusar desse recurso pode violar a política do provedor de serviço e levar ao bloqueio da conta.
841841
migrate.clone_local_path=ou um caminho de servidor local
842842
migrate.permission_denied=Você não pode importar repositórios locais.
843-
migrate.permission_denied_blocked=Você não tem permissão para importar de origens bloqueadas.
844-
migrate.permission_denied_private_ip=Você não tem permissão para importar de IPs privados.
845843
migrate.invalid_local_path=O caminho local é inválido. Ele não existe ou não é um diretório.
846844
migrate.invalid_lfs_endpoint=O destino LFS não é válido.
847845
migrate.failed=Migração falhou: %v

options/locale/locale_pt-PT.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -898,8 +898,6 @@ migrate.clone_address_desc=O URL de clonagem HTTP(S) ou Git de um repositório e
898898
migrate.github_token_desc=Pode colocar aqui um ou mais códigos separados por vírgulas para tornar mais rápida a migração, para compensar a limitação de velocidade da API do GitHub. AVISO: O abuso desta funcionalidade poderá violar a política do seu fornecedor de serviço e levar ao bloqueio da conta.
899899
migrate.clone_local_path=ou um caminho no servidor local
900900
migrate.permission_denied=Não está autorizado a importar repositórios locais.
901-
migrate.permission_denied_blocked=Não tem permissão para importar a partir de servidores bloqueados.
902-
migrate.permission_denied_private_ip=Não tem permissão para importar a partir de IPs privados.
903901
migrate.invalid_local_path=O caminho local é inválido. Não existe ou não é uma pasta.
904902
migrate.invalid_lfs_endpoint=O destino LFS não é válido.
905903
migrate.failed=A migração falhou: %v

options/locale/locale_ru-RU.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -886,8 +886,6 @@ migrate.clone_address=Перенос / Клонирование по URL
886886
migrate.clone_address_desc=Это может быть HTTP/HTTPS/GIT адрес или локальный путь существующего репозитория на сервере.
887887
migrate.clone_local_path=или путь к локальному серверу
888888
migrate.permission_denied=У вас нет прав на импорт локальных репозиториев.
889-
migrate.permission_denied_blocked=Вам не разрешено импортировать с заблокированных узлов.
890-
migrate.permission_denied_private_ip=Вы не можете импортировать с приватных IP.
891889
migrate.invalid_local_path=Недопустимый локальный путь. Возможно он не существует или не является папкой.
892890
migrate.invalid_lfs_endpoint=Конечная точка LFS недействительна.
893891
migrate.failed=Миграция не удалась: %v

options/locale/locale_tr-TR.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -868,8 +868,6 @@ migrate.clone_address=URL'den Taşı / Klonla
868868
migrate.clone_address_desc=Varolan bir deponun HTTP(S) veya Git 'klonlama' URL'si
869869
migrate.clone_local_path=veya bir yerel sunucu yolu
870870
migrate.permission_denied=Yerel depoları içeri aktarma izniniz yok.
871-
migrate.permission_denied_blocked=Engellenen ana bilgisayarlardan içeri aktarmanıza izin verilmiyor.
872-
migrate.permission_denied_private_ip=Özel IP'lerden içeri aktarmanıza izin verilmiyor.
873871
migrate.invalid_local_path=Yerel yol geçersiz. Mevcut değil veya bir dizin değil.
874872
migrate.invalid_lfs_endpoint=LFS Uç noktası geçerli değil.
875873
migrate.failed=Göç başarısız: %v

options/locale/locale_uk-UA.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -860,8 +860,6 @@ migrate.clone_address=Міграція / клонувати з URL-адреси
860860
migrate.clone_address_desc=URL-адреса HTTP(S) або Git "clone" існуючого репозиторія
861861
migrate.clone_local_path=або шлях до локального серверу
862862
migrate.permission_denied=Вам не дозволено імпортувати локальні репозиторії.
863-
migrate.permission_denied_blocked=Вам не дозволено імпортувати з заблокованих хостів.
864-
migrate.permission_denied_private_ip=Вам не дозволено імпортувати з приватних IP-адрес.
865863
migrate.invalid_local_path=Локальний шлях недійсний. Він не існує або не є каталогом.
866864
migrate.invalid_lfs_endpoint=Помилкова кінцева точка LFS.
867865
migrate.failed=Міграція не вдалася: %v

options/locale/locale_zh-CN.ini

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -899,8 +899,6 @@ migrate.clone_address_desc=现有仓库的 HTTP(s) 或 Git "clone" URL
899899
migrate.github_token_desc=由于 Github API 速率限制,您可以在此处放置一个或多个以逗号分隔的令牌,以加快迁移速度。警告:滥用此功能可能会违反服务提供商的政策并导致帐户被封。
900900
migrate.clone_local_path=或服务器本地路径
901901
migrate.permission_denied=您没有获得导入本地仓库的权限。
902-
migrate.permission_denied_blocked=不允许从被屏蔽的主机导入。
903-
migrate.permission_denied_private_ip=不允许从私有IP导入。
904902
migrate.invalid_local_path=无效的本地路径,不存在或不是一个目录!
905903
migrate.invalid_lfs_endpoint=LFS 网址无效。
906904
migrate.failed=迁移失败:%v

options/locale/locale_zh-TW.ini

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -899,8 +899,7 @@ migrate.clone_address_desc=現有存儲庫的 HTTP(S) 或 Git Clone URL
899899
migrate.github_token_desc=由於 Github API 的速率限制,您可在此輸入一個或多個由半形逗號「,」分隔的 Token 來加快遷移速度。警告:濫用此功能可能會違反該服務提供者的政策並導致帳戶被封鎖。
900900
migrate.clone_local_path=或者是本地端伺服器路徑
901901
migrate.permission_denied=您並沒有導入本地儲存庫的權限。
902-
migrate.permission_denied_blocked=您未被允許從已封鎖的主機匯入。
903-
migrate.permission_denied_private_ip=您未被允許從私有 IP 匯入。
902+
migrate.permission_denied_blocked=您無法從未允許的主機匯入,請聯絡管理員檢查以下設定值 ALLOWED_DOMAINS/ALLOW_LOCALNETWORKS/BLOCKED_DOMAINS
904903
migrate.invalid_local_path=無效的本地路徑,該路徑不存在或不是一個目錄!
905904
migrate.invalid_lfs_endpoint=該 LFS 端點無效。
906905
migrate.failed=遷移失敗:%v
@@ -2043,6 +2042,7 @@ diff.file_suppressed=檔案差異因為檔案過大而無法顯示
20432042
diff.file_suppressed_line_too_long=檔案差異因為一行或多行太長而無法顯示
20442043
diff.too_many_files=本差異變更的檔案數量過多導致部分檔案未顯示
20452044
diff.show_more=顯示更多
2045+
diff.load=載入差異
20462046
diff.generated=generated
20472047
diff.vendored=vendored
20482048
diff.comment.placeholder=留言...

templates/repo/commits_list.tmpl

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
{{$userName}}
2424
{{end}}
2525
</td>
26-
<td class="sha">
26+
<td class="sha df">
27+
<button class="ui button copy-commit-sha df ac" data-clipboard-text="{{.ID}}">{{svg "octicon-copy" 14}}</button>
2728
{{$class := "ui sha label"}}
2829
{{if .Signature}}
2930
{{$class = (printf "%s%s" $class " isSigned")}}
@@ -66,7 +67,7 @@
6667
{{end}}
6768
</span>
6869
{{if IsMultilineCommitMessage .Message}}
69-
<button class="basic compact mini ui icon button commit-button"><i class="ellipsis horizontal icon"></i></button>
70+
<button class="ui button ellipsis-button" aria-expanded="false">...</button>
7071
{{end}}
7172
{{template "repo/commit_statuses" dict "Status" .Status "Statuses" .Statuses "root" $}}
7273
{{if IsMultilineCommitMessage .Message}}

0 commit comments

Comments
 (0)