From 6df055493b1600051e467b79d296fa292f658d3f Mon Sep 17 00:00:00 2001 From: Han-Wen Nienhuys Date: Tue, 23 Apr 2024 12:52:11 +0200 Subject: [PATCH] gitindex: interpret SSH URLs (#764) This allows indexing repos that are used for development and therefore have an SSH 'origin' URL. --- gitindex/index.go | 16 ++++++++++++++++ gitindex/index_test.go | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/gitindex/index.go b/gitindex/index.go index d3a5e3c64..eb2588b3c 100644 --- a/gitindex/index.go +++ b/gitindex/index.go @@ -27,6 +27,7 @@ import ( "net/url" "os" "path/filepath" + "regexp" "sort" "strconv" "strings" @@ -111,6 +112,11 @@ func FindGitRepos(dir string) ([]string, error) { // setTemplates fills in URL templates for known git hosting // sites. func setTemplates(repo *zoekt.Repository, u *url.URL, typ string) error { + if u.Scheme == "ssh+git" { + u.Scheme = "https" + u.User = nil + } + repo.URL = u.String() switch typ { case "gitiles": @@ -192,6 +198,8 @@ func configLookupRemoteURL(cfg *config.Config, key string) string { return rc.URLs[0] } +var sshRelativeURLRegexp = regexp.MustCompile(`^([^@]+)@([^:]+):(.*)$`) + func setTemplatesFromConfig(desc *zoekt.Repository, repoDir string) error { repo, err := git.PlainOpen(repoDir) if err != nil { @@ -228,6 +236,14 @@ func setTemplatesFromConfig(desc *zoekt.Repository, repoDir string) error { if remoteURL == "" { return nil } + if sm := sshRelativeURLRegexp.FindStringSubmatch(remoteURL); sm != nil { + user := sm[1] + host := sm[2] + path := sm[3] + + remoteURL = fmt.Sprintf("ssh+git://%s@%s/%s", user, host, path) + } + u, err := url.Parse(remoteURL) if err != nil { return err diff --git a/gitindex/index_test.go b/gitindex/index_test.go index a14f32fe3..bf5993717 100644 --- a/gitindex/index_test.go +++ b/gitindex/index_test.go @@ -768,3 +768,19 @@ func runScript(t *testing.T, cwd string, script string) { t.Fatalf("execution error: %v, output %s", err, out) } } + +func TestSetTemplate(t *testing.T) { + repositoryDir := t.TempDir() + + // setup: initialize the repository and all of its branches + runScript(t, repositoryDir, "git init -b master") + runScript(t, repositoryDir, "git config remote.origin.url git@github.com:sourcegraph/zoekt.git") + desc := zoekt.Repository{} + if err := setTemplatesFromConfig(&desc, repositoryDir); err != nil { + t.Fatalf("setTemplatesFromConfig: %v", err) + } + + if got, want := desc.FileURLTemplate, "https://github.com/sourcegraph/zoekt/blob/{{.Version}}/{{.Path}}"; got != want { + t.Errorf("got %q, want %q", got, want) + } +}