package api
import (
"context"
"fmt"
"reflect"
"strings"
"craftdesign.group/quarry/internal/ops"
)
// canonRepo is the repository key a name stands for. URLs name a
// repository OWNER/NAME (RFC 0025) while the forge keys it by the bare
// key, and a token or grant that kept the URL's spelling reached
// nothing. A key is itself; OWNER/NAME is the key at that address; any
// other name is left as given, for the caller's own checks to refuse.
// It maps spellings only: whether the caller may read the repository is
// asked after, by whoever needs the answer.
func (d Deps) canonRepo(name string) string {
name = strings.TrimSpace(name)
i := strings.Index(name, "/")
if i <= 0 || i == len(name)-1 || d.Repos == nil {
return name
}
if _, ok := d.Repos.Get(name); ok {
return name
}
ns, handle := name[:i], name[i+1:]
if d.AddressBook != nil {
for key, a := range d.AddressBook() {
if a[0] == ns && a[1] == handle {
return key
}
}
return name
}
if d.Address != nil {
for _, key := range d.Repos.Names() {
if n, h, ok := d.Address(key); ok && n == ns && h == handle {
return key
}
}
}
return name
}
// canonRepoAs is canonRepo for an asker: an address is rewritten to its
// key only when the asker can read that repository. Otherwise the name
// stays as sent, so a private repository and a missing one look alike
// and a key is never handed to somebody who may not read the repository.
func (d Deps) canonRepoAs(ctx context.Context, name string) string {
key := d.canonRepo(name)
if key != strings.TrimSpace(name) && d.CanRead != nil && !d.CanRead(ctx, key) {
return name
}
return key
}
// repoKeys resolves the repositories a token or grant is to name, each
// as OWNER/NAME or NAME, to their keys, in order and without repeats.
// A name that is no repository, one the caller cannot read, or one still
// registering is refused alike, with the words a missing repository
// gets, so asking cannot probe for private ones or for startup state.
func (d Deps) repoKeys(ctx context.Context, names []string) ([]string, error) {
out := make([]string, 0, len(names))
seen := map[string]bool{}
for _, n := range names {
key := d.canonRepo(n)
if _, err := d.repoFor(ctx, key); err != nil {
return nil, fmt.Errorf("no repository %q: %w", strings.TrimSpace(n), ops.ErrInvalid)
}
if !seen[key] {
seen[key] = true
out = append(out, key)
}
}
return out, nil
}
// repoOps are the commands that name repositories for a token or a
// grant, and so take OWNER/NAME as well as NAME.
func repoOp(op string) bool {
switch op {
case "agent.token.new", "agent.token.repos", "agent.grant", setupOp:
return true
}
return false
}
// mapRepos is an op's input with every repository it names passed
// through fn, as a copy: the caller's value and slices are untouched.
// Names fn leaves as they were stay byte for byte.
func mapRepos(op string, in any, fn func(string) string) any {
if !repoOp(op) {
return in
}
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return in
}
c := reflect.New(v.Type()).Elem()
c.Set(v)
if f := c.FieldByName("NewRepo"); f.IsValid() && f.Kind() == reflect.Bool && f.Bool() {
return in
}
if f := c.FieldByName("Repos"); f.IsValid() && f.Kind() == reflect.String {
parts := splitList(f.String())
changed := false
for i := range parts {
if key := fn(parts[i]); key != parts[i] {
parts[i], changed = key, true
}
}
if changed {
f.SetString(strings.Join(parts, ","))
}
}
if f := c.FieldByName("Repositories"); f.IsValid() && f.Kind() == reflect.Slice && f.Type().Elem().Kind() == reflect.String {
cp := reflect.MakeSlice(f.Type(), f.Len(), f.Len())
for i := 0; i < f.Len(); i++ {
cp.Index(i).SetString(fn(f.Index(i).String()))
}
f.Set(cp)
}
if f := c.FieldByName("Repo"); f.IsValid() && f.Kind() == reflect.String {
f.SetString(fn(f.String()))
}
if v.Type() == reflect.TypeOf(in) {
return c.Interface()
}
p := reflect.New(v.Type())
p.Elem().Set(c)
return p.Interface()
}
// canonAsked is an asked call's input with its repositories spelled as
// keys, each only where the asker can read the repository.
func (d Deps) canonAsked(ctx context.Context, op string, in any) any {
return mapRepos(op, in, func(n string) string { return d.canonRepoAs(ctx, n) })
}
// labelled is the same input with each key as the address a person
// knows it by, for the sentence they are asked to approve.
func (d Deps) labelled(op string, in any) any {
return mapRepos(op, in, d.repoLabel)
}
// repoField is the field repoOf reads: Repo, else Name.
func repoField(in any) string {
for _, name := range []string{"Repo", "Name"} {
if inputField(in, name) != "" {
return name
}
}
return ""
}
// withRepo is in with the field repoOf reads set to key, as a copy.
func withRepo(in any, key string) any {
field := repoField(in)
v := reflect.ValueOf(in)
if field == "" || v.Kind() != reflect.Struct {
return in
}
c := reflect.New(v.Type()).Elem()
c.Set(v)
c.FieldByName(field).SetString(key)
return c.Interface()
}
// canonAll is canonRepo over a list.
func (d Deps) canonAll(names []string) []string {
out := make([]string, len(names))
for i, n := range names {
out[i] = d.canonRepo(n)
}
return out
}