Browse Source

Redirects for renamed repos (#807)

* Redirects for renamed repos

* Remove unused phrase from locales
Ethan Koenig 2 years ago
parent
commit
027591a3a5

+ 16 - 0
models/error.go

@@ -408,6 +408,22 @@ func (err ErrRepoAlreadyExist) Error() string {
408 408
 	return fmt.Sprintf("repository already exists [uname: %s, name: %s]", err.Uname, err.Name)
409 409
 }
410 410
 
411
+// ErrRepoRedirectNotExist represents a "RepoRedirectNotExist" kind of error.
412
+type ErrRepoRedirectNotExist struct {
413
+	OwnerID int64
414
+	RepoName string
415
+}
416
+
417
+// IsErrRepoRedirectNotExist check if an error is an ErrRepoRedirectNotExist
418
+func IsErrRepoRedirectNotExist(err error) bool {
419
+	_, ok := err.(ErrRepoRedirectNotExist)
420
+	return ok
421
+}
422
+
423
+func (err ErrRepoRedirectNotExist) Error() string {
424
+	return fmt.Sprintf("repository redirect does not exist [uid: %d, name: %s]", err.OwnerID, err.RepoName)
425
+}
426
+
411 427
 // ErrInvalidCloneAddr represents a "InvalidCloneAddr" kind of error.
412 428
 type ErrInvalidCloneAddr struct {
413 429
 	IsURLError         bool

+ 1 - 0
models/models.go

@@ -109,6 +109,7 @@ func init() {
109 109
 		new(LFSMetaObject),
110 110
 		new(TwoFactor),
111 111
 		new(RepoUnit),
112
+		new(RepoRedirect),
112 113
 	)
113 114
 
114 115
 	gonicNames := []string{"SSL", "UID"}

+ 3 - 0
models/repo.go

@@ -1054,6 +1054,9 @@ func createRepository(e *xorm.Session, u *User, repo *Repository) (err error) {
1054 1054
 	if _, err = e.Insert(repo); err != nil {
1055 1055
 		return err
1056 1056
 	}
1057
+	if err = deleteRepoRedirect(e, u.ID, repo.Name); err != nil {
1058
+		return err
1059
+	}
1057 1060
 
1058 1061
 	// insert units for repo
1059 1062
 	var units = make([]RepoUnit, 0, len(defaultRepoUnits))

+ 62 - 0
models/repo_redirect.go

@@ -0,0 +1,62 @@
1
+// Copyright 2017 The Gitea Authors. All rights reserved.
2
+// Use of this source code is governed by a MIT-style
3
+// license that can be found in the LICENSE file.
4
+
5
+package models
6
+
7
+import "strings"
8
+
9
+// RepoRedirect represents that a repo name should be redirected to another
10
+type RepoRedirect struct {
11
+	ID             int64  `xorm:"pk autoincr"`
12
+	OwnerID        int64  `xorm:"UNIQUE(s)"`
13
+	LowerName      string `xorm:"UNIQUE(s) INDEX NOT NULL"`
14
+	RedirectRepoID int64  // repoID to redirect to
15
+}
16
+
17
+// LookupRepoRedirect look up if a repository has a redirect name
18
+func LookupRepoRedirect(ownerID int64, repoName string) (int64, error) {
19
+	repoName = strings.ToLower(repoName)
20
+	redirect := &RepoRedirect{OwnerID: ownerID, LowerName: repoName}
21
+	if has, err := x.Get(redirect); err != nil {
22
+		return 0, err
23
+	} else if !has {
24
+		return 0, ErrRepoRedirectNotExist{OwnerID: ownerID, RepoName: repoName}
25
+	}
26
+	return redirect.RedirectRepoID, nil
27
+}
28
+
29
+// NewRepoRedirect create a new repo redirect
30
+func NewRepoRedirect(ownerID, repoID int64, oldRepoName, newRepoName string) error {
31
+	oldRepoName = strings.ToLower(oldRepoName)
32
+	newRepoName = strings.ToLower(newRepoName)
33
+	sess := x.NewSession()
34
+	defer sess.Close()
35
+
36
+	if err := sess.Begin(); err != nil {
37
+		return err
38
+	}
39
+
40
+	if err := deleteRepoRedirect(sess, ownerID, newRepoName); err != nil {
41
+		sess.Rollback()
42
+		return err
43
+	}
44
+
45
+	if _, err := sess.Insert(&RepoRedirect{
46
+		OwnerID:        ownerID,
47
+		LowerName:      oldRepoName,
48
+		RedirectRepoID: repoID,
49
+	}); err != nil {
50
+		sess.Rollback()
51
+		return err
52
+	}
53
+	return sess.Commit()
54
+}
55
+
56
+// deleteRepoRedirect delete any redirect from the specified repo name to
57
+// anything else
58
+func deleteRepoRedirect(e Engine, ownerID int64, repoName string) error {
59
+	repoName = strings.ToLower(repoName)
60
+	_, err := e.Delete(&RepoRedirect{OwnerID: ownerID, LowerName: repoName})
61
+	return err
62
+}

+ 31 - 4
modules/context/repo.go

@@ -133,6 +133,26 @@ func earlyResponseForGoGetMeta(ctx *Context) {
133 133
 		})))
134 134
 }
135 135
 
136
+// RedirectToRepo redirect to a differently-named repository
137
+func RedirectToRepo(ctx *Context, redirectRepoID int64) {
138
+	ownerName := ctx.Params(":username")
139
+	previousRepoName := ctx.Params(":reponame")
140
+
141
+	repo, err := models.GetRepositoryByID(redirectRepoID)
142
+	if err != nil {
143
+		ctx.Handle(500, "GetRepositoryByID", err)
144
+		return
145
+	}
146
+
147
+	redirectPath := strings.Replace(
148
+		ctx.Req.URL.Path,
149
+		fmt.Sprintf("%s/%s", ownerName, previousRepoName),
150
+		fmt.Sprintf("%s/%s", ownerName, repo.Name),
151
+		1,
152
+	)
153
+	ctx.Redirect(redirectPath)
154
+}
155
+
136 156
 // RepoAssignment returns a macaron to handle repository assignment
137 157
 func RepoAssignment(args ...bool) macaron.Handler {
138 158
 	return func(ctx *Context) {
@@ -176,11 +196,18 @@ func RepoAssignment(args ...bool) macaron.Handler {
176 196
 		repo, err := models.GetRepositoryByName(owner.ID, repoName)
177 197
 		if err != nil {
178 198
 			if models.IsErrRepoNotExist(err) {
179
-				if ctx.Query("go-get") == "1" {
180
-					earlyResponseForGoGetMeta(ctx)
181
-					return
199
+				redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
200
+				if err == nil {
201
+					RedirectToRepo(ctx, redirectRepoID)
202
+				} else if models.IsErrRepoRedirectNotExist(err) {
203
+					if ctx.Query("go-get") == "1" {
204
+						earlyResponseForGoGetMeta(ctx)
205
+						return
206
+					}
207
+					ctx.Handle(404, "GetRepositoryByName", err)
208
+				} else {
209
+					ctx.Handle(500, "LookupRepoRedirect", err)
182 210
 				}
183
-				ctx.Handle(404, "GetRepositoryByName", err)
184 211
 			} else {
185 212
 				ctx.Handle(500, "GetRepositoryByName", err)
186 213
 			}

+ 0 - 1
options/locale/locale_bg-BG.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Синхр. сега
636 636
 settings.mirror_sync_in_progress=Синхронизация на огледалото е в ход, моля обновете страницата след минута.
637 637
 settings.site=Официален сайт
638 638
 settings.update_settings=Запази настройките
639
-settings.change_reponame_prompt=Тази промяна ще засегне връзките, които се отнасят до това хранилището.
640 639
 settings.advanced_settings=Разширени настройки
641 640
 settings.wiki_desc=Включи система за уики
642 641
 settings.use_internal_wiki=Използвай вградено уики

+ 0 - 1
options/locale/locale_cs-CZ.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Provést synchronizaci
636 636
 settings.mirror_sync_in_progress=Synchronizace zrcadel probíhá, prosím načtěte znovu stránku přibližně za minutu.
637 637
 settings.site=Oficiální stránky
638 638
 settings.update_settings=Změnit nastavení
639
-settings.change_reponame_prompt=Tato změna ovlivní vztah odkazů k repositáři.
640 639
 settings.advanced_settings=Pokročilá nastavení
641 640
 settings.wiki_desc=Povolit systém Wiki
642 641
 settings.use_internal_wiki=Použít vestavěný systém Wiki

+ 0 - 1
options/locale/locale_de-DE.ini

@@ -643,7 +643,6 @@ settings.sync_mirror=Jetzt synchronisieren
643 643
 settings.mirror_sync_in_progress=Mirror Synchronisierung läuft, bitte die Seite in ca. einer Minute neu laden.
644 644
 settings.site=Offizielle Webseite
645 645
 settings.update_settings=Einstellungen speichern
646
-settings.change_reponame_prompt=Diese Änderung wirkt sich darauf aus, wie sich Links auf Repositories beziehen.
647 646
 settings.advanced_settings=Erweiterte Einstellungen
648 647
 settings.wiki_desc=Wiki einschalten
649 648
 settings.use_internal_wiki=Eingebautes Wiki verwenden

+ 0 - 1
options/locale/locale_en-US.ini

@@ -699,7 +699,6 @@ settings.sync_mirror = Sync Now
699 699
 settings.mirror_sync_in_progress = Mirror syncing is in progress, please refresh page in about a minute.
700 700
 settings.site = Official Site
701 701
 settings.update_settings = Update Settings
702
-settings.change_reponame_prompt = This change will affect how links relate to the repository.
703 702
 settings.advanced_settings = Advanced Settings
704 703
 settings.wiki_desc = Enable wiki system
705 704
 settings.use_internal_wiki = Use builtin wiki

+ 0 - 1
options/locale/locale_es-ES.ini

@@ -637,7 +637,6 @@ settings.sync_mirror=Sincronizar ahora
637 637
 settings.mirror_sync_in_progress=Sincronización de réplica en curso, por favor actualice la página en unos minutos.
638 638
 settings.site=Sitio oficial
639 639
 settings.update_settings=Actualizar configuración
640
-settings.change_reponame_prompt=Este cambio afectará a los enlaces al repositorio.
641 640
 settings.advanced_settings=Ajustes avanzados
642 641
 settings.wiki_desc=Activar sistema de wiki
643 642
 settings.use_internal_wiki=Usar wiki integrada

+ 0 - 1
options/locale/locale_fi-FI.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Sync Now
636 636
 settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute.
637 637
 settings.site=Virallinen sivusto
638 638
 settings.update_settings=Päivitä asetukset
639
-settings.change_reponame_prompt=Tämä muutos vaikuttaa siihen miten linkit liittyvät repoon.
640 639
 settings.advanced_settings=Lisäasetukset
641 640
 settings.wiki_desc=Enable wiki system
642 641
 settings.use_internal_wiki=Use builtin wiki

+ 0 - 1
options/locale/locale_fr-FR.ini

@@ -637,7 +637,6 @@ settings.sync_mirror=Synchroniser maintenant
637 637
 settings.mirror_sync_in_progress=Synchronisation du miroir en cours, merci de rafraîchir la page dans une minute environ.
638 638
 settings.site=Site officiel
639 639
 settings.update_settings=Valider
640
-settings.change_reponame_prompt=Ce changement affectera comment les liens sont reliés avec le dépôt.
641 640
 settings.advanced_settings=Paramètres avancés
642 641
 settings.wiki_desc=Activer le wiki
643 642
 settings.use_internal_wiki=Utiliser le wiki interne

+ 0 - 1
options/locale/locale_it-IT.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Sync Now
636 636
 settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute.
637 637
 settings.site=Sito Ufficiale
638 638
 settings.update_settings=Aggiorna Impostazioni
639
-settings.change_reponame_prompt=Questa modifica influirà i link al repository.
640 639
 settings.advanced_settings=Opzioni avanzate
641 640
 settings.wiki_desc=Enable wiki system
642 641
 settings.use_internal_wiki=Use builtin wiki

+ 0 - 1
options/locale/locale_ja-JP.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=今すぐ同期
636 636
 settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute.
637 637
 settings.site=公式サイト
638 638
 settings.update_settings=設定の更新
639
-settings.change_reponame_prompt=この変更はリンクがリポジトリに関連付ける方法に影響します。
640 639
 settings.advanced_settings=拡張設定
641 640
 settings.wiki_desc=Enable wiki system
642 641
 settings.use_internal_wiki=Use builtin wiki

+ 0 - 1
options/locale/locale_ko-KR.ini

@@ -637,7 +637,6 @@ settings.sync_mirror=지금 동기화
637 637
 settings.mirror_sync_in_progress=미러 동기화 진행 중입니다. 약 1분 뒤에 페이지를 새로 고침 하세요.
638 638
 settings.site=공식 사이트
639 639
 settings.update_settings=설정 저장
640
-settings.change_reponame_prompt=이 변경은 이 저장소와 연관된 링크들에 영향을 줄 것입니다.
641 640
 settings.advanced_settings=고급 설정
642 641
 settings.wiki_desc=위키 시스템 활성화
643 642
 settings.use_internal_wiki=내장 위키 사용

+ 0 - 1
options/locale/locale_lv-LV.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Sinhronizēt tagad
636 636
 settings.mirror_sync_in_progress=Notiek spoguļa sinhronizācija, uzgaidiet aptuveni minūti un atjaunojiet lapu.
637 637
 settings.site=Oficiālā mājas lapa
638 638
 settings.update_settings=Mainīt iestatījumus
639
-settings.change_reponame_prompt=Šī izmaiņa ietekmēs saites, kas ir saistītas ar šo repozitoriju.
640 639
 settings.advanced_settings=Papildu iestatījumi
641 640
 settings.wiki_desc=Iespējot vikivietnes
642 641
 settings.use_internal_wiki=Izmantot iebūvēto vikivietni

+ 0 - 1
options/locale/locale_nl-NL.ini

@@ -637,7 +637,6 @@ settings.sync_mirror=Sync Now
637 637
 settings.mirror_sync_in_progress=Kopie synchronisatie is bezig, vernieuw de pagina over ongeveer een minuut.
638 638
 settings.site=Officiële site
639 639
 settings.update_settings=Instellingen bewerken
640
-settings.change_reponame_prompt=Deze verandering zal gevolgen hebben voor hoe links zich verhouden tot de repository.
641 640
 settings.advanced_settings=Geavanceerde opties
642 641
 settings.wiki_desc=Enable wiki system
643 642
 settings.use_internal_wiki=Use builtin wiki

+ 0 - 1
options/locale/locale_pl-PL.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Synchronizuj teraz
636 636
 settings.mirror_sync_in_progress=Synchronizacja kopii lustrzanej jest w toku, odśwież stronę w ciągu minuty.
637 637
 settings.site=Oficjalna Strona
638 638
 settings.update_settings=Aktualizuj ustawienia
639
-settings.change_reponame_prompt=Zmiana nazwy repozytorium wpłynie na linki do niego.
640 639
 settings.advanced_settings=Ustawienia zaawansowane
641 640
 settings.wiki_desc=Włącz system wiki
642 641
 settings.use_internal_wiki=Użyj wbudowanego wiki

+ 0 - 1
options/locale/locale_pt-BR.ini

@@ -637,7 +637,6 @@ settings.sync_mirror=Sincronizar agora
637 637
 settings.mirror_sync_in_progress=A sincronização do mirror está em andamento, por favor atualize a página em aproximadamente um minuto.
638 638
 settings.site=Site oficial
639 639
 settings.update_settings=Atualizar configurações
640
-settings.change_reponame_prompt=Esta mudança irá afetar os links para este repositório.
641 640
 settings.advanced_settings=Configurações avançadas
642 641
 settings.wiki_desc=Habilitar sistema de wiki
643 642
 settings.use_internal_wiki=Usar wiki nativa

+ 0 - 1
options/locale/locale_ru-RU.ini

@@ -644,7 +644,6 @@ settings.sync_mirror=Синхронизировать
644 644
 settings.mirror_sync_in_progress=Выполняется синхронизация Зеркала, пожалуйста, обновите эту страницу через минуту.
645 645
 settings.site=Официальный сайт
646 646
 settings.update_settings=Обновить настройки
647
-settings.change_reponame_prompt=Это изменение повлияет на отношения ссылок к этому репозиторию.
648 647
 settings.advanced_settings=Расширенные настройки
649 648
 settings.wiki_desc=Включить систему Wiki
650 649
 settings.use_internal_wiki=Использовать встроенную wiki

+ 0 - 1
options/locale/locale_sr-SP.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Изврши синхронизацију сада
636 636
 settings.mirror_sync_in_progress=Синхронизација је у току, молимо вас да освежите страницу ускоро.
637 637
 settings.site=Званични сајт
638 638
 settings.update_settings=Примени промене
639
-settings.change_reponame_prompt=Ова промена ће утицати на однос линкова на спремиште.
640 639
 settings.advanced_settings=Напредна подешавања
641 640
 settings.wiki_desc=Омогући систем вики
642 641
 settings.use_internal_wiki=Користи уграђен вики

+ 0 - 1
options/locale/locale_sv-SE.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Synkronisera nu
636 636
 settings.mirror_sync_in_progress=Spegningssynkronisering pågår, vänligen ladda om sidan om cirka en minut.
637 637
 settings.site=Officiell webbplats
638 638
 settings.update_settings=Uppdatera inställningar
639
-settings.change_reponame_prompt=Denna ändring kommer att påverka hur länkar relaterar till detta repo.
640 639
 settings.advanced_settings=Advancerade Inställningar
641 640
 settings.wiki_desc=Aktivera wikisystem
642 641
 settings.use_internal_wiki=Använd inbyggd wiki

+ 0 - 1
options/locale/locale_tr-TR.ini

@@ -636,7 +636,6 @@ settings.sync_mirror=Sync Now
636 636
 settings.mirror_sync_in_progress=Mirror syncing is in progress, please refresh page in about a minute.
637 637
 settings.site=Resmi Web Sitesi
638 638
 settings.update_settings=Ayarları Güncelle
639
-settings.change_reponame_prompt=Bu değişiklik, bağlantıların depoyla olan ilişkisini etkileyecektir.
640 639
 settings.advanced_settings=Gelişmiş Ayarlar
641 640
 settings.wiki_desc=Viki sıstemini etkinleştir
642 641
 settings.use_internal_wiki=Use builtin wiki

+ 0 - 1
options/locale/locale_zh-CN.ini

@@ -650,7 +650,6 @@ settings.sync_mirror=立即同步
650 650
 settings.mirror_sync_in_progress=镜像同步请求已经生效,请稍后刷新页面。
651 651
 settings.site=官方网站
652 652
 settings.update_settings=更新仓库设置
653
-settings.change_reponame_prompt=该操作将会影响到所有与该仓库有关的链接
654 653
 settings.advanced_settings=高级设置
655 654
 settings.wiki_desc=启用 Wiki 系统
656 655
 settings.use_internal_wiki=使用内置 Wiki 系统

+ 0 - 1
options/locale/locale_zh-HK.ini

@@ -645,7 +645,6 @@ settings.sync_mirror=立即同步
645 645
 settings.mirror_sync_in_progress=鏡像同步正在進行中,請大約一分鐘後刷新頁面。
646 646
 settings.site=官方網站
647 647
 settings.update_settings=更新儲存庫設定
648
-settings.change_reponame_prompt=該操作將會影響到所有與該儲存庫有關的鏈接
649 648
 settings.advanced_settings=高級設定
650 649
 settings.wiki_desc=啓用 Wiki 系統
651 650
 settings.use_internal_wiki=使用內建 wiki

+ 0 - 1
options/locale/locale_zh-TW.ini

@@ -645,7 +645,6 @@ settings.sync_mirror=立即同步
645 645
 settings.mirror_sync_in_progress=鏡像同步正在進行中,請大約一分鐘後刷新頁面。
646 646
 settings.site=官方網站
647 647
 settings.update_settings=更新儲存庫設定
648
-settings.change_reponame_prompt=該操作將會影響到所有與該儲存庫有關的鏈接
649 648
 settings.advanced_settings=高級設定
650 649
 settings.wiki_desc=啓用 Wiki 系統
651 650
 settings.use_internal_wiki=使用內建 wiki

+ 8 - 1
routers/api/v1/api.go

@@ -52,7 +52,14 @@ func repoAssignment() macaron.Handler {
52 52
 		repo, err := models.GetRepositoryByName(owner.ID, repoName)
53 53
 		if err != nil {
54 54
 			if models.IsErrRepoNotExist(err) {
55
-				ctx.Status(404)
55
+				redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
56
+				if err == nil {
57
+					context.RedirectToRepo(ctx.Context, redirectRepoID)
58
+				} else if models.IsErrRepoRedirectNotExist(err) {
59
+					ctx.Status(404)
60
+				} else {
61
+					ctx.Error(500, "LookupRepoRedirect", err)
62
+				}
56 63
 			} else {
57 64
 				ctx.Error(500, "GetRepositoryByName", err)
58 65
 			}

+ 5 - 0
routers/repo/setting.go

@@ -68,6 +68,11 @@ func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
68 68
 				return
69 69
 			}
70 70
 
71
+			err := models.NewRepoRedirect(ctx.Repo.Owner.ID, repo.ID, repo.Name, newRepoName)
72
+			if err != nil {
73
+				ctx.Handle(500, "NewRepoRedirect", err)
74
+			}
75
+
71 76
 			log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName)
72 77
 		}
73 78
 		// In case it's just a case change.

+ 1 - 1
templates/repo/settings/options.tmpl

@@ -14,7 +14,7 @@
14 14
 						{{.CsrfTokenHtml}}
15 15
 						<input type="hidden" name="action" value="update">
16 16
 						<div class="required field {{if .Err_RepoName}}error{{end}}">
17
-							<label for="repo_name">{{.i18n.Tr "repo.repo_name"}}<span class="text red hide" id="repo-name-change-prompt"> {{.i18n.Tr "repo.settings.change_reponame_prompt"}}</span></label>
17
+							<label for="repo_name">{{.i18n.Tr "repo.repo_name"}}</label>
18 18
 							<input id="repo_name" name="repo_name" value="{{.Repository.Name}}" data-repo-name="{{.Repository.Name}}" autofocus required>
19 19
 						</div>
20 20
 						<div class="field {{if .Err_Description}}error{{end}}">