submodule.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2020 The Gogs 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. package gitutil
  5. import (
  6. "fmt"
  7. "net/url"
  8. "strings"
  9. "github.com/gogs/git-module"
  10. "gogs.io/gogs/internal/lazyregexp"
  11. )
  12. var scpSyntax = lazyregexp.New(`^([a-zA-Z0-9_]+@)?([a-zA-Z0-9._-]+):(.*)$`)
  13. // InferSubmoduleURL returns the inferred external URL of the submodule at best effort.
  14. func InferSubmoduleURL(mod *git.Submodule) string {
  15. raw := strings.TrimSuffix(mod.URL, "/")
  16. raw = strings.TrimSuffix(raw, ".git")
  17. parsed, err := url.Parse(raw)
  18. if err != nil {
  19. // Try parse as SCP syntax again
  20. match := scpSyntax.FindAllStringSubmatch(raw, -1)
  21. if len(match) == 0 {
  22. return mod.URL
  23. }
  24. parsed = &url.URL{
  25. Scheme: "http",
  26. Host: match[0][2],
  27. Path: match[0][3],
  28. }
  29. }
  30. switch parsed.Scheme {
  31. case "http", "https":
  32. raw = parsed.String()
  33. case "ssh":
  34. raw = fmt.Sprintf("http://%s%s", parsed.Host, parsed.Path)
  35. default:
  36. return raw
  37. }
  38. return fmt.Sprintf("%s/commit/%s", raw, mod.Commit)
  39. }