~bigbes/core-go

39c3fd1e41e30cc8ab4e8469248c9309eaa6a937 — Conrad Hoffmann 9 months ago 3afc1a5
Run modernize

See https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize

It's mostly interface{} -> any, but also two quite useful applications
of slices.Contains.
M auth/middleware.go => auth/middleware.go +2 -2
@@ 440,7 440,7 @@ func LookupUser(ctx context.Context, username string, user *AuthContext) error {
			}
			return FetchMetaProfile(ctx, username, user)
		}
		cols := []interface{}{
		cols := []any{
			&user.UserID, &user.Username,
			&user.Created, &user.Updated,
			&user.Email,


@@ 476,7 476,7 @@ func LookupTokenRevocation(ctx context.Context,
			query RevocationStatus($hash: String!, $clientId: String) {
				tokenRevocationStatus(hash: $hash, clientId: $clientId)
			}`,
		Variables: map[string]interface{}{
		Variables: map[string]any{
			"hash":     hex.EncodeToString(hash[:]),
			"clientId": clientID,
		},

M client/graphql.go => client/graphql.go +3 -3
@@ 20,7 20,7 @@ import (

type GraphQLQuery struct {
	Query     string                    `json:"query"`
	Variables map[string]interface{}    `json:"variables"`
	Variables map[string]any            `json:"variables"`
	Uploads   map[string]graphql.Upload `json:"-"`
}



@@ 31,7 31,7 @@ type InternalAuth struct {
}

func Do(ctx context.Context, username string, svc string,
	query GraphQLQuery, result interface{},
	query GraphQLQuery, result any,
) error {
	conf := config.ForContext(ctx)
	origin := config.GetAPI(conf, svc, false)


@@ 159,7 159,7 @@ func Do(ctx context.Context, username string, svc string,
	}

	var respData struct {
		Data   interface{}   `json:"data"`
		Data   any           `json:"data"`
		Errors gqlerror.List `json:"errors"`
	}
	respData.Data = result

M database/ql.go => database/ql.go +2 -2
@@ 30,7 30,7 @@ func collectFields(ctx context.Context) []graphql.CollectedField {
	return fields
}

func Scan(ctx context.Context, m Model) []interface{} {
func Scan(ctx context.Context, m Model) []any {
	qlFields := collectFields(ctx)
	if len(qlFields) == 0 {
		// Collect all fields if we are not in an active graphql context


@@ 45,7 45,7 @@ func Scan(ctx context.Context, m Model) []interface{} {
		return qlFields[a].Name < qlFields[b].Name
	})

	var fields []interface{}
	var fields []any
	for _, qlField := range qlFields {
		if gqlFields, ok := m.Fields().GQL(qlField.Name); ok {
			for _, field := range gqlFields {

M database/sq.go => database/sq.go +4 -4
@@ 13,7 13,7 @@ import (
type FieldMap struct {
	SQL string
	GQL string
	Ptr interface{}
	Ptr any
}

type ModelFields struct {


@@ 85,7 85,7 @@ type ExtendedModel interface {
	Select(q sq.SelectBuilder) sq.SelectBuilder
}

func Select(ctx context.Context, cols ...interface{}) sq.SelectBuilder {
func Select(ctx context.Context, cols ...any) sq.SelectBuilder {
	q := sq.Select().PlaceholderFormat(sq.Dollar)
	for _, col := range cols {
		switch col := col.(type) {


@@ 120,13 120,13 @@ func SelectAll(m Model) sq.SelectBuilder {
	return q.Columns(cols...)
}

func ScanAll(m Model) []interface{} {
func ScanAll(m Model) []any {
	fms := m.Fields().All()
	sort.Slice(fms, func(a, b int) bool {
		return fms[a].SQL < fms[b].SQL
	})

	var fields []interface{}
	var fields []any
	for _, f := range fms {
		if f.SQL != "" {
			fields = append(fields, f.Ptr)

M feature/header.go => feature/header.go +2 -6
@@ 3,6 3,7 @@ package feature
import (
	"context"
	"net/http"
	"slices"
	"strings"
)



@@ 39,10 40,5 @@ func ForContext(ctx context.Context) []string {
// Returns true if the requested feature is enabled via the Accept-Features
// HTTP header
func Enabled(ctx context.Context, name string) bool {
	for _, feat := range ForContext(ctx) {
		if feat == name {
			return true
		}
	}
	return false
	return slices.Contains(ForContext(ctx), name)
}

M model/cursor.go => model/cursor.go +1 -1
@@ 15,7 15,7 @@ type Cursor struct {
	Search string `json:"search"`
}

func (cur *Cursor) UnmarshalGQL(v interface{}) error {
func (cur *Cursor) UnmarshalGQL(v any) error {
	enc, ok := v.(string)
	if !ok {
		return fmt.Errorf("cursor must be strings")

M model/id.go => model/id.go +2 -2
@@ 39,10 39,10 @@ func (id *ID) String() string {
}

func (id ID) MarshalGQL(w io.Writer) {
	w.Write([]byte(fmt.Sprintf(`"%s"`, id.String())))
	w.Write(fmt.Appendf(nil, `"%s"`, id.String()))
}

func (id *ID) UnmarshalGQL(v interface{}) error {
func (id *ID) UnmarshalGQL(v any) error {
	switch v := v.(type) {
	case string:
		bytes, err := base32Encoding.DecodeString(v)

M server/directives.go => server/directives.go +10 -10
@@ 9,8 9,8 @@ import (
	"git.sr.ht/~sircmpwn/core-go/auth"
)

func Admin(ctx context.Context, obj interface{},
	next graphql.Resolver) (interface{}, error) {
func Admin(ctx context.Context, obj any,
	next graphql.Resolver) (any, error) {

	if auth.ForContext(ctx).UserType != auth.USER_TYPE_ADMIN {
		return nil, fmt.Errorf("Access denied")


@@ 19,8 19,8 @@ func Admin(ctx context.Context, obj interface{},
	return next(ctx)
}

func AnonInternal(ctx context.Context, obj interface{},
	next graphql.Resolver) (interface{}, error) {
func AnonInternal(ctx context.Context, obj any,
	next graphql.Resolver) (any, error) {

	if auth.ForContext(ctx).AuthMethod != auth.AUTH_ANON_INTERNAL {
		return nil, fmt.Errorf("Anonymous internal auth access denied")


@@ 29,8 29,8 @@ func AnonInternal(ctx context.Context, obj interface{},
	return next(ctx)
}

func Internal(ctx context.Context, obj interface{},
	next graphql.Resolver) (interface{}, error) {
func Internal(ctx context.Context, obj any,
	next graphql.Resolver) (any, error) {

	if auth.ForContext(ctx).AuthMethod != auth.AUTH_INTERNAL {
		return nil, fmt.Errorf("Internal auth access denied")


@@ 39,8 39,8 @@ func Internal(ctx context.Context, obj interface{},
	return next(ctx)
}

func Private(ctx context.Context, obj interface{},
	next graphql.Resolver) (interface{}, error) {
func Private(ctx context.Context, obj any,
	next graphql.Resolver) (any, error) {

	user := auth.ForContext(ctx)
	switch user.AuthMethod {


@@ 56,8 56,8 @@ func Private(ctx context.Context, obj interface{},
	return nil, fmt.Errorf("Private auth access denied")
}

func Access(ctx context.Context, obj interface{}, next graphql.Resolver,
	scope string, kind string) (interface{}, error) {
func Access(ctx context.Context, obj any, next graphql.Resolver,
	scope string, kind string) (any, error) {

	if err := auth.ForContext(ctx).Access(scope, kind); err != nil {
		return nil, err

M server/email.go => server/email.go +1 -1
@@ 20,7 20,7 @@ import (

// Provides a graphql.RecoverFunc which will print the stack trace, and if
// debug mode is not enabled, email it to the administrator.
func EmailRecover(ctx context.Context, _origErr interface{}) error {
func EmailRecover(ctx context.Context, _origErr any) error {
	origErr, ok := _origErr.(error)
	if !ok {
		log.Printf("Unexpected error in recover: %v\n", _origErr)

M valid/valid.go => valid/valid.go +10 -10
@@ 10,7 10,7 @@ import (

type Validation struct {
	ctx   context.Context
	input map[string]interface{}
	input map[string]any
}

type ValidationError struct {


@@ 23,18 23,18 @@ func Error(ctx context.Context, field string, msg string) error {
	return &gqlerror.Error{
		Message: msg,
		Path:    graphql.GetPath(ctx),
		Extensions: map[string]interface{}{
		Extensions: map[string]any{
			"field": field,
		},
	}
}

// Returns a new GraphQL error attached to the given field.
func Errorf(ctx context.Context, field string, msg string, items ...interface{}) error {
func Errorf(ctx context.Context, field string, msg string, items ...any) error {
	return &gqlerror.Error{
		Message: fmt.Sprintf(msg, items...),
		Path:    graphql.GetPath(ctx),
		Extensions: map[string]interface{}{
		Extensions: map[string]any{
			"field": field,
		},
	}


@@ 48,7 48,7 @@ func New(ctx context.Context) *Validation {
}

// Adds an input map to a validation context.
func (valid *Validation) WithInput(input map[string]interface{}) *Validation {
func (valid *Validation) WithInput(input map[string]any) *Validation {
	valid.input = input
	return valid
}


@@ 62,7 62,7 @@ func (valid *Validation) Ok() bool {
// registered. If the field is not present, the callback is not run. Otherwise,
// the function is called with the value for the user to conduct further
// validation with.
func (valid *Validation) Optional(name string, fn func(i interface{})) {
func (valid *Validation) Optional(name string, fn func(i any)) {
	if valid.input == nil {
		panic(fmt.Errorf("Attempted to validate fields without input"))
	}


@@ 160,7 160,7 @@ func (valid *Validation) OptionalBool(name string, fn func(b bool)) {

// Creates a validation error unconditionally.
func (valid *Validation) Error(msg string,
	items ...interface{}) *ValidationError {
	items ...any) *ValidationError {
	err := &gqlerror.Error{
		Path:    graphql.GetPath(valid.ctx),
		Message: fmt.Sprintf(msg, items...),


@@ 175,7 175,7 @@ func (valid *Validation) Error(msg string,
// Asserts that a condition is true, recording a GraphQL error with the given
// message if not.
func (valid *Validation) Expect(cond bool,
	msg string, items ...interface{}) *ValidationError {
	msg string, items ...any) *ValidationError {
	if cond {
		return &ValidationError{valid: valid}
	}


@@ 188,7 188,7 @@ func (err *ValidationError) WithField(field string) *ValidationError {
		return err
	}
	if err.err.Extensions == nil {
		err.err.Extensions = make(map[string]interface{})
		err.err.Extensions = make(map[string]any)
	}
	err.err.Extensions["field"] = field
	return err


@@ 198,7 198,7 @@ func (err *ValidationError) WithField(field string) *ValidationError {
// created an error. Short-circuiting is used, such that if the earlier
// condition failed, the new condition is not considered.
func (err *ValidationError) And(cond bool,
	msg string, items ...interface{}) *ValidationError {
	msg string, items ...any) *ValidationError {
	if err.err != nil {
		return err
	}

M webhooks/context.go => webhooks/context.go +3 -3
@@ 26,18 26,18 @@ type WebhookContext struct {
	Name         string
	Event        string
	User         *auth.AuthContext
	Payload      interface{}
	Payload      any
	PayloadUUID  uuid.UUID
	Subscription *WebhookSubscription
}

// Prepares an context for a specific webhook delivery.
func Context(ctx context.Context, payload interface{}) context.Context {
func Context(ctx context.Context, payload any) context.Context {
	return context.WithValue(ctx, payloadContextKey, payload)
}

// Returns the active payload for a webhook context.
func Payload(ctx context.Context) (interface{}, error) {
func Payload(ctx context.Context) (any, error) {
	payload := ctx.Value(payloadContextKey)
	if payload == nil {
		return nil, errors.New("Cannot use this resolver without an active webhook context")

M webhooks/legacy.go => webhooks/legacy.go +3 -5
@@ 9,6 9,7 @@ import (
	"io/ioutil"
	"log"
	"net/http"
	"slices"
	"strings"
	"time"



@@ 134,11 135,8 @@ func fetchSubscriptions(ctx context.Context, q sq.SelectBuilder,
			sub.Events = strings.Split(events, ",")

			var valid bool
			for _, e := range sub.Events {
				if e == event {
					valid = true
					break
				}
			if slices.Contains(sub.Events, event) {
				valid = true
			}

			if valid {

M webhooks/queue.go => webhooks/queue.go +2 -2
@@ 65,7 65,7 @@ func NewQueue(schema graphql.ExecutableSchema, conf ini.File) *WebhookQueue {
// context which contains the necessary state for your application to process
// the webhook resolvers.
func (queue *WebhookQueue) Schedule(ctx context.Context, q sq.SelectBuilder,
	name, event string, payloadUUID uuid.UUID, payload interface{}) {
	name, event string, payloadUUID uuid.UUID, payload any) {
	err := queue.schedule(ctx, q, name, event, payloadUUID, payload)
	if err != nil {
		log.Printf("Failed to enqueue webhook deliveries: %v", err)


@@ 73,7 73,7 @@ func (queue *WebhookQueue) Schedule(ctx context.Context, q sq.SelectBuilder,
}

func (queue *WebhookQueue) schedule(ctx context.Context, q sq.SelectBuilder,
	name, event string, payloadUUID uuid.UUID, payload interface{}) error {
	name, event string, payloadUUID uuid.UUID, payload any) error {
	// The following tasks are done during this process:
	//
	// 1. Fetch subscription details from the database