Skip to content
quarry Artifact [e56675a2f0]
Login

Artifact [e56675a2f0]

Artifact e56675a2f0fb5ef80b615285d92754426d1a6489af9266cebd06b29223d6389a:


package pickupclient

import (
	"context"
	"errors"
	"net/url"
	"regexp"
	"strings"
)

// The one place a checkout's remote becomes a repository. A remote names
// its repository as /r/KEY (the flat form) or /r/NAMESPACE/HANDLE. Each
// segment is held to the strict set below; the forge's key, the one every
// /api/v1/r/{repo} route takes, comes from the remote when it is flat and
// from repo.get when it is not.

var repoSegment = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]*$`)

var (
	// errNotRepoRemote: the remote is not a repository's address at all.
	errNotRepoRemote = errors.New("the remote is not a repository of the forge")
	// errBadRepoSegment: it is, but a segment holds characters a name may not.
	errBadRepoSegment = errors.New("the remote names a repository with characters a name may not have")
	// errNoSuchRepo: the forge has no such repository.
	errNoSuchRepo = errors.New("the forge has no such repository")
)

// repoRef is a resolved repository: the key API paths take and the
// address a person is shown.
type repoRef struct {
	Key     string
	Address string
}

// remoteSegments reads the repository segments of a checkout's remote.
func remoteSegments(remote *url.URL) ([]string, error) {
	if remote == nil {
		return nil, errNotRepoRemote
	}
	rest, ok := strings.CutPrefix(remote.EscapedPath(), "/r/")
	if !ok {
		return nil, errNotRepoRemote
	}
	segs := strings.Split(strings.Trim(rest, "/"), "/")
	if len(segs) < 1 || len(segs) > 2 || segs[0] == "" {
		return nil, errNotRepoRemote
	}
	for _, s := range segs {
		if !repoSegment.MatchString(s) {
			return nil, errBadRepoSegment
		}
	}
	return segs, nil
}

// repoInfo is the part of repo.get the client reads.
type repoInfo struct {
	Name      string `json:"name"`
	Handle    string `json:"handle"`
	Namespace string `json:"namespace"`
	Address   string `json:"address"`
}

// resolveRepo turns the segments into a key. wantAddress forces the
// repo.get call for a flat remote too, to learn the address.
func (e *Env) resolveRepo(ctx context.Context, base *url.URL, token string, segs []string, wantAddress bool) (repoRef, error) {
	if len(segs) == 1 && !wantAddress {
		return repoRef{Key: segs[0], Address: segs[0]}, nil
	}
	var info repoInfo
	err := e.getJSON(ctx, base, token, "/r/"+strings.Join(segs, "/")+"/info", nil, &info)
	var se statusError
	switch {
	case errors.As(err, &se) && se == 404:
		return repoRef{}, errNoSuchRepo
	case err != nil:
		return repoRef{}, err
	}
	if !repoSegment.MatchString(info.Name) {
		return repoRef{}, errNoSuchRepo
	}
	if info.Address == "" {
		info.Address = info.Name
	}
	return repoRef{Key: info.Name, Address: info.Address}, nil
}