2020-07-09 22:40:37 +02:00
|
|
|
package git
|
2017-01-14 20:12:20 +02:00
|
|
|
|
|
|
|
import (
|
2020-09-21 19:47:51 +02:00
|
|
|
"errors"
|
2018-02-26 01:17:45 +02:00
|
|
|
"fmt"
|
2021-08-21 15:57:19 +02:00
|
|
|
"net/url"
|
2017-01-14 20:12:20 +02:00
|
|
|
"strings"
|
2017-03-23 02:01:29 +02:00
|
|
|
|
2018-08-15 04:50:20 +02:00
|
|
|
"github.com/goreleaser/goreleaser/pkg/config"
|
2017-01-14 20:12:20 +02:00
|
|
|
)
|
|
|
|
|
2020-07-09 22:40:37 +02:00
|
|
|
// ExtractRepoFromConfig gets the repo name from the Git config.
|
|
|
|
func ExtractRepoFromConfig() (result config.Repo, err error) {
|
|
|
|
if !IsRepo() {
|
2017-10-16 19:43:26 +02:00
|
|
|
return result, errors.New("current folder is not a git repository")
|
2017-10-15 21:46:21 +02:00
|
|
|
}
|
2020-07-09 22:40:37 +02:00
|
|
|
out, err := Run("config", "--get", "remote.origin.url")
|
2017-01-14 20:12:20 +02:00
|
|
|
if err != nil {
|
2018-02-26 01:17:45 +02:00
|
|
|
return result, fmt.Errorf("repository doesn't have an `origin` remote")
|
2017-01-14 20:12:20 +02:00
|
|
|
}
|
2021-08-21 15:57:19 +02:00
|
|
|
return ExtractRepoFromURL(out)
|
2017-01-14 20:12:20 +02:00
|
|
|
}
|
|
|
|
|
2021-08-21 15:57:19 +02:00
|
|
|
func ExtractRepoFromURL(rawurl string) (config.Repo, error) {
|
2018-02-20 23:21:20 +02:00
|
|
|
// removes the .git suffix and any new lines
|
2021-08-21 15:57:19 +02:00
|
|
|
s := strings.TrimSuffix(strings.TrimSpace(rawurl), ".git")
|
|
|
|
|
2018-02-20 23:21:20 +02:00
|
|
|
// if the URL contains a :, indicating a SSH config,
|
|
|
|
// remove all chars until it, including itself
|
|
|
|
// on HTTP and HTTPS URLs it will remove the http(s): prefix,
|
|
|
|
// which is ok. On SSH URLs the whole user@server will be removed,
|
|
|
|
// which is required.
|
|
|
|
s = s[strings.LastIndex(s, ":")+1:]
|
2021-08-21 15:57:19 +02:00
|
|
|
|
|
|
|
// now we can parse it with net/url
|
|
|
|
u, err := url.Parse(s)
|
|
|
|
if err != nil {
|
|
|
|
return config.Repo{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// split the parsed url path by /, the last two parts should be the owner and name
|
|
|
|
ss := strings.Split(strings.TrimPrefix(u.Path, "/"), "/")
|
|
|
|
|
|
|
|
// if less than 2 parts, its likely not a valid repository
|
|
|
|
if len(ss) < 2 {
|
|
|
|
return config.Repo{}, fmt.Errorf("unsupported repository URL: %s", rawurl)
|
|
|
|
}
|
2017-03-23 02:01:29 +02:00
|
|
|
return config.Repo{
|
2018-02-20 23:21:20 +02:00
|
|
|
Owner: ss[len(ss)-2],
|
|
|
|
Name: ss[len(ss)-1],
|
2021-08-21 15:57:19 +02:00
|
|
|
}, nil
|
2017-01-14 20:12:20 +02:00
|
|
|
}
|