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.

endpoint.go 1.9KB

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