File: remote.go

package info (click to toggle)
tea-cli 0.9.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,364 kB
  • sloc: makefile: 120; sh: 17
file content (76 lines) | stat: -rw-r--r-- 1,942 bytes parent folder | download | duplicates (2)
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
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package git

import (
	"fmt"
	"net/url"

	"github.com/go-git/go-git/v5"
	git_config "github.com/go-git/go-git/v5/config"
)

// GetRemote tries to match a Remote of the repo via the given URL.
// Matching is based on the normalized URL, accepting different protocols.
func (r TeaRepo) GetRemote(remoteURL string) (*git.Remote, error) {
	repoURL, err := ParseURL(remoteURL)
	if err != nil {
		return nil, err
	}

	remotes, err := r.Remotes()
	if err != nil {
		return nil, err
	}
	for _, r := range remotes {
		for _, u := range r.Config().URLs {
			remoteURL, err := ParseURL(u)
			if err != nil {
				return nil, err
			}
			if remoteURL.Host == repoURL.Host && remoteURL.Path == repoURL.Path {
				return r, nil
			}
		}
	}

	return nil, nil
}

// GetOrCreateRemote tries to match a Remote of the repo via the given URL.
// If no match is found, a new Remote with `newRemoteName` is created.
// Matching is based on the normalized URL, accepting different protocols.
func (r TeaRepo) GetOrCreateRemote(remoteURL, newRemoteName string) (*git.Remote, error) {
	localRemote, err := r.GetRemote(remoteURL)
	if err != nil {
		return nil, err
	}

	// if no match found, create a new remote
	if localRemote == nil {
		localRemote, err = r.CreateRemote(&git_config.RemoteConfig{
			Name: newRemoteName,
			URLs: []string{remoteURL},
		})
		if err != nil {
			return nil, err
		}
	}

	return localRemote, nil
}

// TeaRemoteURL returns the first url entry for the given remote name
func (r TeaRepo) TeaRemoteURL(name string) (auth *url.URL, err error) {
	remote, err := r.Remote(name)
	if err != nil {
		return nil, err
	}
	urls := remote.Config().URLs
	if len(urls) == 0 {
		return nil, fmt.Errorf("remote %s has no URL configured", name)
	}
	return ParseURL(remote.Config().URLs[0])
}