aboutsummaryrefslogtreecommitdiffstats
path: root/modules/lfs/endpoint.go
blob: 3ae3cf077b2ca93d412f6b6752bea2ab2a8368f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package lfs

import (
	"fmt"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"strings"

	"code.gitea.io/gitea/modules/log"
)

// DetermineEndpoint determines an endpoint from the clone url or uses the specified LFS url.
func DetermineEndpoint(cloneurl, lfsurl string) *url.URL {
	if len(lfsurl) > 0 {
		return endpointFromURL(lfsurl)
	}
	return endpointFromCloneURL(cloneurl)
}

func endpointFromCloneURL(rawurl string) *url.URL {
	ep := endpointFromURL(rawurl)
	if ep == nil {
		return ep
	}

	ep.Path = strings.TrimSuffix(ep.Path, "/")

	if ep.Scheme == "file" {
		return ep
	}

	if path.Ext(ep.Path) == ".git" {
		ep.Path += "/info/lfs"
	} else {
		ep.Path += ".git/info/lfs"
	}

	return ep
}

func endpointFromURL(rawurl string) *url.URL {
	if strings.HasPrefix(rawurl, "/") {
		return endpointFromLocalPath(rawurl)
	}

	u, err := url.Parse(rawurl)
	if err != nil {
		log.Error("lfs.endpointFromUrl: %v", err)
		return nil
	}

	switch u.Scheme {
	case "http", "https":
		return u
	case "git":
		u.Scheme = "https"
		return u
	case "file":
		return u
	default:
		if _, err := os.Stat(rawurl); err == nil {
			return endpointFromLocalPath(rawurl)
		}

		log.Error("lfs.endpointFromUrl: unknown url")
		return nil
	}
}

func endpointFromLocalPath(path string) *url.URL {
	var slash string
	if abs, err := filepath.Abs(path); err == nil {
		if !strings.HasPrefix(abs, "/") {
			slash = "/"
		}
		path = abs
	}

	var gitpath string
	if filepath.Base(path) == ".git" {
		gitpath = path
		path = filepath.Dir(path)
	} else {
		gitpath = filepath.Join(path, ".git")
	}

	if _, err := os.Stat(gitpath); err == nil {
		path = gitpath
	} else if _, err := os.Stat(path); err != nil {
		return nil
	}

	path = fmt.Sprintf("file://%s%s", slash, filepath.ToSlash(path))

	u, _ := url.Parse(path)

	return u
}