formatting

This commit is contained in:
Hayden 2023-02-17 18:51:11 -09:00
parent 6532ea44a5
commit bd058be1fb
No known key found for this signature in database
GPG key ID: 17CF79474E257545
44 changed files with 20 additions and 95 deletions

View file

@ -49,7 +49,6 @@ func (ctrl *V1Controller) HandleAssetGet() server.HandlerFunc {
return server.Respond(w, http.StatusBadRequest, "Invalid page size")
}
}
items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GID, repo.AssetID(assetId), int(page), int(pageSize))
if err != nil {

View file

@ -50,7 +50,6 @@ func (ctrl *V1Controller) HandleAuthLogin() server.HandlerFunc {
loginForm.Password = r.PostFormValue("password")
case server.ContentJSON:
err := server.Decode(r, loginForm)
if err != nil {
log.Err(err).Msg("failed to decode login form")
}
@ -72,7 +71,6 @@ func (ctrl *V1Controller) HandleAuthLogin() server.HandlerFunc {
}
newToken, err := ctrl.svc.User.Login(r.Context(), strings.ToLower(loginForm.Username), loginForm.Password)
if err != nil {
return validate.NewRequestError(errors.New("authentication failed"), http.StatusInternalServerError)
}

View file

@ -26,7 +26,6 @@ import (
// @Router /v1/items [GET]
// @Security Bearer
func (ctrl *V1Controller) HandleItemsGetAll() server.HandlerFunc {
extractQuery := func(r *http.Request) repo.ItemQuery {
params := r.URL.Query()
@ -244,7 +243,6 @@ func (ctrl *V1Controller) HandleGetAllCustomFieldValues() server.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleItemsImport() server.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
if err != nil {
log.Err(err).Msg("failed to parse multipart form")

View file

@ -82,7 +82,6 @@ func (ctrl *V1Controller) HandleItemAttachmentCreate() server.HandlerFunc {
attachment.Type(attachmentType),
file,
)
if err != nil {
log.Err(err).Msg("failed to add attachment")
return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -34,7 +34,6 @@ func (ctrl *V1Controller) HandleLocationTreeQuery() server.HandlerFunc {
WithItems: withItems,
},
)
if err != nil {
log.Err(err).Msg("failed to get locations tree")
return validate.NewRequestError(err, http.StatusInternalServerError)

View file

@ -80,7 +80,6 @@ func (ctrl *V1Controller) HandleUserSelfUpdate() server.HandlerFunc {
actor := services.UseUserCtx(r.Context())
newData, err := ctrl.svc.User.UpdateSelf(r.Context(), actor.ID, updateData)
if err != nil {
return validate.NewRequestError(err, http.StatusInternalServerError)
}

View file

@ -57,7 +57,7 @@ func run(cfg *config.Config) error {
// =========================================================================
// Initialize Database & Repos
err := os.MkdirAll(cfg.Storage.Data, 0755)
err := os.MkdirAll(cfg.Storage.Data, 0o755)
if err != nil {
log.Fatal().Err(err).Msg("failed to create data directory")
}

View file

@ -15,9 +15,7 @@ type tokenHasKey struct {
key string
}
var (
hashedToken = tokenHasKey{key: "hashedToken"}
)
var hashedToken = tokenHasKey{key: "hashedToken"}
type RoleMode int

View file

@ -58,5 +58,4 @@ func TestItemService_AddAttachment(t *testing.T) {
bts, err := os.ReadFile(storedPath)
assert.NoError(t, err)
assert.Equal(t, contents, string(bts))
}

View file

@ -139,7 +139,6 @@ func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data repo.
// User Authentication
func (svc *UserService) createSessionToken(ctx context.Context, userId uuid.UUID) (UserAuthTokenDetail, error) {
attachmentToken := hasher.GenerateToken()
attachmentData := repo.UserAuthTokenCreate{
UserID: userId,
@ -173,7 +172,6 @@ func (svc *UserService) createSessionToken(ctx context.Context, userId uuid.UUID
func (svc *UserService) Login(ctx context.Context, username, password string) (UserAuthTokenDetail, error) {
usr, err := svc.repos.Users.GetOneEmail(ctx, username)
if err != nil {
// SECURITY: Perform hash to ensure response times are the same
hasher.CheckPasswordHash("not-a-real-password", "not-a-real-password")
@ -197,7 +195,6 @@ func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthT
hash := hasher.HashToken(token)
dbToken, err := svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
if err != nil {
return UserAuthTokenDetail{}, ErrorInvalidToken
}

View file

@ -13,7 +13,7 @@ var Files embed.FS
// It returns an error and a cleanup function. The cleanup function
// should be called when the migrations are no longer needed.
func Write(temp string) error {
err := os.MkdirAll(temp, 0755)
err := os.MkdirAll(temp, 0o755)
if err != nil {
return err
}
@ -33,7 +33,7 @@ func Write(temp string) error {
return err
}
err = os.WriteFile(filepath.Join(temp, f.Name()), b, 0644)
err = os.WriteFile(filepath.Join(temp, f.Name()), b, 0o644)
if err != nil {
return err
}

View file

@ -14,9 +14,7 @@ import (
"github.com/hay-kot/homebox/backend/pkgs/pathlib"
)
var (
ErrInvalidDocExtension = errors.New("invalid document extension")
)
var ErrInvalidDocExtension = errors.New("invalid document extension")
type DocumentRepository struct {
db *ent.Client
@ -74,7 +72,7 @@ func (r *DocumentRepository) Create(ctx context.Context, gid uuid.UUID, doc Docu
path := r.path(gid, ext)
parent := filepath.Dir(path)
err := os.MkdirAll(parent, 0755)
err := os.MkdirAll(parent, 0o755)
if err != nil {
return DocumentOut{}, err
}

View file

@ -34,7 +34,6 @@ func useDocs(t *testing.T, num int) []DocumentOut {
t.Cleanup(func() {
for _, id := range ids {
err := tRepos.Docs.Delete(context.Background(), id)
if err != nil {
assert.True(t, ent.IsNotFound(err))
}

View file

@ -76,9 +76,7 @@ type (
}
)
var (
mapToGroupErr = mapTErrFunc(mapToGroup)
)
var mapToGroupErr = mapTErrFunc(mapToGroup)
func mapToGroup(g *ent.Group) Group {
return Group{
@ -90,9 +88,7 @@ func mapToGroup(g *ent.Group) Group {
}
}
var (
mapToGroupInvitationErr = mapTErrFunc(mapToGroupInvitation)
)
var mapToGroupInvitationErr = mapTErrFunc(mapToGroupInvitation)
func mapToGroupInvitation(g *ent.GroupInvitationToken) GroupInvitation {
return GroupInvitation{
@ -118,7 +114,6 @@ func (r *GroupRepository) StatsLocationsByPurchasePrice(ctx context.Context, GID
return sql.As(sql.Sum(t.C(item.FieldPurchasePrice)), "total")
}).
Scan(ctx, &v)
if err != nil {
return nil, err
}
@ -145,7 +140,6 @@ func (r *GroupRepository) StatsLabelsByPurchasePrice(ctx context.Context, GID uu
return sql.As(sql.Sum(itemTable.C(item.FieldPurchasePrice)), "total")
}).
Scan(ctx, &v)
if err != nil {
return nil, err
}
@ -283,7 +277,6 @@ func (r *GroupRepository) InvitationCreate(ctx context.Context, groupID uuid.UUI
SetExpiresAt(invite.ExpiresAt).
SetUses(invite.Uses).
Save(ctx)
if err != nil {
return GroupInvitation{}, err
}

View file

@ -68,7 +68,6 @@ func (r *AttachmentRepo) Update(ctx context.Context, itemId uuid.UUID, typ attac
itm, err := r.db.Attachment.UpdateOneID(itemId).
SetType(typ).
Save(ctx)
if err != nil {
return nil, err
}

View file

@ -58,7 +58,6 @@ func TestAttachmentRepo_Create(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tRepos.Attachments.Create(tt.args.ctx, tt.args.itemId, tt.args.docId, tt.args.typ)
if (err != nil) != tt.wantErr {
t.Errorf("AttachmentRepo.Create() error = %v, wantErr %v", err, tt.wantErr)
@ -119,7 +118,6 @@ func TestAttachmentRepo_Update(t *testing.T) {
assert.Equal(t, typ, updated.Type)
})
}
}
func TestAttachmentRepo_Delete(t *testing.T) {

View file

@ -150,9 +150,7 @@ type (
}
)
var (
mapItemsSummaryErr = mapTEachErrFunc(mapItemSummary)
)
var mapItemsSummaryErr = mapTEachErrFunc(mapItemSummary)
func mapItemSummary(item *ent.Item) ItemSummary {
var location *LocationSummary
@ -371,7 +369,6 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
}
count, err := qb.Count(ctx)
if err != nil {
return PaginationResult[ItemSummary]{}, err
}
@ -387,7 +384,6 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
}
items, err := mapItemsSummaryErr(qb.All(ctx))
if err != nil {
return PaginationResult[ItemSummary]{}, err
}
@ -398,7 +394,6 @@ func (e *ItemsRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q Ite
Total: count,
Items: items,
}, nil
}
// QueryByAssetID returns items by asset ID. If the item does not exist, an error is returned.
@ -422,7 +417,6 @@ func (e *ItemsRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, ass
WithLocation().
All(ctx),
)
if err != nil {
return PaginationResult[ItemSummary]{}, err
}
@ -441,6 +435,7 @@ func (e *ItemsRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]ItemOut,
Where(item.HasGroupWith(group.ID(gid))).
WithLabel().
WithLocation().
WithFields().
All(ctx))
}
@ -651,7 +646,6 @@ func (e *ItemsRepository) GetAllCustomFieldValues(ctx context.Context, GID uuid.
Unique(true).
Select(itemfield.FieldTextValue).
Scan(ctx, &values)
if err != nil {
return nil, fmt.Errorf("failed to get field values: %w", err)
}
@ -679,7 +673,6 @@ func (e *ItemsRepository) GetAllCustomFieldNames(ctx context.Context, GID uuid.U
Unique(true).
Select(itemfield.FieldName).
Scan(ctx, &fields)
if err != nil {
return nil, fmt.Errorf("failed to get custom fields: %w", err)
}

View file

@ -125,7 +125,6 @@ func TestItemsRepository_Create(t *testing.T) {
// Cleanup - Also deletes item
err = tRepos.Locations.Delete(context.Background(), location.ID)
assert.NoError(t, err)
}
func TestItemsRepository_Create_Location(t *testing.T) {
@ -222,7 +221,6 @@ func TestItemsRepository_Update_Labels(t *testing.T) {
}
})
}
}
func TestItemsRepository_Update(t *testing.T) {

View file

@ -100,7 +100,6 @@ func (r *LabelRepository) Create(ctx context.Context, groupdId uuid.UUID, data L
SetColor(data.Color).
SetGroupID(groupdId).
Save(ctx)
if err != nil {
return LabelOut{}, err
}

View file

@ -62,9 +62,7 @@ func mapLocationSummary(location *ent.Location) LocationSummary {
}
}
var (
mapLocationOutErr = mapTErrFunc(mapLocationOut)
)
var mapLocationOutErr = mapTErrFunc(mapLocationOut)
func mapLocationOut(location *ent.Location) LocationOut {
var parent *LocationSummary
@ -181,7 +179,6 @@ func (r *LocationRepository) Create(ctx context.Context, GID uuid.UUID, data Loc
}
location, err := q.Save(ctx)
if err != nil {
return LocationOut{}, err
}
@ -322,7 +319,7 @@ func (lr *LocationRepository) Tree(ctx context.Context, GID uuid.UUID, tq TreeQu
}
func ConvertLocationsToTree(locations []FlatTreeItem) []TreeItem {
var locationMap = make(map[uuid.UUID]*TreeItem, len(locations))
locationMap := make(map[uuid.UUID]*TreeItem, len(locations))
var rootIds []uuid.UUID

View file

@ -31,7 +31,6 @@ func useLocations(t *testing.T, len int) []LocationOut {
t.Cleanup(func() {
for _, loc := range out {
err := tRepos.Locations.Delete(context.Background(), loc.ID)
if err != nil {
assert.True(t, ent.IsNotFound(err))
}
@ -74,7 +73,6 @@ func TestLocationRepositoryGetAllWithCount(t *testing.T) {
assert.Equal(t, 1, loc.ItemCount)
}
}
}
func TestLocationRepository_Create(t *testing.T) {

View file

@ -93,7 +93,6 @@ func (r *MaintenanceEntryRepository) GetLog(ctx context.Context, itemID uuid.UUI
Where(maintenanceentry.ItemID(itemID)).
Order(ent.Desc(maintenanceentry.FieldDate)).
All(ctx)
if err != nil {
return MaintenanceLog{}, err
}

View file

@ -61,7 +61,6 @@ func TestMaintenanceEntryRepository_GetLog(t *testing.T) {
// Get the log for the item
log, err := tRepos.MaintEntry.GetLog(context.Background(), item.ID)
if err != nil {
t.Fatalf("failed to get maintenance log: %v", err)
}

View file

@ -42,7 +42,6 @@ func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (U
QueryUser().
WithGroup().
Only(ctx)
if err != nil {
return UserOut{}, err
}
@ -59,7 +58,6 @@ func (r *TokenRepository) GetRoles(ctx context.Context, token string) (*set.Set[
authtokens.Token(tokenHash),
)).
All(ctx)
if err != nil {
return nil, err
}
@ -80,7 +78,6 @@ func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthT
SetUserID(createToken.UserID).
SetExpiresAt(createToken.ExpiresAt).
Save(ctx)
if err != nil {
return UserAuthToken{}, err
}
@ -90,7 +87,6 @@ func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthT
SetRole(role).
SetToken(dbToken).
Save(ctx)
if err != nil {
return UserAuthToken{}, err
}
@ -115,7 +111,6 @@ func (r *TokenRepository) DeleteToken(ctx context.Context, token []byte) error {
// PurgeExpiredTokens removes all expired tokens from the database
func (r *TokenRepository) PurgeExpiredTokens(ctx context.Context) (int, error) {
tokensDeleted, err := r.db.AuthTokens.Delete().Where(authtokens.ExpiresAtLTE(time.Now())).Exec(ctx)
if err != nil {
return 0, err
}

View file

@ -123,7 +123,6 @@ func (e *UserRepository) DeleteAll(ctx context.Context) error {
func (e *UserRepository) GetSuperusers(ctx context.Context) ([]*ent.User, error) {
users, err := e.db.User.Query().Where(user.IsSuperuser(true)).All(ctx)
if err != nil {
return nil, err
}

View file

@ -139,7 +139,6 @@ func TestUserRepo_Delete(t *testing.T) {
allUsers, _ = tRepos.Users.GetAll(ctx)
assert.Equal(t, len(allUsers), 0)
}
func TestUserRepo_GetSuperusers(t *testing.T) {

View file

@ -4,10 +4,9 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"github.com/ardanlabs/conf/v3"
"os"
)
const (
@ -55,7 +54,6 @@ func New() (*Config, error) {
const prefix = "HBOX"
help, err := conf.Parse(prefix, &cfg)
if err != nil {
if errors.Is(err, conf.ErrHelpWanted) {
fmt.Println(help)
@ -71,11 +69,9 @@ func New() (*Config, error) {
// This is useful for debugging. If the marshaller errors out, it will panic.
func (c *Config) Print() {
res, err := json.MarshalIndent(c, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(res))
}

View file

@ -36,5 +36,4 @@ func Test_MailerReady_Failure(t *testing.T) {
mc.From = "from"
assert.True(t, mc.Ready())
}

View file

@ -5,8 +5,7 @@ import (
"errors"
)
type UnauthorizedError struct {
}
type UnauthorizedError struct{}
func (err *UnauthorizedError) Error() string {
return "unauthorized"

View file

@ -14,7 +14,6 @@ func init() {
// FieldErrors array and returned.
func Check(val any) error {
err := validate.Struct(val)
if err != nil {
verrors, ok := err.(validator.ValidationErrors)
if !ok {

View file

@ -13,7 +13,6 @@ func Errors(log zerolog.Logger) server.Middleware {
return func(h server.Handler) server.Handler {
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
err := h.ServeHTTP(w, r)
if err != nil {
var resp server.ErrorResponse
var code int

View file

@ -76,7 +76,6 @@ func SugarLogger(log zerolog.Logger) server.Middleware {
return func(next server.Handler) server.Handler {
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
record := &statusRecorder{ResponseWriter: w, Status: http.StatusOK}
err := next.ServeHTTP(record, r) // Blocks until the next handler returns.

View file

@ -7,8 +7,7 @@ import (
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
type Faker struct {
}
type Faker struct{}
func NewFaker() *Faker {
rand.Seed(time.Now().UnixNano())
@ -20,7 +19,6 @@ func (f *Faker) Time() time.Time {
}
func (f *Faker) Str(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]

View file

@ -20,7 +20,7 @@ func ValidateUnique(values []string) bool {
func Test_GetRandomString(t *testing.T) {
t.Parallel()
// Test that the function returns a string of the correct length
var generated = make([]string, Loops)
generated := make([]string, Loops)
faker := NewFaker()
@ -36,7 +36,7 @@ func Test_GetRandomString(t *testing.T) {
func Test_GetRandomEmail(t *testing.T) {
t.Parallel()
// Test that the function returns a string of the correct length
var generated = make([]string, Loops)
generated := make([]string, Loops)
faker := NewFaker()
@ -52,8 +52,8 @@ func Test_GetRandomEmail(t *testing.T) {
func Test_GetRandomBool(t *testing.T) {
t.Parallel()
var trues = 0
var falses = 0
trues := 0
falses := 0
faker := NewFaker()
@ -91,5 +91,4 @@ func Test_RandomNumber(t *testing.T) {
t.Errorf("RandomNumber() failed to generate a number between %v and %v", MIN, MAX)
}
}
}

View file

@ -30,14 +30,12 @@ func GetTestMailer() (*Mailer, error) {
}
return mailer, nil
}
func Test_Mailer(t *testing.T) {
t.Parallel()
mailer, err := GetTestMailer()
if err != nil {
t.Skip("Error Reading Test Mailer Config - Skipping")
}
@ -47,7 +45,6 @@ func Test_Mailer(t *testing.T) {
}
message, err := RenderWelcome()
if err != nil {
t.Error(err)
}

View file

@ -41,7 +41,6 @@ func DefaultTemplateData() TemplateProps {
func render(tpl string, data TemplateProps) (string, error) {
tmpl, err := template.New("name").Parse(tpl)
if err != nil {
return "", err
}

View file

@ -11,7 +11,6 @@ type Middleware func(Handler) Handler
// handler. The middlewares' Handlers will be executed by requests in the order
// they are provided.
func wrapMiddleware(mw []Middleware, handler Handler) Handler {
// Loop backwards through the middleware invoking each one. Replace the
// handler with the new wrapped handler. Looping backwards ensures that the
// first middleware of the slice is the first to be executed by requests.

View file

@ -40,7 +40,6 @@ func (s *Server) toHttpHandler(handler Handler, mw ...Middleware) http.HandlerFu
})
err := handler.ServeHTTP(w, r.WithContext(ctx))
if err != nil {
if IsShutdownError(err) {
_ = s.Shutdown("SIGTERM")

View file

@ -37,5 +37,4 @@ func Test_Respond_JSON(t *testing.T) {
assert.Equal(t, http.StatusCreated, recorder.Code)
assert.JSONEq(t, recorder.Body.String(), `{"name":"dummy"}`)
assert.Equal(t, "application/json", recorder.Header().Get("Content-Type"))
}

View file

@ -79,7 +79,6 @@ func (s *Server) Shutdown(sig string) error {
s.wg.Wait()
return nil
}
func (s *Server) Start() error {

View file

@ -72,7 +72,6 @@ func Test_GracefulServerShutdownWithWorkers(t *testing.T) {
assert.NoError(t, err)
assert.True(t, isFinished)
}
func Test_GracefulServerShutdownWithRequests(t *testing.T) {

View file

@ -10,8 +10,7 @@ type Worker interface {
// the Worker interface and runs all tasks in a go routine without
// a pool or que or limits. It's useful for simple or small applications
// with minimal/short background tasks
type SimpleWorker struct {
}
type SimpleWorker struct{}
func NewSimpleWorker() *SimpleWorker {
return &SimpleWorker{}

View file

@ -97,5 +97,4 @@ func Disjoint[T key](a, b Set[T]) bool {
}
}
return true
}

View file

@ -28,7 +28,6 @@ var (
)
func TestDiff(t *testing.T) {
tests := []struct {
name string
args args