From dda1092e74fa82f23a7ad62434fc60200f8df5ca Mon Sep 17 00:00:00 2001 From: ᴜɴᴋɴᴡᴏɴ Date: Fri, 18 Sep 2020 16:19:31 +0800 Subject: gitutil: infer submodule with baseURL when it is a relative path (#6337) --- internal/gitutil/submodule.go | 13 ++++++++++++- internal/gitutil/submodule_test.go | 10 +++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) (limited to 'internal/gitutil') diff --git a/internal/gitutil/submodule.go b/internal/gitutil/submodule.go index e46f48a1..73e08040 100644 --- a/internal/gitutil/submodule.go +++ b/internal/gitutil/submodule.go @@ -17,10 +17,21 @@ import ( var scpSyntax = lazyregexp.New(`^([a-zA-Z0-9_]+@)?([a-zA-Z0-9._-]+):(.*)$`) // InferSubmoduleURL returns the inferred external URL of the submodule at best effort. -func InferSubmoduleURL(mod *git.Submodule) string { +// The `baseURL` should be the URL of the current repository. If the submodule URL looks +// like a relative path, it assumes that the submodule is another repository on the same +// Gogs instance by appending it to the `baseURL` with the commit. +func InferSubmoduleURL(baseURL string, mod *git.Submodule) string { + if !strings.HasSuffix(baseURL, "/") { + baseURL += "/" + } + raw := strings.TrimSuffix(mod.URL, "/") raw = strings.TrimSuffix(raw, ".git") + if strings.HasPrefix(raw, "../") { + return fmt.Sprintf("%s%s/commit/%s", baseURL, raw, mod.Commit) + } + parsed, err := url.Parse(raw) if err != nil { // Try parse as SCP syntax again diff --git a/internal/gitutil/submodule_test.go b/internal/gitutil/submodule_test.go index 2bfe5706..53f48766 100644 --- a/internal/gitutil/submodule_test.go +++ b/internal/gitutil/submodule_test.go @@ -41,6 +41,14 @@ func TestInferSubmoduleURL(t *testing.T) { }, expURL: "http://github.com/gogs/docs-api/commit/6b08f76a5313fa3d26859515b30aa17a5faa2807", }, + { + name: "relative path", + submodule: &git.Submodule{ + URL: "../repo2.git", + Commit: "6b08f76a5313fa3d26859515b30aa17a5faa2807", + }, + expURL: "https://gogs.example.com/user/repo/../repo2/commit/6b08f76a5313fa3d26859515b30aa17a5faa2807", + }, { name: "bad URL", submodule: &git.Submodule{ @@ -52,7 +60,7 @@ func TestInferSubmoduleURL(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - assert.Equal(t, test.expURL, InferSubmoduleURL(test.submodule)) + assert.Equal(t, test.expURL, InferSubmoduleURL("https://gogs.example.com/user/repo", test.submodule)) }) } } -- cgit v1.2.3