github.com/ahmet2mir/goreleaser@v0.180.3-0.20210927151101-8e5ee5a9b8c5/internal/git/config.go (about)

     1  package git
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net/url"
     7  	"strings"
     8  
     9  	"github.com/goreleaser/goreleaser/pkg/config"
    10  )
    11  
    12  // ExtractRepoFromConfig gets the repo name from the Git config.
    13  func ExtractRepoFromConfig() (result config.Repo, err error) {
    14  	if !IsRepo() {
    15  		return result, errors.New("current folder is not a git repository")
    16  	}
    17  	out, err := Run("ls-remote", "--get-url")
    18  	if err != nil {
    19  		return result, fmt.Errorf("no remote configured to list refs from")
    20  	}
    21  	return ExtractRepoFromURL(out)
    22  }
    23  
    24  func ExtractRepoFromURL(rawurl string) (config.Repo, error) {
    25  	// removes the .git suffix and any new lines
    26  	s := strings.TrimSuffix(strings.TrimSpace(rawurl), ".git")
    27  
    28  	// if the URL contains a :, indicating a SSH config,
    29  	// remove all chars until it, including itself
    30  	// on HTTP and HTTPS URLs it will remove the http(s): prefix,
    31  	// which is ok. On SSH URLs the whole user@server will be removed,
    32  	// which is required.
    33  	s = s[strings.LastIndex(s, ":")+1:]
    34  
    35  	// now we can parse it with net/url
    36  	u, err := url.Parse(s)
    37  	if err != nil {
    38  		return config.Repo{}, err
    39  	}
    40  
    41  	// split the parsed url path by /, the last parts should be the owner and name
    42  	ss := strings.Split(strings.TrimPrefix(u.Path, "/"), "/")
    43  
    44  	// if less than 2 parts, its likely not a valid repository
    45  	if len(ss) < 2 {
    46  		return config.Repo{}, fmt.Errorf("unsupported repository URL: %s", rawurl)
    47  	}
    48  	return config.Repo{
    49  		Owner: strings.Join(ss[:len(ss)-1], "/"),
    50  		Name:  ss[len(ss)-1],
    51  	}, nil
    52  }