You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package lfs
  4. import (
  5. "net/url"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/util"
  12. )
  13. // DetermineEndpoint determines an endpoint from the clone url or uses the specified LFS url.
  14. func DetermineEndpoint(cloneurl, lfsurl string) *url.URL {
  15. if len(lfsurl) > 0 {
  16. return endpointFromURL(lfsurl)
  17. }
  18. return endpointFromCloneURL(cloneurl)
  19. }
  20. func endpointFromCloneURL(rawurl string) *url.URL {
  21. ep := endpointFromURL(rawurl)
  22. if ep == nil {
  23. return ep
  24. }
  25. ep.Path = strings.TrimSuffix(ep.Path, "/")
  26. if ep.Scheme == "file" {
  27. return ep
  28. }
  29. if path.Ext(ep.Path) == ".git" {
  30. ep.Path += "/info/lfs"
  31. } else {
  32. ep.Path += ".git/info/lfs"
  33. }
  34. return ep
  35. }
  36. func endpointFromURL(rawurl string) *url.URL {
  37. if strings.HasPrefix(rawurl, "/") {
  38. return endpointFromLocalPath(rawurl)
  39. }
  40. u, err := url.Parse(rawurl)
  41. if err != nil {
  42. log.Error("lfs.endpointFromUrl: %v", err)
  43. return nil
  44. }
  45. switch u.Scheme {
  46. case "http", "https":
  47. return u
  48. case "git":
  49. u.Scheme = "https"
  50. return u
  51. case "file":
  52. return u
  53. default:
  54. if _, err := os.Stat(rawurl); err == nil {
  55. return endpointFromLocalPath(rawurl)
  56. }
  57. log.Error("lfs.endpointFromUrl: unknown url")
  58. return nil
  59. }
  60. }
  61. func endpointFromLocalPath(path string) *url.URL {
  62. var slash string
  63. if abs, err := filepath.Abs(path); err == nil {
  64. if !strings.HasPrefix(abs, "/") {
  65. slash = "/"
  66. }
  67. path = abs
  68. }
  69. var gitpath string
  70. if filepath.Base(path) == ".git" {
  71. gitpath = path
  72. path = filepath.Dir(path)
  73. } else {
  74. gitpath = filepath.Join(path, ".git")
  75. }
  76. if _, err := os.Stat(gitpath); err == nil {
  77. path = gitpath
  78. } else if _, err := os.Stat(path); err != nil {
  79. return nil
  80. }
  81. path = "file://" + slash + util.PathEscapeSegments(filepath.ToSlash(path))
  82. u, _ := url.Parse(path)
  83. return u
  84. }