BlueGit

timfa bluegit

Forks stap 2: synchroniseren met upstream (alleen fast-forward), UI + API

timfa Tim Falken · pushed by timfa

Authored 2026-10-27 · 3 weeks ago

Hash
dcb27648cdf6b0608789b1d66006d86358b75fcd
Parent
9a0f55f2
Pipeline
Passed
8 files changed +363 −73
internal/gitrepo/repo.go +18 −0
@@ -5,6 +5,7 @@ import (
5 5 "bufio"
6 6 "bytes"
7 7 "context"
8 "errors"
8 9 "fmt"
9 10 "io"
10 11 "os"
@@ -850,3 +851,20 @@ func Fork(gitBin, src, dir, hookBinary string) error {
850 851 }
851 852 return InstallHook(dir, hookBinary)
852 853 }
854
855 // ErrNotFastForward: de branch in de fork is afgeweken van upstream.
856 var ErrNotFastForward = errors.New("not fast-forward")
857
858 // PushBranch zet branch uit src door naar dst, alleen fast-forward (geen
859 // force). De pre-receive-hook van dst controleert rechten en bescherming.
860 func PushBranch(ctx context.Context, gitBin, src, dst, branch string, env []string) error {
861 out, err := run(ctx, gitBin, env, "-C", src, "push", dst, "refs/heads/"+branch+":refs/heads/"+branch)
862 if err != nil {
863 msg := out + " " + err.Error()
864 if strings.Contains(msg, "non-fast-forward") || strings.Contains(msg, "fetch first") {
865 return ErrNotFastForward
866 }
867 return classifyGit(err)
868 }
869 return nil
870 }
@@ -5,6 +5,7 @@ import (
5 "bufio"
5 "bufio"
6 "bytes"
6 "bytes"
7 "context"
7 "context"
8 "errors"
8 "fmt"
9 "fmt"
9 "io"
10 "io"
10 "os"
11 "os"
@@ -850,3 +851,20 @@ func Fork(gitBin, src, dir, hookBinary string) error {
850 }
851 }
851 return InstallHook(dir, hookBinary)
852 return InstallHook(dir, hookBinary)
852}
853}
854
855// ErrNotFastForward: de branch in de fork is afgeweken van upstream.
856var ErrNotFastForward = errors.New("not fast-forward")
857
858// PushBranch zet branch uit src door naar dst, alleen fast-forward (geen
859// force). De pre-receive-hook van dst controleert rechten en bescherming.
860func PushBranch(ctx context.Context, gitBin, src, dst, branch string, env []string) error {
861 out, err := run(ctx, gitBin, env, "-C", src, "push", dst, "refs/heads/"+branch+":refs/heads/"+branch)
862 if err != nil {
863 msg := out + " " + err.Error()
864 if strings.Contains(msg, "non-fast-forward") || strings.Contains(msg, "fetch first") {
865 return ErrNotFastForward
866 }
867 return classifyGit(err)
868 }
869 return nil
870}
internal/i18n/catalog_fork.go +104 −72
@@ -2,83 +2,115 @@ package i18n
2 2
3 3 func init() {
4 4 addCatalog(en, map[string]string{
5 "fork.button": "Fork",
6 "fork.tip": "Copy this repository with all branches and tags to your account or a group where you can write. The fork remembers where it came from.",
7 "fork.title": "Fork %s",
8 "fork.target": "Target",
9 "fork.name": "Name",
10 "fork.hint": "All branches and tags are copied. A fork of a private repository stays private.",
11 "fork.of": "Fork of",
12 "fork.ofTip": "This repository was forked; the link shows the upstream when you may see it.",
13 "fork.hidden": "Fork",
14 "fork.listTitle": "Forks",
15 "fork.none": "No forks you can see.",
16 "count.fork.one": "%d fork",
17 "count.fork.many": "%d forks",
18 "flash.forked": "Fork created",
19 "err.forkExists": "%s already exists; choose another name",
20 "err.forkDisk": "Not enough free disk space for this fork",
21 "err.forkGit": "fork failed: %s",
22 "err.forkPrivate": "a fork of a private repository cannot be made public",
5 "fork.sync": "Sync %s with upstream",
6 "fork.syncTip": "Fast-forwards this branch to the same branch in upstream. If this fork has its own commits on it, sync stops with a message; nothing is overwritten.",
7 "flash.synced": "%s synced with upstream",
8 "flash.syncUpToDate": "%s is already up to date",
9 "err.notFork": "this repository is not a fork",
10 "err.upstreamNoAccess": "you have no access to the upstream repository",
11 "err.upstreamBranch": "branch %s does not exist in upstream",
12 "err.syncNotFF": "%s has diverged from upstream and cannot be fast-forwarded; merge or rebase it yourself",
13 "fork.button": "Fork",
14 "fork.tip": "Copy this repository with all branches and tags to your account or a group where you can write. The fork remembers where it came from.",
15 "fork.title": "Fork %s",
16 "fork.target": "Target",
17 "fork.name": "Name",
18 "fork.hint": "All branches and tags are copied. A fork of a private repository stays private.",
19 "fork.of": "Fork of",
20 "fork.ofTip": "This repository was forked; the link shows the upstream when you may see it.",
21 "fork.hidden": "Fork",
22 "fork.listTitle": "Forks",
23 "fork.none": "No forks you can see.",
24 "count.fork.one": "%d fork",
25 "count.fork.many": "%d forks",
26 "flash.forked": "Fork created",
27 "err.forkExists": "%s already exists; choose another name",
28 "err.forkDisk": "Not enough free disk space for this fork",
29 "err.forkGit": "fork failed: %s",
30 "err.forkPrivate": "a fork of a private repository cannot be made public",
23 31 })
24 32 addCatalog(nl, map[string]string{
25 "fork.button": "Fork",
26 "fork.tip": "Kopieer deze repository met alle branches en tags naar je account of een groep waar je mag schrijven. De fork onthoudt waar hij vandaan komt.",
27 "fork.title": "%s forken",
28 "fork.target": "Doel",
29 "fork.name": "Naam",
30 "fork.hint": "Alle branches en tags worden gekopieerd. Een fork van een privé repository blijft privé.",
31 "fork.of": "Fork van",
32 "fork.ofTip": "Deze repository is een fork; de link toont de upstream als je die mag zien.",
33 "fork.hidden": "Fork",
34 "fork.listTitle": "Forks",
35 "fork.none": "Geen forks die je mag zien.",
36 "count.fork.one": "%d fork",
37 "count.fork.many": "%d forks",
38 "flash.forked": "Fork gemaakt",
39 "err.forkExists": "%s bestaat al; kies een andere naam",
40 "err.forkDisk": "Niet genoeg vrije schijfruimte voor deze fork",
41 "err.forkGit": "fork mislukt: %s",
42 "err.forkPrivate": "een fork van een privé repository kan niet openbaar worden",
33 "fork.sync": "%s synchroniseren met upstream",
34 "fork.syncTip": "Zet deze branch fast-forward door naar dezelfde branch in upstream. Heeft deze fork eigen commits op die branch, dan stopt de sync met een melding; er wordt niets overschreven.",
35 "flash.synced": "%s gesynchroniseerd met upstream",
36 "flash.syncUpToDate": "%s is al bijgewerkt",
37 "err.notFork": "deze repository is geen fork",
38 "err.upstreamNoAccess": "je hebt geen toegang tot de upstream-repository",
39 "err.upstreamBranch": "branch %s bestaat niet in upstream",
40 "err.syncNotFF": "%s is afgeweken van upstream en kan niet fast-forward; merge of rebase zelf",
41 "fork.button": "Fork",
42 "fork.tip": "Kopieer deze repository met alle branches en tags naar je account of een groep waar je mag schrijven. De fork onthoudt waar hij vandaan komt.",
43 "fork.title": "%s forken",
44 "fork.target": "Doel",
45 "fork.name": "Naam",
46 "fork.hint": "Alle branches en tags worden gekopieerd. Een fork van een privé repository blijft privé.",
47 "fork.of": "Fork van",
48 "fork.ofTip": "Deze repository is een fork; de link toont de upstream als je die mag zien.",
49 "fork.hidden": "Fork",
50 "fork.listTitle": "Forks",
51 "fork.none": "Geen forks die je mag zien.",
52 "count.fork.one": "%d fork",
53 "count.fork.many": "%d forks",
54 "flash.forked": "Fork gemaakt",
55 "err.forkExists": "%s bestaat al; kies een andere naam",
56 "err.forkDisk": "Niet genoeg vrije schijfruimte voor deze fork",
57 "err.forkGit": "fork mislukt: %s",
58 "err.forkPrivate": "een fork van een privé repository kan niet openbaar worden",
43 59 })
44 60 addCatalog(de, map[string]string{
45 "fork.button": "Fork",
46 "fork.tip": "Kopiere dieses Repository mit allen Branches und Tags in dein Konto oder eine Gruppe, in der du schreiben darfst. Der Fork merkt sich seine Herkunft.",
47 "fork.title": "%s forken",
48 "fork.target": "Ziel",
49 "fork.name": "Name",
50 "fork.hint": "Alle Branches und Tags werden kopiert. Ein Fork eines privaten Repositorys bleibt privat.",
51 "fork.of": "Fork von",
52 "fork.ofTip": "Dieses Repository ist ein Fork; der Link zeigt das Upstream, wenn du es sehen darfst.",
53 "fork.hidden": "Fork",
54 "fork.listTitle": "Forks",
55 "fork.none": "Keine sichtbaren Forks.",
56 "count.fork.one": "%d Fork",
57 "count.fork.many": "%d Forks",
58 "flash.forked": "Fork erstellt",
59 "err.forkExists": "%s existiert bereits; wähle einen anderen Namen",
60 "err.forkDisk": "Nicht genug freier Speicher für diesen Fork",
61 "err.forkGit": "Fork fehlgeschlagen: %s",
62 "err.forkPrivate": "ein Fork eines privaten Repositorys kann nicht öffentlich werden",
61 "fork.sync": "%s mit Upstream synchronisieren",
62 "fork.syncTip": "Spult diesen Branch auf denselben Branch im Upstream vor (Fast-Forward). Hat dieser Fork eigene Commits darauf, bricht die Synchronisation mit einer Meldung ab; nichts wird überschrieben.",
63 "flash.synced": "%s mit Upstream synchronisiert",
64 "flash.syncUpToDate": "%s ist bereits aktuell",
65 "err.notFork": "dieses Repository ist kein Fork",
66 "err.upstreamNoAccess": "du hast keinen Zugriff auf das Upstream-Repository",
67 "err.upstreamBranch": "Branch %s existiert im Upstream nicht",
68 "err.syncNotFF": "%s ist vom Upstream abgewichen und kann nicht vorgespult werden; merge oder rebase selbst",
69 "fork.button": "Fork",
70 "fork.tip": "Kopiere dieses Repository mit allen Branches und Tags in dein Konto oder eine Gruppe, in der du schreiben darfst. Der Fork merkt sich seine Herkunft.",
71 "fork.title": "%s forken",
72 "fork.target": "Ziel",
73 "fork.name": "Name",
74 "fork.hint": "Alle Branches und Tags werden kopiert. Ein Fork eines privaten Repositorys bleibt privat.",
75 "fork.of": "Fork von",
76 "fork.ofTip": "Dieses Repository ist ein Fork; der Link zeigt das Upstream, wenn du es sehen darfst.",
77 "fork.hidden": "Fork",
78 "fork.listTitle": "Forks",
79 "fork.none": "Keine sichtbaren Forks.",
80 "count.fork.one": "%d Fork",
81 "count.fork.many": "%d Forks",
82 "flash.forked": "Fork erstellt",
83 "err.forkExists": "%s existiert bereits; wähle einen anderen Namen",
84 "err.forkDisk": "Nicht genug freier Speicher für diesen Fork",
85 "err.forkGit": "Fork fehlgeschlagen: %s",
86 "err.forkPrivate": "ein Fork eines privaten Repositorys kann nicht öffentlich werden",
63 87 })
64 88 addCatalog(fr, map[string]string{
65 "fork.button": "Fork",
66 "fork.tip": "Copie ce dépôt avec toutes les branches et tags vers ton compte ou un groupe où tu peux écrire. Le fork se souvient de son origine.",
67 "fork.title": "Forker %s",
68 "fork.target": "Cible",
69 "fork.name": "Nom",
70 "fork.hint": "Toutes les branches et tags sont copiés. Un fork d'un dépôt privé reste privé.",
71 "fork.of": "Fork de",
72 "fork.ofTip": "Ce dépôt est un fork ; le lien montre l'upstream si tu peux le voir.",
73 "fork.hidden": "Fork",
74 "fork.listTitle": "Forks",
75 "fork.none": "Aucun fork visible.",
76 "count.fork.one": "%d fork",
77 "count.fork.many": "%d forks",
78 "flash.forked": "Fork créé",
79 "err.forkExists": "%s existe déjà ; choisis un autre nom",
80 "err.forkDisk": "Pas assez d'espace disque libre pour ce fork",
81 "err.forkGit": "échec du fork : %s",
82 "err.forkPrivate": "un fork d'un dépôt privé ne peut pas devenir public",
89 "fork.sync": "Synchroniser %s avec l'upstream",
90 "fork.syncTip": "Avance cette branche en fast-forward jusqu'à la même branche de l'upstream. Si ce fork a ses propres commits dessus, la synchronisation s'arrête avec un message ; rien n'est écrasé.",
91 "flash.synced": "%s synchronisé avec l'upstream",
92 "flash.syncUpToDate": "%s est déjà à jour",
93 "err.notFork": "ce dépôt n'est pas un fork",
94 "err.upstreamNoAccess": "tu n'as pas accès au dépôt upstream",
95 "err.upstreamBranch": "la branche %s n'existe pas dans l'upstream",
96 "err.syncNotFF": "%s a divergé de l'upstream et ne peut pas avancer en fast-forward ; fais un merge ou un rebase toi-même",
97 "fork.button": "Fork",
98 "fork.tip": "Copie ce dépôt avec toutes les branches et tags vers ton compte ou un groupe où tu peux écrire. Le fork se souvient de son origine.",
99 "fork.title": "Forker %s",
100 "fork.target": "Cible",
101 "fork.name": "Nom",
102 "fork.hint": "Toutes les branches et tags sont copiés. Un fork d'un dépôt privé reste privé.",
103 "fork.of": "Fork de",
104 "fork.ofTip": "Ce dépôt est un fork ; le lien montre l'upstream si tu peux le voir.",
105 "fork.hidden": "Fork",
106 "fork.listTitle": "Forks",
107 "fork.none": "Aucun fork visible.",
108 "count.fork.one": "%d fork",
109 "count.fork.many": "%d forks",
110 "flash.forked": "Fork créé",
111 "err.forkExists": "%s existe déjà ; choisis un autre nom",
112 "err.forkDisk": "Pas assez d'espace disque libre pour ce fork",
113 "err.forkGit": "échec du fork : %s",
114 "err.forkPrivate": "un fork d'un dépôt privé ne peut pas devenir public",
83 115 })
84 116 }
@@ -2,83 +2,115 @@ package i18n
2
2
3func init() {
3func init() {
4 addCatalog(en, map[string]string{
4 addCatalog(en, map[string]string{
5 "fork.button": "Fork",
5 "fork.sync": "Sync %s with upstream",
6 "fork.tip": "Copy this repository with all branches and tags to your account or a group where you can write. The fork remembers where it came from.",
6 "fork.syncTip": "Fast-forwards this branch to the same branch in upstream. If this fork has its own commits on it, sync stops with a message; nothing is overwritten.",
7 "fork.title": "Fork %s",
7 "flash.synced": "%s synced with upstream",
8 "fork.target": "Target",
8 "flash.syncUpToDate": "%s is already up to date",
9 "fork.name": "Name",
9 "err.notFork": "this repository is not a fork",
10 "fork.hint": "All branches and tags are copied. A fork of a private repository stays private.",
10 "err.upstreamNoAccess": "you have no access to the upstream repository",
11 "fork.of": "Fork of",
11 "err.upstreamBranch": "branch %s does not exist in upstream",
12 "fork.ofTip": "This repository was forked; the link shows the upstream when you may see it.",
12 "err.syncNotFF": "%s has diverged from upstream and cannot be fast-forwarded; merge or rebase it yourself",
13 "fork.hidden": "Fork",
13 "fork.button": "Fork",
14 "fork.listTitle": "Forks",
14 "fork.tip": "Copy this repository with all branches and tags to your account or a group where you can write. The fork remembers where it came from.",
15 "fork.none": "No forks you can see.",
15 "fork.title": "Fork %s",
16 "count.fork.one": "%d fork",
16 "fork.target": "Target",
17 "count.fork.many": "%d forks",
17 "fork.name": "Name",
18 "flash.forked": "Fork created",
18 "fork.hint": "All branches and tags are copied. A fork of a private repository stays private.",
19 "err.forkExists": "%s already exists; choose another name",
19 "fork.of": "Fork of",
20 "err.forkDisk": "Not enough free disk space for this fork",
20 "fork.ofTip": "This repository was forked; the link shows the upstream when you may see it.",
21 "err.forkGit": "fork failed: %s",
21 "fork.hidden": "Fork",
22 "err.forkPrivate": "a fork of a private repository cannot be made public",
22 "fork.listTitle": "Forks",
23 "fork.none": "No forks you can see.",
24 "count.fork.one": "%d fork",
25 "count.fork.many": "%d forks",
26 "flash.forked": "Fork created",
27 "err.forkExists": "%s already exists; choose another name",
28 "err.forkDisk": "Not enough free disk space for this fork",
29 "err.forkGit": "fork failed: %s",
30 "err.forkPrivate": "a fork of a private repository cannot be made public",
23 })
31 })
24 addCatalog(nl, map[string]string{
32 addCatalog(nl, map[string]string{
25 "fork.button": "Fork",
33 "fork.sync": "%s synchroniseren met upstream",
26 "fork.tip": "Kopieer deze repository met alle branches en tags naar je account of een groep waar je mag schrijven. De fork onthoudt waar hij vandaan komt.",
34 "fork.syncTip": "Zet deze branch fast-forward door naar dezelfde branch in upstream. Heeft deze fork eigen commits op die branch, dan stopt de sync met een melding; er wordt niets overschreven.",
27 "fork.title": "%s forken",
35 "flash.synced": "%s gesynchroniseerd met upstream",
28 "fork.target": "Doel",
36 "flash.syncUpToDate": "%s is al bijgewerkt",
29 "fork.name": "Naam",
37 "err.notFork": "deze repository is geen fork",
30 "fork.hint": "Alle branches en tags worden gekopieerd. Een fork van een privé repository blijft privé.",
38 "err.upstreamNoAccess": "je hebt geen toegang tot de upstream-repository",
31 "fork.of": "Fork van",
39 "err.upstreamBranch": "branch %s bestaat niet in upstream",
32 "fork.ofTip": "Deze repository is een fork; de link toont de upstream als je die mag zien.",
40 "err.syncNotFF": "%s is afgeweken van upstream en kan niet fast-forward; merge of rebase zelf",
33 "fork.hidden": "Fork",
41 "fork.button": "Fork",
34 "fork.listTitle": "Forks",
42 "fork.tip": "Kopieer deze repository met alle branches en tags naar je account of een groep waar je mag schrijven. De fork onthoudt waar hij vandaan komt.",
35 "fork.none": "Geen forks die je mag zien.",
43 "fork.title": "%s forken",
36 "count.fork.one": "%d fork",
44 "fork.target": "Doel",
37 "count.fork.many": "%d forks",
45 "fork.name": "Naam",
38 "flash.forked": "Fork gemaakt",
46 "fork.hint": "Alle branches en tags worden gekopieerd. Een fork van een privé repository blijft privé.",
39 "err.forkExists": "%s bestaat al; kies een andere naam",
47 "fork.of": "Fork van",
40 "err.forkDisk": "Niet genoeg vrije schijfruimte voor deze fork",
48 "fork.ofTip": "Deze repository is een fork; de link toont de upstream als je die mag zien.",
41 "err.forkGit": "fork mislukt: %s",
49 "fork.hidden": "Fork",
42 "err.forkPrivate": "een fork van een privé repository kan niet openbaar worden",
50 "fork.listTitle": "Forks",
51 "fork.none": "Geen forks die je mag zien.",
52 "count.fork.one": "%d fork",
53 "count.fork.many": "%d forks",
54 "flash.forked": "Fork gemaakt",
55 "err.forkExists": "%s bestaat al; kies een andere naam",
56 "err.forkDisk": "Niet genoeg vrije schijfruimte voor deze fork",
57 "err.forkGit": "fork mislukt: %s",
58 "err.forkPrivate": "een fork van een privé repository kan niet openbaar worden",
43 })
59 })
44 addCatalog(de, map[string]string{
60 addCatalog(de, map[string]string{
45 "fork.button": "Fork",
61 "fork.sync": "%s mit Upstream synchronisieren",
46 "fork.tip": "Kopiere dieses Repository mit allen Branches und Tags in dein Konto oder eine Gruppe, in der du schreiben darfst. Der Fork merkt sich seine Herkunft.",
62 "fork.syncTip": "Spult diesen Branch auf denselben Branch im Upstream vor (Fast-Forward). Hat dieser Fork eigene Commits darauf, bricht die Synchronisation mit einer Meldung ab; nichts wird überschrieben.",
47 "fork.title": "%s forken",
63 "flash.synced": "%s mit Upstream synchronisiert",
48 "fork.target": "Ziel",
64 "flash.syncUpToDate": "%s ist bereits aktuell",
49 "fork.name": "Name",
65 "err.notFork": "dieses Repository ist kein Fork",
50 "fork.hint": "Alle Branches und Tags werden kopiert. Ein Fork eines privaten Repositorys bleibt privat.",
66 "err.upstreamNoAccess": "du hast keinen Zugriff auf das Upstream-Repository",
51 "fork.of": "Fork von",
67 "err.upstreamBranch": "Branch %s existiert im Upstream nicht",
52 "fork.ofTip": "Dieses Repository ist ein Fork; der Link zeigt das Upstream, wenn du es sehen darfst.",
68 "err.syncNotFF": "%s ist vom Upstream abgewichen und kann nicht vorgespult werden; merge oder rebase selbst",
53 "fork.hidden": "Fork",
69 "fork.button": "Fork",
54 "fork.listTitle": "Forks",
70 "fork.tip": "Kopiere dieses Repository mit allen Branches und Tags in dein Konto oder eine Gruppe, in der du schreiben darfst. Der Fork merkt sich seine Herkunft.",
55 "fork.none": "Keine sichtbaren Forks.",
71 "fork.title": "%s forken",
56 "count.fork.one": "%d Fork",
72 "fork.target": "Ziel",
57 "count.fork.many": "%d Forks",
73 "fork.name": "Name",
58 "flash.forked": "Fork erstellt",
74 "fork.hint": "Alle Branches und Tags werden kopiert. Ein Fork eines privaten Repositorys bleibt privat.",
59 "err.forkExists": "%s existiert bereits; wähle einen anderen Namen",
75 "fork.of": "Fork von",
60 "err.forkDisk": "Nicht genug freier Speicher für diesen Fork",
76 "fork.ofTip": "Dieses Repository ist ein Fork; der Link zeigt das Upstream, wenn du es sehen darfst.",
61 "err.forkGit": "Fork fehlgeschlagen: %s",
77 "fork.hidden": "Fork",
62 "err.forkPrivate": "ein Fork eines privaten Repositorys kann nicht öffentlich werden",
78 "fork.listTitle": "Forks",
79 "fork.none": "Keine sichtbaren Forks.",
80 "count.fork.one": "%d Fork",
81 "count.fork.many": "%d Forks",
82 "flash.forked": "Fork erstellt",
83 "err.forkExists": "%s existiert bereits; wähle einen anderen Namen",
84 "err.forkDisk": "Nicht genug freier Speicher für diesen Fork",
85 "err.forkGit": "Fork fehlgeschlagen: %s",
86 "err.forkPrivate": "ein Fork eines privaten Repositorys kann nicht öffentlich werden",
63 })
87 })
64 addCatalog(fr, map[string]string{
88 addCatalog(fr, map[string]string{
65 "fork.button": "Fork",
89 "fork.sync": "Synchroniser %s avec l'upstream",
66 "fork.tip": "Copie ce dépôt avec toutes les branches et tags vers ton compte ou un groupe où tu peux écrire. Le fork se souvient de son origine.",
90 "fork.syncTip": "Avance cette branche en fast-forward jusqu'à la même branche de l'upstream. Si ce fork a ses propres commits dessus, la synchronisation s'arrête avec un message ; rien n'est écrasé.",
67 "fork.title": "Forker %s",
91 "flash.synced": "%s synchronisé avec l'upstream",
68 "fork.target": "Cible",
92 "flash.syncUpToDate": "%s est déjà à jour",
69 "fork.name": "Nom",
93 "err.notFork": "ce dépôt n'est pas un fork",
70 "fork.hint": "Toutes les branches et tags sont copiés. Un fork d'un dépôt privé reste privé.",
94 "err.upstreamNoAccess": "tu n'as pas accès au dépôt upstream",
71 "fork.of": "Fork de",
95 "err.upstreamBranch": "la branche %s n'existe pas dans l'upstream",
72 "fork.ofTip": "Ce dépôt est un fork ; le lien montre l'upstream si tu peux le voir.",
96 "err.syncNotFF": "%s a divergé de l'upstream et ne peut pas avancer en fast-forward ; fais un merge ou un rebase toi-même",
73 "fork.hidden": "Fork",
97 "fork.button": "Fork",
74 "fork.listTitle": "Forks",
98 "fork.tip": "Copie ce dépôt avec toutes les branches et tags vers ton compte ou un groupe où tu peux écrire. Le fork se souvient de son origine.",
75 "fork.none": "Aucun fork visible.",
99 "fork.title": "Forker %s",
76 "count.fork.one": "%d fork",
100 "fork.target": "Cible",
77 "count.fork.many": "%d forks",
101 "fork.name": "Nom",
78 "flash.forked": "Fork créé",
102 "fork.hint": "Toutes les branches et tags sont copiés. Un fork d'un dépôt privé reste privé.",
79 "err.forkExists": "%s existe déjà ; choisis un autre nom",
103 "fork.of": "Fork de",
80 "err.forkDisk": "Pas assez d'espace disque libre pour ce fork",
104 "fork.ofTip": "Ce dépôt est un fork ; le lien montre l'upstream si tu peux le voir.",
81 "err.forkGit": "échec du fork : %s",
105 "fork.hidden": "Fork",
82 "err.forkPrivate": "un fork d'un dépôt privé ne peut pas devenir public",
106 "fork.listTitle": "Forks",
107 "fork.none": "Aucun fork visible.",
108 "count.fork.one": "%d fork",
109 "count.fork.many": "%d forks",
110 "flash.forked": "Fork créé",
111 "err.forkExists": "%s existe déjà ; choisis un autre nom",
112 "err.forkDisk": "Pas assez d'espace disque libre pour ce fork",
113 "err.forkGit": "échec du fork : %s",
114 "err.forkPrivate": "un fork d'un dépôt privé ne peut pas devenir public",
83 })
115 })
84}
116}
internal/server/api_openapi.go +10 −0
@@ -137,6 +137,7 @@ func apiBinds() []apiBind {
137 137 {path: "/groups/{path}/secrets", method: "GET", code: "200", resp: "Secret", array: true},
138 138 {path: "/groups/{path}/secrets", method: "POST", code: "200", body: "SecretWrite", resp: "SecretName"},
139 139 {path: "/projects/{owner}/{repo}/fork", method: "POST", code: "201", body: "ForkCreate", resp: "ForkedProject"},
140 {path: "/projects/{owner}/{repo}/sync-upstream", method: "POST", code: "200", body: "SyncUpstream", resp: "SyncResult"},
140 141 {path: "/projects/{owner}/{repo}/forks", method: "GET", code: "200", resp: "ForkedProject", array: true},
141 142 {path: "/projects/{owner}/{repo}/secrets/inherited", method: "GET", code: "200", resp: "InheritedSecret", array: true},
142 143 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
@@ -411,6 +412,15 @@ func apiSchemas() map[string]any {
411 412 "visibility": str("public or private."),
412 413 "forked_from": str("Upstream owner/name (only in the fork response)."),
413 414 }),
415 "SyncUpstream": obj("Fast-forward a fork branch to the same branch in upstream. Never forces; a diverged branch gives 409.", map[string]any{
416 "branch": str("Branch to sync. Default: the fork's default branch."),
417 }),
418 "SyncResult": obj("Outcome of an upstream sync.", map[string]any{
419 "branch": str("Branch."),
420 "before": str("Fork commit before (empty if the branch was new)."),
421 "after": str("Fork commit after."),
422 "up_to_date": boolean("Nothing to do."),
423 }),
414 424 "ForkCreate": obj("Fork a project with all branches and tags. Objects are hard-linked on the server disk. A fork of a private project is private and cannot be made public. The response adds forked_from.", map[string]any{
415 425 "namespace": str("Group path where you are at least developer. Empty: your own account."),
416 426 "name": str("Optional new name. Default keeps the upstream name. 409 if it already exists."),
@@ -137,6 +137,7 @@ func apiBinds() []apiBind {
137 {path: "/groups/{path}/secrets", method: "GET", code: "200", resp: "Secret", array: true},
137 {path: "/groups/{path}/secrets", method: "GET", code: "200", resp: "Secret", array: true},
138 {path: "/groups/{path}/secrets", method: "POST", code: "200", body: "SecretWrite", resp: "SecretName"},
138 {path: "/groups/{path}/secrets", method: "POST", code: "200", body: "SecretWrite", resp: "SecretName"},
139 {path: "/projects/{owner}/{repo}/fork", method: "POST", code: "201", body: "ForkCreate", resp: "ForkedProject"},
139 {path: "/projects/{owner}/{repo}/fork", method: "POST", code: "201", body: "ForkCreate", resp: "ForkedProject"},
140 {path: "/projects/{owner}/{repo}/sync-upstream", method: "POST", code: "200", body: "SyncUpstream", resp: "SyncResult"},
140 {path: "/projects/{owner}/{repo}/forks", method: "GET", code: "200", resp: "ForkedProject", array: true},
141 {path: "/projects/{owner}/{repo}/forks", method: "GET", code: "200", resp: "ForkedProject", array: true},
141 {path: "/projects/{owner}/{repo}/secrets/inherited", method: "GET", code: "200", resp: "InheritedSecret", array: true},
142 {path: "/projects/{owner}/{repo}/secrets/inherited", method: "GET", code: "200", resp: "InheritedSecret", array: true},
142 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
143 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
@@ -411,6 +412,15 @@ func apiSchemas() map[string]any {
411 "visibility": str("public or private."),
412 "visibility": str("public or private."),
412 "forked_from": str("Upstream owner/name (only in the fork response)."),
413 "forked_from": str("Upstream owner/name (only in the fork response)."),
413 }),
414 }),
415 "SyncUpstream": obj("Fast-forward a fork branch to the same branch in upstream. Never forces; a diverged branch gives 409.", map[string]any{
416 "branch": str("Branch to sync. Default: the fork's default branch."),
417 }),
418 "SyncResult": obj("Outcome of an upstream sync.", map[string]any{
419 "branch": str("Branch."),
420 "before": str("Fork commit before (empty if the branch was new)."),
421 "after": str("Fork commit after."),
422 "up_to_date": boolean("Nothing to do."),
423 }),
414 "ForkCreate": obj("Fork a project with all branches and tags. Objects are hard-linked on the server disk. A fork of a private project is private and cannot be made public. The response adds forked_from.", map[string]any{
424 "ForkCreate": obj("Fork a project with all branches and tags. Objects are hard-linked on the server disk. A fork of a private project is private and cannot be made public. The response adds forked_from.", map[string]any{
415 "namespace": str("Group path where you are at least developer. Empty: your own account."),
425 "namespace": str("Group path where you are at least developer. Empty: your own account."),
416 "name": str("Optional new name. Default keeps the upstream name. 409 if it already exists."),
426 "name": str("Optional new name. Default keeps the upstream name. 409 if it already exists."),
internal/server/api_routes.go +1 −0
@@ -88,6 +88,7 @@ var apiCatalog = []apiRoute{
88 88 {http.MethodGet, "/api/v1/projects/{owner}/{repo}", access.ScopeRepoRead, authOptional, "Get project", (*Server).apiGetProject},
89 89 {http.MethodPut, "/api/v1/projects/{owner}/{repo}", access.ScopeWrite, authUser, "Update project", (*Server).apiPutProject},
90 90 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/fork", access.ScopeWrite, authUser, "Fork a project with all branches and tags. Body {namespace: group path or empty for your account, name: optional}. 409 if the name is taken. A fork of a private project is private.", (*Server).apiForkProject},
91 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/sync-upstream", access.ScopeWrite, authUser, "Fast-forward a branch of this fork to upstream. Body {branch: optional, default branch}. 409 when the fork has diverged (no force). Needs developer on the fork and read access to upstream.", (*Server).apiSyncUpstream},
91 92 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/forks", access.ScopeRead, authUser, "List forks of a project you can see.", (*Server).apiListForks},
92 93 {http.MethodDelete, "/api/v1/projects/{owner}/{repo}", access.ScopeWrite, authUser, "Delete project. A running doNotInterrupt job makes this 409 unless the query has force=true.", (*Server).apiDeleteProject},
93 94 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/star", access.ScopeWrite, authUser, "Toggle star", (*Server).apiStar},
@@ -88,6 +88,7 @@ var apiCatalog = []apiRoute{
88 {http.MethodGet, "/api/v1/projects/{owner}/{repo}", access.ScopeRepoRead, authOptional, "Get project", (*Server).apiGetProject},
88 {http.MethodGet, "/api/v1/projects/{owner}/{repo}", access.ScopeRepoRead, authOptional, "Get project", (*Server).apiGetProject},
89 {http.MethodPut, "/api/v1/projects/{owner}/{repo}", access.ScopeWrite, authUser, "Update project", (*Server).apiPutProject},
89 {http.MethodPut, "/api/v1/projects/{owner}/{repo}", access.ScopeWrite, authUser, "Update project", (*Server).apiPutProject},
90 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/fork", access.ScopeWrite, authUser, "Fork a project with all branches and tags. Body {namespace: group path or empty for your account, name: optional}. 409 if the name is taken. A fork of a private project is private.", (*Server).apiForkProject},
90 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/fork", access.ScopeWrite, authUser, "Fork a project with all branches and tags. Body {namespace: group path or empty for your account, name: optional}. 409 if the name is taken. A fork of a private project is private.", (*Server).apiForkProject},
91 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/sync-upstream", access.ScopeWrite, authUser, "Fast-forward a branch of this fork to upstream. Body {branch: optional, default branch}. 409 when the fork has diverged (no force). Needs developer on the fork and read access to upstream.", (*Server).apiSyncUpstream},
91 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/forks", access.ScopeRead, authUser, "List forks of a project you can see.", (*Server).apiListForks},
92 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/forks", access.ScopeRead, authUser, "List forks of a project you can see.", (*Server).apiListForks},
92 {http.MethodDelete, "/api/v1/projects/{owner}/{repo}", access.ScopeWrite, authUser, "Delete project. A running doNotInterrupt job makes this 409 unless the query has force=true.", (*Server).apiDeleteProject},
93 {http.MethodDelete, "/api/v1/projects/{owner}/{repo}", access.ScopeWrite, authUser, "Delete project. A running doNotInterrupt job makes this 409 unless the query has force=true.", (*Server).apiDeleteProject},
93 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/star", access.ScopeWrite, authUser, "Toggle star", (*Server).apiStar},
94 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/star", access.ScopeWrite, authUser, "Toggle star", (*Server).apiStar},
internal/server/fork_sync_test.go added +124 −0
@@ -0,0 +1,124 @@
1 package server
2
3 import (
4 "context"
5 "gitlab.com/Timfa/bluegit/internal/gitrepo"
6 "net/http"
7 "net/http/httptest"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "testing"
12 "time"
13
14 "gitlab.com/Timfa/bluegit/internal/auth"
15 "gitlab.com/Timfa/bluegit/internal/config"
16 "gitlab.com/Timfa/bluegit/internal/store"
17 )
18
19 func TestForkSyncUpstream(t *testing.T) {
20 if _, err := exec.LookPath("git"); err != nil {
21 t.Skip("git ontbreekt")
22 }
23 storage := t.TempDir()
24 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
25 if err != nil {
26 t.Fatal(err)
27 }
28 t.Cleanup(func() { _ = st.Close() })
29 ctx := context.Background()
30 ada, err := st.UpsertUser(ctx, 1, "ada", "", false)
31 if err != nil {
32 t.Fatal(err)
33 }
34 dev, err := st.UpsertUser(ctx, 2, "dev", "", false)
35 if err != nil {
36 t.Fatal(err)
37 }
38 issue := func(u store.User) string {
39 plain, _, err := st.IssueToken(ctx, u.ID, store.TokenRequest{Name: u.Username, Scopes: "api", ExpiresAt: time.Time{}})
40 if err != nil {
41 t.Fatal(err)
42 }
43 return plain
44 }
45 adaTok, devTok := issue(ada), issue(dev)
46 cfg := config.Config{
47 BaseURL: "http://127.0.0.1:9", StoragePath: storage,
48 Auth: config.Auth{Mode: "dev", DevUser: "ada", DevAuthID: 1},
49 Git: config.Git{Binary: "git", DefaultBranch: "master"},
50 }
51 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "ada", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true", StateDir: t.TempDir()}
52 ts := httptest.NewServer(srv.Handler())
53 t.Cleanup(ts.Close)
54
55 call := func(method, path, token, body string) (int, string) {
56 t.Helper()
57 req, _ := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
58 if body != "" {
59 req.Header.Set("Content-Type", "application/json")
60 }
61 req.Header.Set("Authorization", "Bearer "+token)
62 res, err := http.DefaultClient.Do(req)
63 if err != nil {
64 t.Fatal(err)
65 }
66 return res.StatusCode, read(t, res)
67 }
68 if code, body := call(http.MethodPost, "/api/v1/projects", adaTok, `{"name":"App","visibility":"public","initialize_with_readme":true}`); code != 201 {
69 t.Fatalf("project %d %s", code, body)
70 }
71 app, _ := st.RepoByPath(ctx, "ada", "app")
72 if code, body := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{}`); code != 201 {
73 t.Fatalf("fork %d %s", code, body)
74 }
75 updir := gitrepo.Dir(storage, "ada", "app")
76 fdir := gitrepo.Dir(storage, "dev", "app")
77 commit := func(dir, msg string) string {
78 t.Helper()
79 tree, _ := exec.Command("git", "-C", dir, "rev-parse", "master^{tree}").Output()
80 cmd := exec.Command("git", "-C", dir, "commit-tree", strings.TrimSpace(string(tree)), "-p", "master", "-m", msg)
81 cmd.Env = append(cmd.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@x", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@x")
82 out, err := cmd.Output()
83 if err != nil {
84 t.Fatal(err)
85 }
86 sha := strings.TrimSpace(string(out))
87 if out, err := exec.Command("git", "-C", dir, "update-ref", "refs/heads/master", sha).CombinedOutput(); err != nil {
88 t.Fatalf("%s", out)
89 }
90 return sha
91 }
92 up1 := commit(updir, "upstream 1")
93 code, body := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{}`)
94 if code != 200 || !strings.Contains(body, up1) {
95 t.Fatalf("sync: %d %s", code, body)
96 }
97 if code, body := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{"branch":"master"}`); code != 200 || !strings.Contains(body, `"up_to_date":true`) {
98 t.Fatalf("up to date: %d %s", code, body)
99 }
100 // ada (geen schrijfrechten op de fork) mag niet
101 if code, _ := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", adaTok, `{}`); code != 403 && code != 404 {
102 t.Fatalf("ada: %d", code)
103 }
104 // afgeweken: 409, niets overschreven
105 mine := commit(fdir, "eigen")
106 commit(updir, "upstream 2")
107 if code, body := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{}`); code != 409 {
108 t.Fatalf("diverged: %d %s", code, body)
109 }
110 if out, _ := exec.Command("git", "-C", fdir, "rev-parse", "master").Output(); strings.TrimSpace(string(out)) != mine {
111 t.Fatal("fork overschreven")
112 }
113 if code, _ := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{"branch":"nope"}`); code != 404 {
114 t.Fatalf("onbekende branch: %d", code)
115 }
116 // upstream wordt privé: dev heeft geen toegang meer
117 if err := st.UpdateRepo(ctx, app.ID, "", "private"); err != nil {
118 t.Fatal(err)
119 }
120 code, body = call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{}`)
121 if code != 403 || strings.Contains(body, "ada/app") {
122 t.Fatalf("privé upstream: %d %s", code, body)
123 }
124 }
@@ -0,0 +1,124 @@
1package server
2
3import (
4 "context"
5 "gitlab.com/Timfa/bluegit/internal/gitrepo"
6 "net/http"
7 "net/http/httptest"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "testing"
12 "time"
13
14 "gitlab.com/Timfa/bluegit/internal/auth"
15 "gitlab.com/Timfa/bluegit/internal/config"
16 "gitlab.com/Timfa/bluegit/internal/store"
17)
18
19func TestForkSyncUpstream(t *testing.T) {
20 if _, err := exec.LookPath("git"); err != nil {
21 t.Skip("git ontbreekt")
22 }
23 storage := t.TempDir()
24 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
25 if err != nil {
26 t.Fatal(err)
27 }
28 t.Cleanup(func() { _ = st.Close() })
29 ctx := context.Background()
30 ada, err := st.UpsertUser(ctx, 1, "ada", "", false)
31 if err != nil {
32 t.Fatal(err)
33 }
34 dev, err := st.UpsertUser(ctx, 2, "dev", "", false)
35 if err != nil {
36 t.Fatal(err)
37 }
38 issue := func(u store.User) string {
39 plain, _, err := st.IssueToken(ctx, u.ID, store.TokenRequest{Name: u.Username, Scopes: "api", ExpiresAt: time.Time{}})
40 if err != nil {
41 t.Fatal(err)
42 }
43 return plain
44 }
45 adaTok, devTok := issue(ada), issue(dev)
46 cfg := config.Config{
47 BaseURL: "http://127.0.0.1:9", StoragePath: storage,
48 Auth: config.Auth{Mode: "dev", DevUser: "ada", DevAuthID: 1},
49 Git: config.Git{Binary: "git", DefaultBranch: "master"},
50 }
51 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "ada", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true", StateDir: t.TempDir()}
52 ts := httptest.NewServer(srv.Handler())
53 t.Cleanup(ts.Close)
54
55 call := func(method, path, token, body string) (int, string) {
56 t.Helper()
57 req, _ := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
58 if body != "" {
59 req.Header.Set("Content-Type", "application/json")
60 }
61 req.Header.Set("Authorization", "Bearer "+token)
62 res, err := http.DefaultClient.Do(req)
63 if err != nil {
64 t.Fatal(err)
65 }
66 return res.StatusCode, read(t, res)
67 }
68 if code, body := call(http.MethodPost, "/api/v1/projects", adaTok, `{"name":"App","visibility":"public","initialize_with_readme":true}`); code != 201 {
69 t.Fatalf("project %d %s", code, body)
70 }
71 app, _ := st.RepoByPath(ctx, "ada", "app")
72 if code, body := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{}`); code != 201 {
73 t.Fatalf("fork %d %s", code, body)
74 }
75 updir := gitrepo.Dir(storage, "ada", "app")
76 fdir := gitrepo.Dir(storage, "dev", "app")
77 commit := func(dir, msg string) string {
78 t.Helper()
79 tree, _ := exec.Command("git", "-C", dir, "rev-parse", "master^{tree}").Output()
80 cmd := exec.Command("git", "-C", dir, "commit-tree", strings.TrimSpace(string(tree)), "-p", "master", "-m", msg)
81 cmd.Env = append(cmd.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@x", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@x")
82 out, err := cmd.Output()
83 if err != nil {
84 t.Fatal(err)
85 }
86 sha := strings.TrimSpace(string(out))
87 if out, err := exec.Command("git", "-C", dir, "update-ref", "refs/heads/master", sha).CombinedOutput(); err != nil {
88 t.Fatalf("%s", out)
89 }
90 return sha
91 }
92 up1 := commit(updir, "upstream 1")
93 code, body := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{}`)
94 if code != 200 || !strings.Contains(body, up1) {
95 t.Fatalf("sync: %d %s", code, body)
96 }
97 if code, body := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{"branch":"master"}`); code != 200 || !strings.Contains(body, `"up_to_date":true`) {
98 t.Fatalf("up to date: %d %s", code, body)
99 }
100 // ada (geen schrijfrechten op de fork) mag niet
101 if code, _ := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", adaTok, `{}`); code != 403 && code != 404 {
102 t.Fatalf("ada: %d", code)
103 }
104 // afgeweken: 409, niets overschreven
105 mine := commit(fdir, "eigen")
106 commit(updir, "upstream 2")
107 if code, body := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{}`); code != 409 {
108 t.Fatalf("diverged: %d %s", code, body)
109 }
110 if out, _ := exec.Command("git", "-C", fdir, "rev-parse", "master").Output(); strings.TrimSpace(string(out)) != mine {
111 t.Fatal("fork overschreven")
112 }
113 if code, _ := call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{"branch":"nope"}`); code != 404 {
114 t.Fatalf("onbekende branch: %d", code)
115 }
116 // upstream wordt privé: dev heeft geen toegang meer
117 if err := st.UpdateRepo(ctx, app.ID, "", "private"); err != nil {
118 t.Fatal(err)
119 }
120 code, body = call(http.MethodPost, "/api/v1/projects/dev/app/sync-upstream", devTok, `{}`)
121 if code != 403 || strings.Contains(body, "ada/app") {
122 t.Fatalf("privé upstream: %d %s", code, body)
123 }
124}
internal/server/forks.go +97 −0
@@ -2,6 +2,7 @@ package server
2 2
3 3 import (
4 4 "context"
5 "errors"
5 6 "net/http"
6 7 "os"
7 8 "strings"
@@ -206,3 +207,99 @@ func (s *Server) apiListForks(w http.ResponseWriter, r *http.Request) {
206 207 }
207 208 s.writeProjects(w, r, s.visibleForks(r.Context(), apiUser(r).ID, repo))
208 209 }
210
211 // SyncResult is de uitkomst van een upstream-synchronisatie.
212 type SyncResult struct {
213 Branch string `json:"branch"`
214 Before string `json:"before"`
215 After string `json:"after"`
216 UpToDate bool `json:"up_to_date"`
217 }
218
219 // opSyncUpstream zet branch (standaard de standaardbranch) van upstream
220 // fast-forward door naar de fork. Geen force: bij afwijking 409. Vereist
221 // schrijfrechten op de fork en leesrechten op upstream; zonder leesrechten
222 // noemt de fout de upstream niet.
223 func (s *Server) opSyncUpstream(ctx context.Context, user store.User, fork store.Repo, branch string) (SyncResult, error) {
224 role, err := s.Store.EffectiveRole(ctx, user.ID, fork.ID)
225 if err != nil || !role.CanWriteCode() {
226 return SyncResult{}, fail(403, i18n.E("err.forbidden"))
227 }
228 upID, _ := s.Store.ForkOf(ctx, fork.ID)
229 if upID == 0 {
230 return SyncResult{}, fail(400, i18n.E("err.notFork"))
231 }
232 up, err := s.Store.RepoByID(ctx, upID)
233 if err != nil || !s.canReadRepo(ctx, user.ID, up) {
234 return SyncResult{}, fail(403, i18n.E("err.upstreamNoAccess"))
235 }
236 branch = strings.TrimSpace(branch)
237 if branch == "" {
238 branch = fork.DefaultBranch
239 }
240 if !safeBranchName(branch) {
241 return SyncResult{}, fail(400, i18n.E("err.upstreamBranch", branch))
242 }
243 updir := gitrepo.Dir(s.StoragePath(), up.OwnerPath, up.Name)
244 dir := gitrepo.Dir(s.StoragePath(), fork.OwnerPath, fork.Name)
245 upSHA := gitOne(ctx, s.Git, updir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)
246 if !shaLike(upSHA) {
247 return SyncResult{}, fail(404, i18n.E("err.upstreamBranch", branch))
248 }
249 res := SyncResult{Branch: branch, Before: gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)}
250 if res.Before == upSHA {
251 res.After, res.UpToDate = upSHA, true
252 return res, nil
253 }
254 patterns, _ := s.Store.ProtectedPatterns(ctx, fork.ID)
255 env := append(os.Environ(), gitrepo.PushEnv(role, patterns, nil)...)
256 if err := s.postReceive(ctx, fork, user, dir, func() error {
257 return gitrepo.PushBranch(ctx, s.Git, updir, dir, branch, env)
258 }); err != nil {
259 if errors.Is(err, gitrepo.ErrNotFastForward) {
260 return res, fail(409, i18n.E("err.syncNotFF", branch))
261 }
262 return res, fail(400, err)
263 }
264 res.After = gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)
265 return res, nil
266 }
267
268 func safeBranchName(b string) bool {
269 return b != "" && !strings.HasPrefix(b, "-") && !strings.Contains(b, "..") && !strings.ContainsAny(b, " ~^:?*[\\")
270 }
271
272 func (s *Server) syncUpstreamPost(w http.ResponseWriter, r *http.Request) {
273 u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
274 if !ok || !s.csrfOK(w, r) {
275 return
276 }
277 res, err := s.opSyncUpstream(r.Context(), u, repo, r.FormValue("branch"))
278 if !s.uiOK(w, r, repoURL(repo), err) {
279 return
280 }
281 msg := "flash.synced"
282 if res.UpToDate {
283 msg = "flash.syncUpToDate"
284 }
285 s.redirect(w, r, repoURL(repo), s.tr(r, msg, res.Branch), "")
286 }
287
288 func (s *Server) apiSyncUpstream(w http.ResponseWriter, r *http.Request) {
289 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
290 if !ok {
291 return
292 }
293 var body struct {
294 Branch string `json:"branch"`
295 }
296 if err := readJSON(r, &body); err != nil {
297 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
298 return
299 }
300 res, err := s.opSyncUpstream(r.Context(), apiUser(r), repo, body.Branch)
301 if !s.apiOK(w, r, err) {
302 return
303 }
304 writeJSON(w, http.StatusOK, res)
305 }
@@ -2,6 +2,7 @@ package server
2
2
3import (
3import (
4 "context"
4 "context"
5 "errors"
5 "net/http"
6 "net/http"
6 "os"
7 "os"
7 "strings"
8 "strings"
@@ -206,3 +207,99 @@ func (s *Server) apiListForks(w http.ResponseWriter, r *http.Request) {
206 }
207 }
207 s.writeProjects(w, r, s.visibleForks(r.Context(), apiUser(r).ID, repo))
208 s.writeProjects(w, r, s.visibleForks(r.Context(), apiUser(r).ID, repo))
208}
209}
210
211// SyncResult is de uitkomst van een upstream-synchronisatie.
212type SyncResult struct {
213 Branch string `json:"branch"`
214 Before string `json:"before"`
215 After string `json:"after"`
216 UpToDate bool `json:"up_to_date"`
217}
218
219// opSyncUpstream zet branch (standaard de standaardbranch) van upstream
220// fast-forward door naar de fork. Geen force: bij afwijking 409. Vereist
221// schrijfrechten op de fork en leesrechten op upstream; zonder leesrechten
222// noemt de fout de upstream niet.
223func (s *Server) opSyncUpstream(ctx context.Context, user store.User, fork store.Repo, branch string) (SyncResult, error) {
224 role, err := s.Store.EffectiveRole(ctx, user.ID, fork.ID)
225 if err != nil || !role.CanWriteCode() {
226 return SyncResult{}, fail(403, i18n.E("err.forbidden"))
227 }
228 upID, _ := s.Store.ForkOf(ctx, fork.ID)
229 if upID == 0 {
230 return SyncResult{}, fail(400, i18n.E("err.notFork"))
231 }
232 up, err := s.Store.RepoByID(ctx, upID)
233 if err != nil || !s.canReadRepo(ctx, user.ID, up) {
234 return SyncResult{}, fail(403, i18n.E("err.upstreamNoAccess"))
235 }
236 branch = strings.TrimSpace(branch)
237 if branch == "" {
238 branch = fork.DefaultBranch
239 }
240 if !safeBranchName(branch) {
241 return SyncResult{}, fail(400, i18n.E("err.upstreamBranch", branch))
242 }
243 updir := gitrepo.Dir(s.StoragePath(), up.OwnerPath, up.Name)
244 dir := gitrepo.Dir(s.StoragePath(), fork.OwnerPath, fork.Name)
245 upSHA := gitOne(ctx, s.Git, updir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)
246 if !shaLike(upSHA) {
247 return SyncResult{}, fail(404, i18n.E("err.upstreamBranch", branch))
248 }
249 res := SyncResult{Branch: branch, Before: gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)}
250 if res.Before == upSHA {
251 res.After, res.UpToDate = upSHA, true
252 return res, nil
253 }
254 patterns, _ := s.Store.ProtectedPatterns(ctx, fork.ID)
255 env := append(os.Environ(), gitrepo.PushEnv(role, patterns, nil)...)
256 if err := s.postReceive(ctx, fork, user, dir, func() error {
257 return gitrepo.PushBranch(ctx, s.Git, updir, dir, branch, env)
258 }); err != nil {
259 if errors.Is(err, gitrepo.ErrNotFastForward) {
260 return res, fail(409, i18n.E("err.syncNotFF", branch))
261 }
262 return res, fail(400, err)
263 }
264 res.After = gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch)
265 return res, nil
266}
267
268func safeBranchName(b string) bool {
269 return b != "" && !strings.HasPrefix(b, "-") && !strings.Contains(b, "..") && !strings.ContainsAny(b, " ~^:?*[\\")
270}
271
272func (s *Server) syncUpstreamPost(w http.ResponseWriter, r *http.Request) {
273 u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
274 if !ok || !s.csrfOK(w, r) {
275 return
276 }
277 res, err := s.opSyncUpstream(r.Context(), u, repo, r.FormValue("branch"))
278 if !s.uiOK(w, r, repoURL(repo), err) {
279 return
280 }
281 msg := "flash.synced"
282 if res.UpToDate {
283 msg = "flash.syncUpToDate"
284 }
285 s.redirect(w, r, repoURL(repo), s.tr(r, msg, res.Branch), "")
286}
287
288func (s *Server) apiSyncUpstream(w http.ResponseWriter, r *http.Request) {
289 repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
290 if !ok {
291 return
292 }
293 var body struct {
294 Branch string `json:"branch"`
295 }
296 if err := readJSON(r, &body); err != nil {
297 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
298 return
299 }
300 res, err := s.opSyncUpstream(r.Context(), apiUser(r), repo, body.Branch)
301 if !s.apiOK(w, r, err) {
302 return
303 }
304 writeJSON(w, http.StatusOK, res)
305}
internal/server/server.go +1 −0
@@ -239,6 +239,7 @@ func (s *Server) Handler() http.Handler {
239 239 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
240 240 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
241 241 mux.HandleFunc("POST /{owner}/{repo}/-/fork", s.forkPost)
242 mux.HandleFunc("POST /{owner}/{repo}/-/sync-upstream", s.syncUpstreamPost)
242 243 mux.HandleFunc("GET /{owner}/{repo}/-/forks", s.forksPage)
243 244 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
244 245 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
@@ -239,6 +239,7 @@ func (s *Server) Handler() http.Handler {
239 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
239 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
240 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
240 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
241 mux.HandleFunc("POST /{owner}/{repo}/-/fork", s.forkPost)
241 mux.HandleFunc("POST /{owner}/{repo}/-/fork", s.forkPost)
242 mux.HandleFunc("POST /{owner}/{repo}/-/sync-upstream", s.syncUpstreamPost)
242 mux.HandleFunc("GET /{owner}/{repo}/-/forks", s.forksPage)
243 mux.HandleFunc("GET /{owner}/{repo}/-/forks", s.forksPage)
243 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
244 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
244 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
245 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
internal/server/templates/pages.html +8 −1
@@ -549,7 +549,14 @@
549 549 <aside class="side">
550 550 <h2>{{t "repo.project"}}</h2>
551 551 {{if .Repo.Description}}<p>{{.Repo.Description}}</p>{{end}}
552 {{if .Fork.IsFork}}<p class="muted" data-tip="{{t "fork.ofTip"}}">{{if .Fork.Upstream}}{{t "fork.of"}} <a href="/{{.Fork.Upstream.FullPath}}">{{.Fork.Upstream.FullPath}}</a>{{else}}{{t "fork.hidden"}}{{end}}</p>{{end}}
552 {{if .Fork.IsFork}}<p class="muted" data-tip="{{t "fork.ofTip"}}">{{if .Fork.Upstream}}{{t "fork.of"}} <a href="/{{.Fork.Upstream.FullPath}}">{{.Fork.Upstream.FullPath}}</a>{{else}}{{t "fork.hidden"}}{{end}}</p>
553 {{if and .Fork.Upstream .CanWrite}}
554 <form method="post" action="/{{.Repo.FullPath}}/-/sync-upstream" class="tiphost">
555 <input type="hidden" name="csrf" value="{{.CSRF}}">
556 <input type="hidden" name="branch" value="{{.Rev}}">
557 <button type="submit" class="ghost tiny">{{t "fork.sync" .Rev}}</button> {{tip "fork.syncTip"}}
558 </form>
559 {{end}}{{end}}
553 560 <ul class="counts">
554 561 <li><a href="/{{.Repo.FullPath}}/-/commits?rev={{.Rev}}">{{tn .NCommits "count.commit.one" "count.commit.many"}}</a></li>
555 562 <li><a href="/{{.Repo.FullPath}}/-/branches">{{tn .NBranches "count.branch.one" "count.branch.many"}}</a></li>
@@ -549,7 +549,14 @@
549 <aside class="side">
549 <aside class="side">
550 <h2>{{t "repo.project"}}</h2>
550 <h2>{{t "repo.project"}}</h2>
551 {{if .Repo.Description}}<p>{{.Repo.Description}}</p>{{end}}
551 {{if .Repo.Description}}<p>{{.Repo.Description}}</p>{{end}}
552 {{if .Fork.IsFork}}<p class="muted" data-tip="{{t "fork.ofTip"}}">{{if .Fork.Upstream}}{{t "fork.of"}} <a href="/{{.Fork.Upstream.FullPath}}">{{.Fork.Upstream.FullPath}}</a>{{else}}{{t "fork.hidden"}}{{end}}</p>{{end}}
552 {{if .Fork.IsFork}}<p class="muted" data-tip="{{t "fork.ofTip"}}">{{if .Fork.Upstream}}{{t "fork.of"}} <a href="/{{.Fork.Upstream.FullPath}}">{{.Fork.Upstream.FullPath}}</a>{{else}}{{t "fork.hidden"}}{{end}}</p>
553 {{if and .Fork.Upstream .CanWrite}}
554 <form method="post" action="/{{.Repo.FullPath}}/-/sync-upstream" class="tiphost">
555 <input type="hidden" name="csrf" value="{{.CSRF}}">
556 <input type="hidden" name="branch" value="{{.Rev}}">
557 <button type="submit" class="ghost tiny">{{t "fork.sync" .Rev}}</button> {{tip "fork.syncTip"}}
558 </form>
559 {{end}}{{end}}
553 <ul class="counts">
560 <ul class="counts">
554 <li><a href="/{{.Repo.FullPath}}/-/commits?rev={{.Rev}}">{{tn .NCommits "count.commit.one" "count.commit.many"}}</a></li>
561 <li><a href="/{{.Repo.FullPath}}/-/commits?rev={{.Rev}}">{{tn .NCommits "count.commit.one" "count.commit.many"}}</a></li>
555 <li><a href="/{{.Repo.FullPath}}/-/branches">{{tn .NBranches "count.branch.one" "count.branch.many"}}</a></li>
562 <li><a href="/{{.Repo.FullPath}}/-/branches">{{tn .NBranches "count.branch.one" "count.branch.many"}}</a></li>