BlueGit

timfa bluegit

Merged

Forks stap 1: fork maken

!105 · merged 3 weeks ago

timfa wants to merge 1 commit from cursor/fork-create into stage

Pipeline

#457 Passed
Stage: build

Reviews

  • No reviews yet.

Merged by timfa on 27 October 2026 1421f7e2

Overview Commits 1 Pipelines 2 Changes 14

Changes

14 files changed +561 −0
internal/gitrepo/repo.go +23 −0
@@ -827,3 +827,26 @@ func run(ctx context.Context, bin string, env []string, args ...string) (string,
827 827 }
828 828 return stdout.String(), nil
829 829 }
830
831 // Fork maakt dir als bare kloon van src met alle branches en tags. Objecten
832 // worden lokaal gehardlinkt (geen extra schijfruimte voor bestaande objecten).
833 // Daarna dezelfde instellingen en hook als Init; de remote naar src gaat weg.
834 func Fork(gitBin, src, dir, hookBinary string) error {
835 if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
836 return err
837 }
838 if _, err := run(context.Background(), gitBin, nil, "clone", "--bare", "--quiet", src, dir); err != nil {
839 return err
840 }
841 _, _ = run(context.Background(), gitBin, nil, "-C", dir, "remote", "remove", "origin")
842 for _, kv := range [][2]string{
843 {"http.receivepack", "true"},
844 {"http.uploadpack", "true"},
845 {"receive.denyCurrentBranch", "ignore"},
846 } {
847 if _, err := run(context.Background(), gitBin, nil, "-C", dir, "config", kv[0], kv[1]); err != nil {
848 return err
849 }
850 }
851 return InstallHook(dir, hookBinary)
852 }
@@ -827,3 +827,26 @@ func run(ctx context.Context, bin string, env []string, args ...string) (string,
827 }
827 }
828 return stdout.String(), nil
828 return stdout.String(), nil
829}
829}
830
831// Fork maakt dir als bare kloon van src met alle branches en tags. Objecten
832// worden lokaal gehardlinkt (geen extra schijfruimte voor bestaande objecten).
833// Daarna dezelfde instellingen en hook als Init; de remote naar src gaat weg.
834func Fork(gitBin, src, dir, hookBinary string) error {
835 if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
836 return err
837 }
838 if _, err := run(context.Background(), gitBin, nil, "clone", "--bare", "--quiet", src, dir); err != nil {
839 return err
840 }
841 _, _ = run(context.Background(), gitBin, nil, "-C", dir, "remote", "remove", "origin")
842 for _, kv := range [][2]string{
843 {"http.receivepack", "true"},
844 {"http.uploadpack", "true"},
845 {"receive.denyCurrentBranch", "ignore"},
846 } {
847 if _, err := run(context.Background(), gitBin, nil, "-C", dir, "config", kv[0], kv[1]); err != nil {
848 return err
849 }
850 }
851 return InstallHook(dir, hookBinary)
852}
internal/i18n/catalog_fork.go added +84 −0
@@ -0,0 +1,84 @@
1 package i18n
2
3 func init() {
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",
23 })
24 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",
43 })
44 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",
63 })
64 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",
83 })
84 }
@@ -0,0 +1,84 @@
1package i18n
2
3func init() {
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",
23 })
24 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",
43 })
44 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",
63 })
64 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",
83 })
84}
internal/server/api_openapi.go +11 −0
@@ -136,6 +136,8 @@ func apiBinds() []apiBind {
136 136 {path: "/projects/{owner}/{repo}/secrets", method: "POST", code: "200", body: "SecretWrite", resp: "SecretName"},
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 {path: "/projects/{owner}/{repo}/fork", method: "POST", code: "201", body: "ForkCreate", resp: "ForkedProject"},
140 {path: "/projects/{owner}/{repo}/forks", method: "GET", code: "200", resp: "ForkedProject", array: true},
139 141 {path: "/projects/{owner}/{repo}/secrets/inherited", method: "GET", code: "200", resp: "InheritedSecret", array: true},
140 142 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
141 143 {path: "/groups/{path}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
@@ -404,6 +406,15 @@ func apiSchemas() map[string]any {
404 406 "expand": boolean("Expand $NAME references in the value at job time. Default false; omitted on update keeps the stored setting."),
405 407 }),
406 408 "SecretName": obj("The stored secret name.", map[string]any{"name": str("Secret name.")}),
409 "ForkedProject": obj("A project (same fields as GET /projects/{owner}/{repo}). The fork response adds forked_from.", map[string]any{
410 "path_with_namespace": str("owner/name."),
411 "visibility": str("public or private."),
412 "forked_from": str("Upstream owner/name (only in the fork response)."),
413 }),
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{
415 "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."),
417 }),
407 418 "InheritedSecret": obj("A group secret the project inherits. Values are never returned. Jobs get group secrets first; a project secret with the same name wins.", map[string]any{
408 419 "name": str("Secret name."),
409 420 "group": str("Path of the group it comes from."),
@@ -136,6 +136,8 @@ func apiBinds() []apiBind {
136 {path: "/projects/{owner}/{repo}/secrets", method: "POST", code: "200", body: "SecretWrite", resp: "SecretName"},
136 {path: "/projects/{owner}/{repo}/secrets", method: "POST", code: "200", body: "SecretWrite", resp: "SecretName"},
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"},
140 {path: "/projects/{owner}/{repo}/forks", method: "GET", code: "200", resp: "ForkedProject", array: true},
139 {path: "/projects/{owner}/{repo}/secrets/inherited", method: "GET", code: "200", resp: "InheritedSecret", array: true},
141 {path: "/projects/{owner}/{repo}/secrets/inherited", method: "GET", code: "200", resp: "InheritedSecret", array: true},
140 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
142 {path: "/groups/{path}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
141 {path: "/groups/{path}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
143 {path: "/groups/{path}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
@@ -404,6 +406,15 @@ func apiSchemas() map[string]any {
404 "expand": boolean("Expand $NAME references in the value at job time. Default false; omitted on update keeps the stored setting."),
406 "expand": boolean("Expand $NAME references in the value at job time. Default false; omitted on update keeps the stored setting."),
405 }),
407 }),
406 "SecretName": obj("The stored secret name.", map[string]any{"name": str("Secret name.")}),
408 "SecretName": obj("The stored secret name.", map[string]any{"name": str("Secret name.")}),
409 "ForkedProject": obj("A project (same fields as GET /projects/{owner}/{repo}). The fork response adds forked_from.", map[string]any{
410 "path_with_namespace": str("owner/name."),
411 "visibility": str("public or private."),
412 "forked_from": str("Upstream owner/name (only in the fork response)."),
413 }),
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{
415 "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."),
417 }),
407 "InheritedSecret": obj("A group secret the project inherits. Values are never returned. Jobs get group secrets first; a project secret with the same name wins.", map[string]any{
418 "InheritedSecret": obj("A group secret the project inherits. Values are never returned. Jobs get group secrets first; a project secret with the same name wins.", map[string]any{
408 "name": str("Secret name."),
419 "name": str("Secret name."),
409 "group": str("Path of the group it comes from."),
420 "group": str("Path of the group it comes from."),
internal/server/api_routes.go +2 −0
@@ -87,6 +87,8 @@ var apiCatalog = []apiRoute{
87 87 {http.MethodPost, "/api/v1/projects", access.ScopeWrite, authUser, "Create project", (*Server).apiCreateProject},
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 {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.MethodGet, "/api/v1/projects/{owner}/{repo}/forks", access.ScopeRead, authUser, "List forks of a project you can see.", (*Server).apiListForks},
90 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},
91 93 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/star", access.ScopeWrite, authUser, "Toggle star", (*Server).apiStar},
92 94 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/logo", access.ScopeRepoRead, authOptional, "Project logo", (*Server).apiProjectLogo},
@@ -87,6 +87,8 @@ var apiCatalog = []apiRoute{
87 {http.MethodPost, "/api/v1/projects", access.ScopeWrite, authUser, "Create project", (*Server).apiCreateProject},
87 {http.MethodPost, "/api/v1/projects", access.ScopeWrite, authUser, "Create project", (*Server).apiCreateProject},
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},
91 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/forks", access.ScopeRead, authUser, "List forks of a project you can see.", (*Server).apiListForks},
90 {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},
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},
91 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/star", access.ScopeWrite, authUser, "Toggle star", (*Server).apiStar},
93 {http.MethodPost, "/api/v1/projects/{owner}/{repo}/star", access.ScopeWrite, authUser, "Toggle star", (*Server).apiStar},
92 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/logo", access.ScopeRepoRead, authOptional, "Project logo", (*Server).apiProjectLogo},
94 {http.MethodGet, "/api/v1/projects/{owner}/{repo}/logo", access.ScopeRepoRead, authOptional, "Project logo", (*Server).apiProjectLogo},
internal/server/fork_test.go added +133 −0
@@ -0,0 +1,133 @@
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 TestForkRepo(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":"private","initialize_with_readme":true}`); code != 201 {
69 t.Fatalf("project %d %s", code, body)
70 }
71 app, _ := st.RepoByPath(ctx, "ada", "app")
72 updir := gitrepo.Dir(storage, "ada", "app")
73 for _, args := range [][]string{{"branch", "feature", "master"}, {"tag", "v1", "master"}} {
74 if out, err := exec.Command("git", append([]string{"-C", updir}, args...)...).CombinedOutput(); err != nil {
75 t.Fatalf("%v %s", err, out)
76 }
77 }
78 // geen toegang tot privé upstream: 404
79 if code, _ := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{}`); code != 404 {
80 t.Fatalf("dev zonder toegang: %d", code)
81 }
82 _ = st.SetMember(ctx, "repo", app.ID, "dev", "readonly")
83 code, body := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{"name":"mijn-app"}`)
84 if code != 201 || !strings.Contains(body, `"forked_from":"ada/app"`) {
85 t.Fatalf("fork: %d %s", code, body)
86 }
87 if code, _ := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{"name":"mijn-app"}`); code != 409 {
88 t.Fatalf("dubbele naam: %d", code)
89 }
90 fork, err := st.RepoByPath(ctx, "dev", "mijn-app")
91 if err != nil || fork.Visibility != "private" {
92 t.Fatalf("fork: %+v %v", fork, err)
93 }
94 fdir := gitrepo.Dir(storage, "dev", "mijn-app")
95 out, _ := exec.Command("git", "-C", fdir, "for-each-ref", "--format=%(refname)").CombinedOutput()
96 for _, ref := range []string{"refs/heads/master", "refs/heads/feature", "refs/tags/v1"} {
97 if !strings.Contains(string(out), ref) {
98 t.Fatalf("%s ontbreekt: %s", ref, out)
99 }
100 }
101 if out, _ := exec.Command("git", "-C", fdir, "remote").CombinedOutput(); strings.TrimSpace(string(out)) != "" {
102 t.Fatalf("remote blijft: %s", out)
103 }
104 // privé upstream: fork mag niet openbaar
105 if code, _ := call(http.MethodPut, "/api/v1/projects/dev/mijn-app", devTok, `{"visibility":"public"}`); code == 200 {
106 t.Fatal("fork van privé werd openbaar")
107 }
108 if code, body := call(http.MethodGet, "/api/v1/projects/ada/app/forks", adaTok, ""); code != 200 || strings.Contains(body, "mijn-app") {
109 // ada ziet de privé fork van dev niet
110 t.Fatalf("forks voor ada: %d %s", code, body)
111 }
112 if code, body := call(http.MethodGet, "/api/v1/projects/ada/app/forks", devTok, ""); code != 200 || !strings.Contains(body, "mijn-app") {
113 t.Fatalf("forks voor dev: %d %s", code, body)
114 }
115 // upstream-info verborgen zonder toegang
116 if fi := srv.forkInfo(ctx, ada.ID, fork); !fi.IsFork || fi.Upstream == nil {
117 t.Fatal("ada ziet upstream")
118 }
119 _ = st.RemoveMember(ctx, "repo", app.ID, "dev")
120 if fi := srv.forkInfo(ctx, dev.ID, fork); !fi.IsFork || fi.Upstream != nil {
121 t.Fatal("upstream lekt na intrekken")
122 }
123 // upstream weg: fork blijft, relatie los
124 if code, _ := call(http.MethodDelete, "/api/v1/projects/ada/app", adaTok, `{"confirm":"app"}`); code != 204 {
125 t.Fatalf("upstream weg: %d", code)
126 }
127 if up, _ := st.ForkOf(ctx, fork.ID); up != 0 {
128 t.Fatal("relatie niet los")
129 }
130 if _, err := st.RepoByPath(ctx, "dev", "mijn-app"); err != nil {
131 t.Fatal("fork weg")
132 }
133 }
@@ -0,0 +1,133 @@
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 TestForkRepo(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":"private","initialize_with_readme":true}`); code != 201 {
69 t.Fatalf("project %d %s", code, body)
70 }
71 app, _ := st.RepoByPath(ctx, "ada", "app")
72 updir := gitrepo.Dir(storage, "ada", "app")
73 for _, args := range [][]string{{"branch", "feature", "master"}, {"tag", "v1", "master"}} {
74 if out, err := exec.Command("git", append([]string{"-C", updir}, args...)...).CombinedOutput(); err != nil {
75 t.Fatalf("%v %s", err, out)
76 }
77 }
78 // geen toegang tot privé upstream: 404
79 if code, _ := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{}`); code != 404 {
80 t.Fatalf("dev zonder toegang: %d", code)
81 }
82 _ = st.SetMember(ctx, "repo", app.ID, "dev", "readonly")
83 code, body := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{"name":"mijn-app"}`)
84 if code != 201 || !strings.Contains(body, `"forked_from":"ada/app"`) {
85 t.Fatalf("fork: %d %s", code, body)
86 }
87 if code, _ := call(http.MethodPost, "/api/v1/projects/ada/app/fork", devTok, `{"name":"mijn-app"}`); code != 409 {
88 t.Fatalf("dubbele naam: %d", code)
89 }
90 fork, err := st.RepoByPath(ctx, "dev", "mijn-app")
91 if err != nil || fork.Visibility != "private" {
92 t.Fatalf("fork: %+v %v", fork, err)
93 }
94 fdir := gitrepo.Dir(storage, "dev", "mijn-app")
95 out, _ := exec.Command("git", "-C", fdir, "for-each-ref", "--format=%(refname)").CombinedOutput()
96 for _, ref := range []string{"refs/heads/master", "refs/heads/feature", "refs/tags/v1"} {
97 if !strings.Contains(string(out), ref) {
98 t.Fatalf("%s ontbreekt: %s", ref, out)
99 }
100 }
101 if out, _ := exec.Command("git", "-C", fdir, "remote").CombinedOutput(); strings.TrimSpace(string(out)) != "" {
102 t.Fatalf("remote blijft: %s", out)
103 }
104 // privé upstream: fork mag niet openbaar
105 if code, _ := call(http.MethodPut, "/api/v1/projects/dev/mijn-app", devTok, `{"visibility":"public"}`); code == 200 {
106 t.Fatal("fork van privé werd openbaar")
107 }
108 if code, body := call(http.MethodGet, "/api/v1/projects/ada/app/forks", adaTok, ""); code != 200 || strings.Contains(body, "mijn-app") {
109 // ada ziet de privé fork van dev niet
110 t.Fatalf("forks voor ada: %d %s", code, body)
111 }
112 if code, body := call(http.MethodGet, "/api/v1/projects/ada/app/forks", devTok, ""); code != 200 || !strings.Contains(body, "mijn-app") {
113 t.Fatalf("forks voor dev: %d %s", code, body)
114 }
115 // upstream-info verborgen zonder toegang
116 if fi := srv.forkInfo(ctx, ada.ID, fork); !fi.IsFork || fi.Upstream == nil {
117 t.Fatal("ada ziet upstream")
118 }
119 _ = st.RemoveMember(ctx, "repo", app.ID, "dev")
120 if fi := srv.forkInfo(ctx, dev.ID, fork); !fi.IsFork || fi.Upstream != nil {
121 t.Fatal("upstream lekt na intrekken")
122 }
123 // upstream weg: fork blijft, relatie los
124 if code, _ := call(http.MethodDelete, "/api/v1/projects/ada/app", adaTok, `{"confirm":"app"}`); code != 204 {
125 t.Fatalf("upstream weg: %d", code)
126 }
127 if up, _ := st.ForkOf(ctx, fork.ID); up != 0 {
128 t.Fatal("relatie niet los")
129 }
130 if _, err := st.RepoByPath(ctx, "dev", "mijn-app"); err != nil {
131 t.Fatal("fork weg")
132 }
133}
internal/server/forks.go added +208 −0
@@ -0,0 +1,208 @@
1 package server
2
3 import (
4 "context"
5 "net/http"
6 "os"
7 "strings"
8 "syscall"
9
10 "gitlab.com/Timfa/bluegit/internal/access"
11 "gitlab.com/Timfa/bluegit/internal/gitrepo"
12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 "gitlab.com/Timfa/bluegit/internal/state"
14 "gitlab.com/Timfa/bluegit/internal/store"
15 )
16
17 // forkReserveBytes: zoveel moet er naast de upstream-grootte vrij blijven.
18 const forkReserveBytes = 512 << 20
19
20 // canReadRepo: openbaar, of de gebruiker heeft minstens leesrechten.
21 func (s *Server) canReadRepo(ctx context.Context, userID int64, repo store.Repo) bool {
22 if repo.Visibility == "public" {
23 return true
24 }
25 if userID == 0 {
26 return false
27 }
28 role, err := s.Store.EffectiveRole(ctx, userID, repo.ID)
29 return err == nil && role.CanRead()
30 }
31
32 // ForkInfo is wat de repo-pagina over de fork-relatie toont.
33 type ForkInfo struct {
34 IsFork bool
35 Upstream *store.Repo // nil als de kijker upstream niet mag zien
36 Forks int // zichtbare forks van deze repo
37 }
38
39 func (s *Server) forkInfo(ctx context.Context, userID int64, repo store.Repo) ForkInfo {
40 var fi ForkInfo
41 if up, _ := s.Store.ForkOf(ctx, repo.ID); up != 0 {
42 fi.IsFork = true
43 if u, err := s.Store.RepoByID(ctx, up); err == nil && s.canReadRepo(ctx, userID, u) {
44 fi.Upstream = &u
45 }
46 }
47 fi.Forks = len(s.visibleForks(ctx, userID, repo))
48 return fi
49 }
50
51 func (s *Server) visibleForks(ctx context.Context, userID int64, repo store.Repo) []store.Repo {
52 ids, _ := s.Store.ForkIDs(ctx, repo.ID)
53 if len(ids) == 0 {
54 return nil
55 }
56 list, _ := s.Store.ReposByIDs(ctx, ids)
57 var out []store.Repo
58 for _, f := range list {
59 if s.canReadRepo(ctx, userID, f) {
60 out = append(out, f)
61 }
62 }
63 return out
64 }
65
66 // ForkTarget is een plek waar de gebruiker een fork mag maken.
67 type ForkTarget struct {
68 Value string // "" = eigen account, anders groepspad
69 Label string
70 }
71
72 func (s *Server) forkTargets(ctx context.Context, user store.User) []ForkTarget {
73 out := []ForkTarget{{Value: "", Label: user.Username}}
74 groups, _ := s.Store.ListGroups(ctx, user.ID)
75 for _, g := range groups {
76 if role, err := s.Store.GroupRole(ctx, g.ID, user.ID); err == nil && role.CanWriteCode() {
77 out = append(out, ForkTarget{Value: g.Path, Label: g.Path})
78 }
79 }
80 return out
81 }
82
83 // opForkRepo maakt een fork met alle branches en tags. Doel: eigen account
84 // of een groep waar de gebruiker minstens developer is. Een fork van een
85 // privé repo is privé.
86 func (s *Server) opForkRepo(ctx context.Context, user store.User, upstream store.Repo, groupPath, rawName string) (store.Repo, error) {
87 if s.StoragePath() == "" {
88 return store.Repo{}, fail(503, i18n.E("err.noStorage"))
89 }
90 if !s.canReadRepo(ctx, user.ID, upstream) {
91 return store.Repo{}, fail(404, i18n.E("err.notFound"))
92 }
93 if strings.TrimSpace(rawName) == "" {
94 rawName = upstream.Name
95 }
96 name, err := slugKind("repo", rawName)
97 if err != nil {
98 return store.Repo{}, fail(400, err)
99 }
100 ownerKind, ownerID, ownerPath := "user", user.ID, user.Username
101 if gp := strings.TrimSpace(groupPath); gp != "" {
102 g, err := s.Store.GroupByPath(ctx, gp)
103 if err != nil {
104 return store.Repo{}, fail(404, i18n.E("err.groupMissing"))
105 }
106 role, err := s.Store.GroupRole(ctx, g.ID, user.ID)
107 if err != nil || !role.AtLeast(access.RoleDeveloper) {
108 return store.Repo{}, fail(403, i18n.E("err.forbidden"))
109 }
110 ownerKind, ownerID, ownerPath = "group", g.ID, g.Path
111 }
112 if _, err := s.Store.RepoByPath(ctx, ownerPath, name); err == nil {
113 return store.Repo{}, fail(409, i18n.E("err.forkExists", ownerPath+"/"+name))
114 }
115 src := gitrepo.Dir(s.StoragePath(), upstream.OwnerPath, upstream.Name)
116 if size, err := state.DirSize(ctx, src); err == nil {
117 var st syscall.Statfs_t
118 if syscall.Statfs(s.StoragePath(), &st) == nil && st.Bavail*uint64(st.Bsize) < size+forkReserveBytes {
119 return store.Repo{}, fail(507, i18n.E("err.forkDisk"))
120 }
121 }
122 repo, err := s.Store.CreateRepo(ctx, ownerKind, ownerID, name, upstream.Description, upstream.DefaultBranch, upstream.Visibility)
123 if err != nil {
124 return store.Repo{}, fail(400, err)
125 }
126 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
127 if err := gitrepo.Fork(s.Git, src, dir, s.HookBin); err != nil {
128 _ = s.Store.DeleteRepo(ctx, repo.ID)
129 _ = os.RemoveAll(dir)
130 return store.Repo{}, fail(500, i18n.E("err.forkGit", err.Error()))
131 }
132 if err := s.Store.SetForkOf(ctx, repo.ID, upstream.ID); err != nil {
133 return store.Repo{}, fail(500, err)
134 }
135 s.syncRepos(ctx, []int64{repo.ID})
136 return repo, nil
137 }
138
139 // forkMustStayPrivate: een fork van een privé upstream mag niet openbaar.
140 func (s *Server) forkMustStayPrivate(ctx context.Context, repo store.Repo) bool {
141 up, _ := s.Store.ForkOf(ctx, repo.ID)
142 if up == 0 {
143 return false
144 }
145 u, err := s.Store.RepoByID(ctx, up)
146 return err == nil && u.Visibility != "public"
147 }
148
149 func (s *Server) forkPost(w http.ResponseWriter, r *http.Request) {
150 u, repo, _, ok := s.guard(w, r, access.RoleReadonly)
151 if !ok || !s.csrfOK(w, r) {
152 return
153 }
154 if u.ID == 0 {
155 http.Redirect(w, r, "/login", http.StatusSeeOther)
156 return
157 }
158 fork, err := s.opForkRepo(r.Context(), u, repo, r.FormValue("namespace"), r.FormValue("name"))
159 if !s.uiOK(w, r, repoURL(repo), err) {
160 return
161 }
162 s.redirect(w, r, repoURL(fork), s.tr(r, "flash.forked"), "")
163 }
164
165 func (s *Server) forksPage(w http.ResponseWriter, r *http.Request) {
166 u, repo, role, ok := s.guard(w, r, access.RoleReadonly)
167 if !ok {
168 return
169 }
170 v := s.repoView(w, r, repo, role, s.tr(r, "fork.listTitle"))
171 v.ForkList = s.visibleForks(r.Context(), u.ID, repo)
172 v.Fork = s.forkInfo(r.Context(), u.ID, repo)
173 s.render(w, "forks", v)
174 }
175
176 func forkJSON(fork store.Repo, upstream store.Repo) map[string]any {
177 out := projectJSON(fork)
178 out["forked_from"] = upstream.FullPath()
179 return out
180 }
181
182 func (s *Server) apiForkProject(w http.ResponseWriter, r *http.Request) {
183 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
184 if !ok {
185 return
186 }
187 var body struct {
188 Namespace string `json:"namespace"`
189 Name string `json:"name"`
190 }
191 if err := readJSON(r, &body); err != nil {
192 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
193 return
194 }
195 fork, err := s.opForkRepo(r.Context(), apiUser(r), repo, body.Namespace, body.Name)
196 if !s.apiOK(w, r, err) {
197 return
198 }
199 writeJSON(w, http.StatusCreated, forkJSON(fork, repo))
200 }
201
202 func (s *Server) apiListForks(w http.ResponseWriter, r *http.Request) {
203 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
204 if !ok {
205 return
206 }
207 s.writeProjects(w, r, s.visibleForks(r.Context(), apiUser(r).ID, repo))
208 }
@@ -0,0 +1,208 @@
1package server
2
3import (
4 "context"
5 "net/http"
6 "os"
7 "strings"
8 "syscall"
9
10 "gitlab.com/Timfa/bluegit/internal/access"
11 "gitlab.com/Timfa/bluegit/internal/gitrepo"
12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 "gitlab.com/Timfa/bluegit/internal/state"
14 "gitlab.com/Timfa/bluegit/internal/store"
15)
16
17// forkReserveBytes: zoveel moet er naast de upstream-grootte vrij blijven.
18const forkReserveBytes = 512 << 20
19
20// canReadRepo: openbaar, of de gebruiker heeft minstens leesrechten.
21func (s *Server) canReadRepo(ctx context.Context, userID int64, repo store.Repo) bool {
22 if repo.Visibility == "public" {
23 return true
24 }
25 if userID == 0 {
26 return false
27 }
28 role, err := s.Store.EffectiveRole(ctx, userID, repo.ID)
29 return err == nil && role.CanRead()
30}
31
32// ForkInfo is wat de repo-pagina over de fork-relatie toont.
33type ForkInfo struct {
34 IsFork bool
35 Upstream *store.Repo // nil als de kijker upstream niet mag zien
36 Forks int // zichtbare forks van deze repo
37}
38
39func (s *Server) forkInfo(ctx context.Context, userID int64, repo store.Repo) ForkInfo {
40 var fi ForkInfo
41 if up, _ := s.Store.ForkOf(ctx, repo.ID); up != 0 {
42 fi.IsFork = true
43 if u, err := s.Store.RepoByID(ctx, up); err == nil && s.canReadRepo(ctx, userID, u) {
44 fi.Upstream = &u
45 }
46 }
47 fi.Forks = len(s.visibleForks(ctx, userID, repo))
48 return fi
49}
50
51func (s *Server) visibleForks(ctx context.Context, userID int64, repo store.Repo) []store.Repo {
52 ids, _ := s.Store.ForkIDs(ctx, repo.ID)
53 if len(ids) == 0 {
54 return nil
55 }
56 list, _ := s.Store.ReposByIDs(ctx, ids)
57 var out []store.Repo
58 for _, f := range list {
59 if s.canReadRepo(ctx, userID, f) {
60 out = append(out, f)
61 }
62 }
63 return out
64}
65
66// ForkTarget is een plek waar de gebruiker een fork mag maken.
67type ForkTarget struct {
68 Value string // "" = eigen account, anders groepspad
69 Label string
70}
71
72func (s *Server) forkTargets(ctx context.Context, user store.User) []ForkTarget {
73 out := []ForkTarget{{Value: "", Label: user.Username}}
74 groups, _ := s.Store.ListGroups(ctx, user.ID)
75 for _, g := range groups {
76 if role, err := s.Store.GroupRole(ctx, g.ID, user.ID); err == nil && role.CanWriteCode() {
77 out = append(out, ForkTarget{Value: g.Path, Label: g.Path})
78 }
79 }
80 return out
81}
82
83// opForkRepo maakt een fork met alle branches en tags. Doel: eigen account
84// of een groep waar de gebruiker minstens developer is. Een fork van een
85// privé repo is privé.
86func (s *Server) opForkRepo(ctx context.Context, user store.User, upstream store.Repo, groupPath, rawName string) (store.Repo, error) {
87 if s.StoragePath() == "" {
88 return store.Repo{}, fail(503, i18n.E("err.noStorage"))
89 }
90 if !s.canReadRepo(ctx, user.ID, upstream) {
91 return store.Repo{}, fail(404, i18n.E("err.notFound"))
92 }
93 if strings.TrimSpace(rawName) == "" {
94 rawName = upstream.Name
95 }
96 name, err := slugKind("repo", rawName)
97 if err != nil {
98 return store.Repo{}, fail(400, err)
99 }
100 ownerKind, ownerID, ownerPath := "user", user.ID, user.Username
101 if gp := strings.TrimSpace(groupPath); gp != "" {
102 g, err := s.Store.GroupByPath(ctx, gp)
103 if err != nil {
104 return store.Repo{}, fail(404, i18n.E("err.groupMissing"))
105 }
106 role, err := s.Store.GroupRole(ctx, g.ID, user.ID)
107 if err != nil || !role.AtLeast(access.RoleDeveloper) {
108 return store.Repo{}, fail(403, i18n.E("err.forbidden"))
109 }
110 ownerKind, ownerID, ownerPath = "group", g.ID, g.Path
111 }
112 if _, err := s.Store.RepoByPath(ctx, ownerPath, name); err == nil {
113 return store.Repo{}, fail(409, i18n.E("err.forkExists", ownerPath+"/"+name))
114 }
115 src := gitrepo.Dir(s.StoragePath(), upstream.OwnerPath, upstream.Name)
116 if size, err := state.DirSize(ctx, src); err == nil {
117 var st syscall.Statfs_t
118 if syscall.Statfs(s.StoragePath(), &st) == nil && st.Bavail*uint64(st.Bsize) < size+forkReserveBytes {
119 return store.Repo{}, fail(507, i18n.E("err.forkDisk"))
120 }
121 }
122 repo, err := s.Store.CreateRepo(ctx, ownerKind, ownerID, name, upstream.Description, upstream.DefaultBranch, upstream.Visibility)
123 if err != nil {
124 return store.Repo{}, fail(400, err)
125 }
126 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
127 if err := gitrepo.Fork(s.Git, src, dir, s.HookBin); err != nil {
128 _ = s.Store.DeleteRepo(ctx, repo.ID)
129 _ = os.RemoveAll(dir)
130 return store.Repo{}, fail(500, i18n.E("err.forkGit", err.Error()))
131 }
132 if err := s.Store.SetForkOf(ctx, repo.ID, upstream.ID); err != nil {
133 return store.Repo{}, fail(500, err)
134 }
135 s.syncRepos(ctx, []int64{repo.ID})
136 return repo, nil
137}
138
139// forkMustStayPrivate: een fork van een privé upstream mag niet openbaar.
140func (s *Server) forkMustStayPrivate(ctx context.Context, repo store.Repo) bool {
141 up, _ := s.Store.ForkOf(ctx, repo.ID)
142 if up == 0 {
143 return false
144 }
145 u, err := s.Store.RepoByID(ctx, up)
146 return err == nil && u.Visibility != "public"
147}
148
149func (s *Server) forkPost(w http.ResponseWriter, r *http.Request) {
150 u, repo, _, ok := s.guard(w, r, access.RoleReadonly)
151 if !ok || !s.csrfOK(w, r) {
152 return
153 }
154 if u.ID == 0 {
155 http.Redirect(w, r, "/login", http.StatusSeeOther)
156 return
157 }
158 fork, err := s.opForkRepo(r.Context(), u, repo, r.FormValue("namespace"), r.FormValue("name"))
159 if !s.uiOK(w, r, repoURL(repo), err) {
160 return
161 }
162 s.redirect(w, r, repoURL(fork), s.tr(r, "flash.forked"), "")
163}
164
165func (s *Server) forksPage(w http.ResponseWriter, r *http.Request) {
166 u, repo, role, ok := s.guard(w, r, access.RoleReadonly)
167 if !ok {
168 return
169 }
170 v := s.repoView(w, r, repo, role, s.tr(r, "fork.listTitle"))
171 v.ForkList = s.visibleForks(r.Context(), u.ID, repo)
172 v.Fork = s.forkInfo(r.Context(), u.ID, repo)
173 s.render(w, "forks", v)
174}
175
176func forkJSON(fork store.Repo, upstream store.Repo) map[string]any {
177 out := projectJSON(fork)
178 out["forked_from"] = upstream.FullPath()
179 return out
180}
181
182func (s *Server) apiForkProject(w http.ResponseWriter, r *http.Request) {
183 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
184 if !ok {
185 return
186 }
187 var body struct {
188 Namespace string `json:"namespace"`
189 Name string `json:"name"`
190 }
191 if err := readJSON(r, &body); err != nil {
192 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
193 return
194 }
195 fork, err := s.opForkRepo(r.Context(), apiUser(r), repo, body.Namespace, body.Name)
196 if !s.apiOK(w, r, err) {
197 return
198 }
199 writeJSON(w, http.StatusCreated, forkJSON(fork, repo))
200}
201
202func (s *Server) apiListForks(w http.ResponseWriter, r *http.Request) {
203 repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
204 if !ok {
205 return
206 }
207 s.writeProjects(w, r, s.visibleForks(r.Context(), apiUser(r).ID, repo))
208}
internal/server/ops_collab.go +3 −0
@@ -136,6 +136,9 @@ func (s *Server) opUpdateRepo(ctx context.Context, user store.User, repo store.R
136 136 if visibility != "public" {
137 137 visibility = "private"
138 138 }
139 if visibility == "public" && s.forkMustStayPrivate(ctx, repo) {
140 return fail(400, i18n.E("err.forkPrivate"))
141 }
139 142 if err := s.Store.UpdateRepo(ctx, repo.ID, description, visibility); err != nil {
140 143 return fail(400, err)
141 144 }
@@ -136,6 +136,9 @@ func (s *Server) opUpdateRepo(ctx context.Context, user store.User, repo store.R
136 if visibility != "public" {
136 if visibility != "public" {
137 visibility = "private"
137 visibility = "private"
138 }
138 }
139 if visibility == "public" && s.forkMustStayPrivate(ctx, repo) {
140 return fail(400, i18n.E("err.forkPrivate"))
141 }
139 if err := s.Store.UpdateRepo(ctx, repo.ID, description, visibility); err != nil {
142 if err := s.Store.UpdateRepo(ctx, repo.ID, description, visibility); err != nil {
140 return fail(400, err)
143 return fail(400, err)
141 }
144 }
internal/server/repo_handlers.go +6 −0
@@ -83,6 +83,12 @@ func (s *Server) repoHome(w http.ResponseWriter, r *http.Request) {
83 83 v := s.repoView(w, r, repo, role, repo.Name)
84 84 v.Wide = true
85 85 s.fillOverview(r, &v, repo)
86 uid := int64(0)
87 if v.User != nil {
88 uid = v.User.ID
89 v.ForkTargets = s.forkTargets(r.Context(), *v.User)
90 }
91 v.Fork = s.forkInfo(r.Context(), uid, repo)
86 92 v.Heat = s.heatmap(r.Context(), 0, []int64{repo.ID}, s.langOf(r))
87 93 s.render(w, "repo", v)
88 94 }
@@ -83,6 +83,12 @@ func (s *Server) repoHome(w http.ResponseWriter, r *http.Request) {
83 v := s.repoView(w, r, repo, role, repo.Name)
83 v := s.repoView(w, r, repo, role, repo.Name)
84 v.Wide = true
84 v.Wide = true
85 s.fillOverview(r, &v, repo)
85 s.fillOverview(r, &v, repo)
86 uid := int64(0)
87 if v.User != nil {
88 uid = v.User.ID
89 v.ForkTargets = s.forkTargets(r.Context(), *v.User)
90 }
91 v.Fork = s.forkInfo(r.Context(), uid, repo)
86 v.Heat = s.heatmap(r.Context(), 0, []int64{repo.ID}, s.langOf(r))
92 v.Heat = s.heatmap(r.Context(), 0, []int64{repo.ID}, s.langOf(r))
87 s.render(w, "repo", v)
93 s.render(w, "repo", v)
88}
94}
internal/server/server.go +5 −0
@@ -238,6 +238,8 @@ func (s *Server) Handler() http.Handler {
238 238 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
239 239 mux.HandleFunc("POST /{owner}/{repo}/-/logo", s.uploadRepoLogo)
240 240 mux.HandleFunc("POST /{owner}/{repo}/-/star", s.toggleStar)
241 mux.HandleFunc("POST /{owner}/{repo}/-/fork", s.forkPost)
242 mux.HandleFunc("GET /{owner}/{repo}/-/forks", s.forksPage)
241 243 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
242 244 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
243 245 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
@@ -720,6 +722,9 @@ type View struct {
720 722 DashNext int
721 723 DashRepoN int
722 724 DashGroupN int
725 Fork ForkInfo
726 ForkTargets []ForkTarget
727 ForkList []store.Repo
723 728 FlipDir string
724 729 Cards []RepoCard
725 730 Head *CommitRow
@@ -238,6 +238,8 @@ func (s *Server) Handler() http.Handler {
238 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
238 mux.HandleFunc("GET /{owner}/{repo}/-/logo", s.repoLogo)
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)
242 mux.HandleFunc("GET /{owner}/{repo}/-/forks", s.forksPage)
241 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
243 mux.HandleFunc("GET /{owner}/{repo}/-/settings", s.settings)
242 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
244 mux.HandleFunc("POST /{owner}/{repo}/-/settings", s.updateRepo)
243 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
245 mux.HandleFunc("POST /{owner}/{repo}/-/approvals", s.saveRepoApproval)
@@ -720,6 +722,9 @@ type View struct {
720 DashNext int
722 DashNext int
721 DashRepoN int
723 DashRepoN int
722 DashGroupN int
724 DashGroupN int
725 Fork ForkInfo
726 ForkTargets []ForkTarget
727 ForkList []store.Repo
723 FlipDir string
728 FlipDir string
724 Cards []RepoCard
729 Cards []RepoCard
725 Head *CommitRow
730 Head *CommitRow
internal/server/static/transfer.js +15 −0
@@ -66,3 +66,18 @@
66 66 dialog.close();
67 67 });
68 68 })();
69
70 // Fork: eigen modal om doel en naam te kiezen.
71 (function () {
72 var open = document.querySelector("[data-fork-open]");
73 var dialog = document.querySelector("[data-fork-dialog]");
74 if (!open || !dialog) {
75 return;
76 }
77 open.addEventListener("click", function () {
78 dialog.showModal();
79 });
80 dialog.querySelector("[data-fork-cancel]").addEventListener("click", function () {
81 dialog.close();
82 });
83 })();
@@ -66,3 +66,18 @@
66 dialog.close();
66 dialog.close();
67 });
67 });
68})();
68})();
69
70// Fork: eigen modal om doel en naam te kiezen.
71(function () {
72 var open = document.querySelector("[data-fork-open]");
73 var dialog = document.querySelector("[data-fork-dialog]");
74 if (!open || !dialog) {
75 return;
76 }
77 open.addEventListener("click", function () {
78 dialog.showModal();
79 });
80 dialog.querySelector("[data-fork-cancel]").addEventListener("click", function () {
81 dialog.close();
82 });
83})();
internal/server/templates/pages.html +32 −0
@@ -509,8 +509,27 @@
509 509 <h1>{{t "tab.overview"}}</h1>
510 510 <div class="pageacts">
511 511 <a class="btn ghost" href="/{{.Repo.FullPath}}/-/tree?rev={{.Rev}}&amp;focus=1">{{t "repo.searchFile"}}</a>
512 {{if and .User .ForkTargets (not .ReleaseOnly)}}<button type="button" class="btn ghost" data-fork-open data-tip="{{t "fork.tip"}}">{{t "fork.button"}}{{if .Fork.Forks}} <span class="count">{{.Fork.Forks}}</span>{{end}}</button>{{end}}
512 513 </div>
513 514 </header>
515 {{if and .User .ForkTargets (not .ReleaseOnly)}}
516 <dialog class="danger-modal" data-fork-dialog>
517 <form method="post" action="/{{.Repo.FullPath}}/-/fork">
518 <input type="hidden" name="csrf" value="{{.CSRF}}">
519 <h2>{{t "fork.title" .Repo.FullPath}}</h2>
520 <label>{{t "fork.target"}}
521 <select name="namespace">{{range .ForkTargets}}<option value="{{.Value}}">{{.Label}}</option>{{end}}</select>
522 </label>
523 <label>{{t "fork.name"}} <input name="name" value="{{.Repo.Name}}" required autocomplete="off"></label>
524 <p class="muted">{{t "fork.hint"}}</p>
525 <div class="row">
526 <button type="submit">{{t "fork.button"}}</button>
527 <button type="button" class="ghost" data-fork-cancel>{{t "action.cancel"}}</button>
528 </div>
529 </form>
530 </dialog>
531 <script src="/assets/transfer.js"></script>
532 {{end}}
514 533 {{if .Heat}}{{template "heatmap" .Heat}}{{end}}
515 534 <div class="proj">
516 535 <div>
@@ -530,11 +549,13 @@
530 549 <aside class="side">
531 550 <h2>{{t "repo.project"}}</h2>
532 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}}
533 553 <ul class="counts">
534 554 <li><a href="/{{.Repo.FullPath}}/-/commits?rev={{.Rev}}">{{tn .NCommits "count.commit.one" "count.commit.many"}}</a></li>
535 555 <li><a href="/{{.Repo.FullPath}}/-/branches">{{tn .NBranches "count.branch.one" "count.branch.many"}}</a></li>
536 556 <li><a href="/{{.Repo.FullPath}}/-/tags">{{tn .NTags "count.tag.one" "count.tag.many"}}</a></li>
537 557 <li><a href="/{{.Repo.FullPath}}/-/releases">{{tn .NReleases "count.release.one" "count.release.many"}}</a></li>
558 <li><a href="/{{.Repo.FullPath}}/-/forks">{{tn .Fork.Forks "count.fork.one" "count.fork.many"}}</a></li>
538 559 </ul>
539 560 {{if .ReadmeName}}<p><a href="/{{.Repo.FullPath}}/-/blob/{{.ReadmeName}}?rev={{.Rev}}">README</a></p>{{end}}
540 561 {{if .LicensePath}}<p><a href="/{{.Repo.FullPath}}/-/blob/{{.LicensePath}}?rev={{.Rev}}">LICENSE</a></p>{{end}}
@@ -767,3 +788,14 @@
767 788 </div>
768 789 {{else}}<p class="muted">{{t "runner.none"}}</p>{{end}}
769 790 {{end}}
791
792 {{define "forks"}}
793 {{template "layout-start" .}}
794 <header class="pagehead"><h1>{{t "fork.listTitle"}}</h1></header>
795 {{if .Fork.IsFork}}<p class="muted">{{if .Fork.Upstream}}{{t "fork.of"}} <a href="/{{.Fork.Upstream.FullPath}}">{{.Fork.Upstream.FullPath}}</a>{{else}}{{t "fork.hidden"}}{{end}}</p>{{end}}
796 <ul class="repolist">
797 {{range .ForkList}}<li>{{template "namemark" .}}<div class="grown"><a class="reponame" href="/{{.FullPath}}">{{.FullPath}}</a> <span class="pill">{{visName .Visibility}}</span></div></li>
798 {{else}}<li class="muted">{{t "fork.none"}}</li>{{end}}
799 </ul>
800 {{template "layout-end" .}}
801 {{end}}
@@ -509,8 +509,27 @@
509 <h1>{{t "tab.overview"}}</h1>
509 <h1>{{t "tab.overview"}}</h1>
510 <div class="pageacts">
510 <div class="pageacts">
511 <a class="btn ghost" href="/{{.Repo.FullPath}}/-/tree?rev={{.Rev}}&amp;focus=1">{{t "repo.searchFile"}}</a>
511 <a class="btn ghost" href="/{{.Repo.FullPath}}/-/tree?rev={{.Rev}}&amp;focus=1">{{t "repo.searchFile"}}</a>
512 {{if and .User .ForkTargets (not .ReleaseOnly)}}<button type="button" class="btn ghost" data-fork-open data-tip="{{t "fork.tip"}}">{{t "fork.button"}}{{if .Fork.Forks}} <span class="count">{{.Fork.Forks}}</span>{{end}}</button>{{end}}
512 </div>
513 </div>
513</header>
514</header>
515{{if and .User .ForkTargets (not .ReleaseOnly)}}
516<dialog class="danger-modal" data-fork-dialog>
517 <form method="post" action="/{{.Repo.FullPath}}/-/fork">
518 <input type="hidden" name="csrf" value="{{.CSRF}}">
519 <h2>{{t "fork.title" .Repo.FullPath}}</h2>
520 <label>{{t "fork.target"}}
521 <select name="namespace">{{range .ForkTargets}}<option value="{{.Value}}">{{.Label}}</option>{{end}}</select>
522 </label>
523 <label>{{t "fork.name"}} <input name="name" value="{{.Repo.Name}}" required autocomplete="off"></label>
524 <p class="muted">{{t "fork.hint"}}</p>
525 <div class="row">
526 <button type="submit">{{t "fork.button"}}</button>
527 <button type="button" class="ghost" data-fork-cancel>{{t "action.cancel"}}</button>
528 </div>
529 </form>
530</dialog>
531<script src="/assets/transfer.js"></script>
532{{end}}
514{{if .Heat}}{{template "heatmap" .Heat}}{{end}}
533{{if .Heat}}{{template "heatmap" .Heat}}{{end}}
515<div class="proj">
534<div class="proj">
516 <div>
535 <div>
@@ -530,11 +549,13 @@
530 <aside class="side">
549 <aside class="side">
531 <h2>{{t "repo.project"}}</h2>
550 <h2>{{t "repo.project"}}</h2>
532 {{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}}
533 <ul class="counts">
553 <ul class="counts">
534 <li><a href="/{{.Repo.FullPath}}/-/commits?rev={{.Rev}}">{{tn .NCommits "count.commit.one" "count.commit.many"}}</a></li>
554 <li><a href="/{{.Repo.FullPath}}/-/commits?rev={{.Rev}}">{{tn .NCommits "count.commit.one" "count.commit.many"}}</a></li>
535 <li><a href="/{{.Repo.FullPath}}/-/branches">{{tn .NBranches "count.branch.one" "count.branch.many"}}</a></li>
555 <li><a href="/{{.Repo.FullPath}}/-/branches">{{tn .NBranches "count.branch.one" "count.branch.many"}}</a></li>
536 <li><a href="/{{.Repo.FullPath}}/-/tags">{{tn .NTags "count.tag.one" "count.tag.many"}}</a></li>
556 <li><a href="/{{.Repo.FullPath}}/-/tags">{{tn .NTags "count.tag.one" "count.tag.many"}}</a></li>
537 <li><a href="/{{.Repo.FullPath}}/-/releases">{{tn .NReleases "count.release.one" "count.release.many"}}</a></li>
557 <li><a href="/{{.Repo.FullPath}}/-/releases">{{tn .NReleases "count.release.one" "count.release.many"}}</a></li>
558 <li><a href="/{{.Repo.FullPath}}/-/forks">{{tn .Fork.Forks "count.fork.one" "count.fork.many"}}</a></li>
538 </ul>
559 </ul>
539 {{if .ReadmeName}}<p><a href="/{{.Repo.FullPath}}/-/blob/{{.ReadmeName}}?rev={{.Rev}}">README</a></p>{{end}}
560 {{if .ReadmeName}}<p><a href="/{{.Repo.FullPath}}/-/blob/{{.ReadmeName}}?rev={{.Rev}}">README</a></p>{{end}}
540 {{if .LicensePath}}<p><a href="/{{.Repo.FullPath}}/-/blob/{{.LicensePath}}?rev={{.Rev}}">LICENSE</a></p>{{end}}
561 {{if .LicensePath}}<p><a href="/{{.Repo.FullPath}}/-/blob/{{.LicensePath}}?rev={{.Rev}}">LICENSE</a></p>{{end}}
@@ -767,3 +788,14 @@
767</div>
788</div>
768{{else}}<p class="muted">{{t "runner.none"}}</p>{{end}}
789{{else}}<p class="muted">{{t "runner.none"}}</p>{{end}}
769{{end}}
790{{end}}
791
792{{define "forks"}}
793{{template "layout-start" .}}
794<header class="pagehead"><h1>{{t "fork.listTitle"}}</h1></header>
795{{if .Fork.IsFork}}<p class="muted">{{if .Fork.Upstream}}{{t "fork.of"}} <a href="/{{.Fork.Upstream.FullPath}}">{{.Fork.Upstream.FullPath}}</a>{{else}}{{t "fork.hidden"}}{{end}}</p>{{end}}
796<ul class="repolist">
797 {{range .ForkList}}<li>{{template "namemark" .}}<div class="grown"><a class="reponame" href="/{{.FullPath}}">{{.FullPath}}</a> <span class="pill">{{visName .Visibility}}</span></div></li>
798 {{else}}<li class="muted">{{t "fork.none"}}</li>{{end}}
799</ul>
800{{template "layout-end" .}}
801{{end}}
internal/store/forks.go added +34 −0
@@ -0,0 +1,34 @@
1 package store
2
3 import "context"
4
5 // SetForkOf legt vast dat repo een fork is van upstream.
6 func (s *Store) SetForkOf(ctx context.Context, repoID, upstreamID int64) error {
7 _, err := s.db.ExecContext(ctx, `UPDATE repos SET fork_of = ? WHERE id = ?`, upstreamID, repoID)
8 return err
9 }
10
11 // ForkOf geeft de upstream-id (0 = geen fork).
12 func (s *Store) ForkOf(ctx context.Context, repoID int64) (int64, error) {
13 var id int64
14 err := s.db.QueryRowContext(ctx, `SELECT fork_of FROM repos WHERE id = ?`, repoID).Scan(&id)
15 return id, err
16 }
17
18 // ForkIDs geeft de ids van de directe forks van upstream.
19 func (s *Store) ForkIDs(ctx context.Context, upstreamID int64) ([]int64, error) {
20 rows, err := s.db.QueryContext(ctx, `SELECT id FROM repos WHERE fork_of = ? ORDER BY id`, upstreamID)
21 if err != nil {
22 return nil, err
23 }
24 defer rows.Close()
25 var out []int64
26 for rows.Next() {
27 var id int64
28 if err := rows.Scan(&id); err != nil {
29 return nil, err
30 }
31 out = append(out, id)
32 }
33 return out, rows.Err()
34 }
@@ -0,0 +1,34 @@
1package store
2
3import "context"
4
5// SetForkOf legt vast dat repo een fork is van upstream.
6func (s *Store) SetForkOf(ctx context.Context, repoID, upstreamID int64) error {
7 _, err := s.db.ExecContext(ctx, `UPDATE repos SET fork_of = ? WHERE id = ?`, upstreamID, repoID)
8 return err
9}
10
11// ForkOf geeft de upstream-id (0 = geen fork).
12func (s *Store) ForkOf(ctx context.Context, repoID int64) (int64, error) {
13 var id int64
14 err := s.db.QueryRowContext(ctx, `SELECT fork_of FROM repos WHERE id = ?`, repoID).Scan(&id)
15 return id, err
16}
17
18// ForkIDs geeft de ids van de directe forks van upstream.
19func (s *Store) ForkIDs(ctx context.Context, upstreamID int64) ([]int64, error) {
20 rows, err := s.db.QueryContext(ctx, `SELECT id FROM repos WHERE fork_of = ? ORDER BY id`, upstreamID)
21 if err != nil {
22 return nil, err
23 }
24 defer rows.Close()
25 var out []int64
26 for rows.Next() {
27 var id int64
28 if err := rows.Scan(&id); err != nil {
29 return nil, err
30 }
31 out = append(out, id)
32 }
33 return out, rows.Err()
34}
internal/store/repos.go +4 −0
@@ -355,6 +355,10 @@ func (s *Store) UpdateRepo(ctx context.Context, id int64, description, visibilit
355 355
356 356 // DeleteRepo verwijdert de metadata. Bestanden verwijdert de aanroeper.
357 357 func (s *Store) DeleteRepo(ctx context.Context, id int64) error {
358 // Forks blijven bestaan als zelfstandige repositories.
359 if _, err := s.db.ExecContext(ctx, `UPDATE repos SET fork_of = 0 WHERE fork_of = ?`, id); err != nil {
360 return err
361 }
358 362 _, err := s.db.ExecContext(ctx, `DELETE FROM repos WHERE id = ?`, id)
359 363 return err
360 364 }
@@ -355,6 +355,10 @@ func (s *Store) UpdateRepo(ctx context.Context, id int64, description, visibilit
355
355
356// DeleteRepo verwijdert de metadata. Bestanden verwijdert de aanroeper.
356// DeleteRepo verwijdert de metadata. Bestanden verwijdert de aanroeper.
357func (s *Store) DeleteRepo(ctx context.Context, id int64) error {
357func (s *Store) DeleteRepo(ctx context.Context, id int64) error {
358 // Forks blijven bestaan als zelfstandige repositories.
359 if _, err := s.db.ExecContext(ctx, `UPDATE repos SET fork_of = 0 WHERE fork_of = ?`, id); err != nil {
360 return err
361 }
358 _, err := s.db.ExecContext(ctx, `DELETE FROM repos WHERE id = ?`, id)
362 _, err := s.db.ExecContext(ctx, `DELETE FROM repos WHERE id = ?`, id)
359 return err
363 return err
360}
364}
internal/store/store.go +1 −0
@@ -65,6 +65,7 @@ func (s *Store) migrate() error {
65 65 `ALTER TABLE repos ADD COLUMN release_visibility TEXT NOT NULL DEFAULT 'inherit'`,
66 66 `ALTER TABLE repos ADD COLUMN pushed_at TEXT NOT NULL DEFAULT ''`,
67 67 `ALTER TABLE secrets ADD COLUMN expand INTEGER NOT NULL DEFAULT 0`,
68 `ALTER TABLE repos ADD COLUMN fork_of INTEGER NOT NULL DEFAULT 0`,
68 69 `ALTER TABLE webhooks ADD COLUMN method TEXT NOT NULL DEFAULT 'POST'`,
69 70 `ALTER TABLE notes ADD COLUMN file_path TEXT NOT NULL DEFAULT ''`,
70 71 `ALTER TABLE notes ADD COLUMN line_start INTEGER NOT NULL DEFAULT 0`,
@@ -65,6 +65,7 @@ func (s *Store) migrate() error {
65 `ALTER TABLE repos ADD COLUMN release_visibility TEXT NOT NULL DEFAULT 'inherit'`,
65 `ALTER TABLE repos ADD COLUMN release_visibility TEXT NOT NULL DEFAULT 'inherit'`,
66 `ALTER TABLE repos ADD COLUMN pushed_at TEXT NOT NULL DEFAULT ''`,
66 `ALTER TABLE repos ADD COLUMN pushed_at TEXT NOT NULL DEFAULT ''`,
67 `ALTER TABLE secrets ADD COLUMN expand INTEGER NOT NULL DEFAULT 0`,
67 `ALTER TABLE secrets ADD COLUMN expand INTEGER NOT NULL DEFAULT 0`,
68 `ALTER TABLE repos ADD COLUMN fork_of INTEGER NOT NULL DEFAULT 0`,
68 `ALTER TABLE webhooks ADD COLUMN method TEXT NOT NULL DEFAULT 'POST'`,
69 `ALTER TABLE webhooks ADD COLUMN method TEXT NOT NULL DEFAULT 'POST'`,
69 `ALTER TABLE notes ADD COLUMN file_path TEXT NOT NULL DEFAULT ''`,
70 `ALTER TABLE notes ADD COLUMN file_path TEXT NOT NULL DEFAULT ''`,
70 `ALTER TABLE notes ADD COLUMN line_start INTEGER NOT NULL DEFAULT 0`,
71 `ALTER TABLE notes ADD COLUMN line_start INTEGER NOT NULL DEFAULT 0`,