From b33ef5f02928cb5f948963c401f51898037d4a2e Mon Sep 17 00:00:00 2001 From: Hayden <64056131+hay-kot@users.noreply.github.com> Date: Sat, 3 Sep 2022 01:52:05 -0800 Subject: [PATCH] fix linter errors --- backend/app/api/v1/main_test.go | 6 +- backend/app/generator/main.go | 55 ------------ backend/internal/repo/repo_locations_test.go | 12 ++- backend/internal/repo/repo_tokens_test.go | 15 ++-- backend/internal/repo/repo_users_test.go | 20 +++-- backend/pkgs/automapper/README.md | 56 ------------ backend/pkgs/automapper/automapper.go | 92 -------------------- backend/pkgs/automapper/conf.go | 11 --- backend/pkgs/automapper/main.go | 48 ---------- backend/pkgs/automapper/templates.go | 22 ----- backend/pkgs/hasher/token.go | 2 +- backend/pkgs/logger/struct_logger.go | 2 +- backend/pkgs/logger/struct_logger_test.go | 5 ++ backend/pkgs/server/server_test.go | 5 +- 14 files changed, 44 insertions(+), 307 deletions(-) delete mode 100644 backend/app/generator/main.go delete mode 100644 backend/pkgs/automapper/README.md delete mode 100644 backend/pkgs/automapper/automapper.go delete mode 100644 backend/pkgs/automapper/conf.go delete mode 100644 backend/pkgs/automapper/main.go delete mode 100644 backend/pkgs/automapper/templates.go diff --git a/backend/app/api/v1/main_test.go b/backend/app/api/v1/main_test.go index 43c7132..dfaeaf7 100644 --- a/backend/app/api/v1/main_test.go +++ b/backend/app/api/v1/main_test.go @@ -31,7 +31,7 @@ func userPool() func() { users = userOut purge := func() { - mockHandler.svc.Admin.DeleteAll(context.Background()) + _ = mockHandler.svc.Admin.DeleteAll(context.Background()) } return purge @@ -43,7 +43,9 @@ func TestMain(m *testing.M) { repos, closeDb := mocks.GetEntRepos() mockHandler.svc = mocks.GetMockServices(repos) - defer closeDb() + defer func() { + _ = closeDb() + }() purge := userPool() defer purge() diff --git a/backend/app/generator/main.go b/backend/app/generator/main.go deleted file mode 100644 index 8caf35c..0000000 --- a/backend/app/generator/main.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "time" - - "github.com/google/uuid" - "github.com/hay-kot/content/backend/internal/types" - "github.com/hay-kot/content/backend/pkgs/automapper" - "github.com/tkrajina/typescriptify-golang-structs/typescriptify" -) - -// generateMappers serialized the config file into a list of automapper struct -func generateMappers() []automapper.AutoMapper { - return []automapper.AutoMapper{} -} - -func generateTypeScript() { - // Configuration - converter := typescriptify.New() - converter.CreateInterface = true - converter.ManageType(uuid.UUID{}, typescriptify.TypeOptions{TSType: "string"}) - converter.ManageType(time.Time{}, typescriptify.TypeOptions{TSType: "Date", TSTransform: "new Date(__VALUE__)"}) - - // General - public := []any{ - // Base Types - types.ApiSummary{}, - - // User Types - types.UserCreate{}, - types.UserIn{}, - types.UserUpdate{}, - - // Auth Types - types.LoginForm{}, - types.TokenResponse{}, - } - - for i := 0; i < len(public); i++ { - converter.Add(public[i]) - } - - // Creation - converter.ConvertToFile("./generated-types.ts") - -} - -func main() { - automappers := generateMappers() - conf := automapper.DefaultConf() - - automapper.Generate(automappers, conf) - - generateTypeScript() -} diff --git a/backend/internal/repo/repo_locations_test.go b/backend/internal/repo/repo_locations_test.go index 1aefdea..f2818ef 100644 --- a/backend/internal/repo/repo_locations_test.go +++ b/backend/internal/repo/repo_locations_test.go @@ -27,7 +27,8 @@ func Test_Locations_Get(t *testing.T) { assert.NoError(t, err) assert.Equal(t, loc.ID, foundLoc.ID) - testRepos.Locations.Delete(context.Background(), loc.ID) + err = testRepos.Locations.Delete(context.Background(), loc.ID) + assert.NoError(t, err) } func Test_LocationsGetAllWithCount(t *testing.T) { @@ -36,8 +37,9 @@ func Test_LocationsGetAllWithCount(t *testing.T) { Name: fk.RandomString(10), Description: fk.RandomString(100), }) + assert.NoError(t, err) - testRepos.Items.Create(ctx, testGroup.ID, types.ItemCreate{ + _, err = testRepos.Items.Create(ctx, testGroup.ID, types.ItemCreate{ Name: fk.RandomString(10), Description: fk.RandomString(100), LocationID: result.ID, @@ -65,7 +67,8 @@ func Test_Locations_Create(t *testing.T) { assert.NoError(t, err) assert.Equal(t, loc.ID, foundLoc.ID) - testRepos.Locations.Delete(context.Background(), loc.ID) + err = testRepos.Locations.Delete(context.Background(), loc.ID) + assert.NoError(t, err) } func Test_Locations_Update(t *testing.T) { @@ -88,7 +91,8 @@ func Test_Locations_Update(t *testing.T) { assert.Equal(t, update.Name, foundLoc.Name) assert.Equal(t, update.Description, foundLoc.Description) - testRepos.Locations.Delete(context.Background(), loc.ID) + err = testRepos.Locations.Delete(context.Background(), loc.ID) + assert.NoError(t, err) } func Test_Locations_Delete(t *testing.T) { diff --git a/backend/internal/repo/repo_tokens_test.go b/backend/internal/repo/repo_tokens_test.go index 169d4a7..be737ef 100644 --- a/backend/internal/repo/repo_tokens_test.go +++ b/backend/internal/repo/repo_tokens_test.go @@ -34,8 +34,9 @@ func Test_EntAuthTokenRepo_CreateToken(t *testing.T) { assert.Equal(expiresAt, token.ExpiresAt) // Cleanup - testRepos.Users.Delete(ctx, userOut.ID) - testRepos.AuthTokens.DeleteAll(ctx) + assert.NoError(testRepos.Users.Delete(ctx, userOut.ID)) + _, err = testRepos.AuthTokens.DeleteAll(ctx) + assert.NoError(err) } func Test_EntAuthTokenRepo_GetUserByToken(t *testing.T) { @@ -65,8 +66,9 @@ func Test_EntAuthTokenRepo_GetUserByToken(t *testing.T) { assert.Equal(userOut.Email, foundUser.Email) // Cleanup - testRepos.Users.Delete(ctx, userOut.ID) - testRepos.AuthTokens.DeleteAll(ctx) + assert.NoError(testRepos.Users.Delete(ctx, userOut.ID)) + _, err = testRepos.AuthTokens.DeleteAll(ctx) + assert.NoError(err) } func Test_EntAuthTokenRepo_PurgeExpiredTokens(t *testing.T) { @@ -108,6 +110,7 @@ func Test_EntAuthTokenRepo_PurgeExpiredTokens(t *testing.T) { } // Cleanup - testRepos.Users.Delete(ctx, userOut.ID) - testRepos.AuthTokens.DeleteAll(ctx) + assert.NoError(testRepos.Users.Delete(ctx, userOut.ID)) + _, err = testRepos.AuthTokens.DeleteAll(ctx) + assert.NoError(err) } diff --git a/backend/internal/repo/repo_users_test.go b/backend/internal/repo/repo_users_test.go index c1f7cd9..4f63b61 100644 --- a/backend/internal/repo/repo_users_test.go +++ b/backend/internal/repo/repo_users_test.go @@ -28,7 +28,8 @@ func Test_EntUserRepo_GetOneEmail(t *testing.T) { user := UserFactory() ctx := context.Background() - testRepos.Users.Create(ctx, user) + _, err := testRepos.Users.Create(ctx, user) + assert.NoError(err) foundUser, err := testRepos.Users.GetOneEmail(ctx, user.Email) @@ -38,7 +39,8 @@ func Test_EntUserRepo_GetOneEmail(t *testing.T) { assert.Equal(user.Name, foundUser.Name) // Cleanup - testRepos.Users.DeleteAll(ctx) + err = testRepos.Users.DeleteAll(ctx) + assert.NoError(err) } func Test_EntUserRepo_GetOneId(t *testing.T) { @@ -55,7 +57,8 @@ func Test_EntUserRepo_GetOneId(t *testing.T) { assert.Equal(user.Name, foundUser.Name) // Cleanup - testRepos.Users.DeleteAll(ctx) + err = testRepos.Users.DeleteAll(ctx) + assert.NoError(err) } func Test_EntUserRepo_GetAll(t *testing.T) { @@ -95,11 +98,12 @@ func Test_EntUserRepo_GetAll(t *testing.T) { } for _, usr := range created { - testRepos.Users.Delete(ctx, usr.ID) + _ = testRepos.Users.Delete(ctx, usr.ID) } // Cleanup - testRepos.Users.DeleteAll(ctx) + err = testRepos.Users.DeleteAll(ctx) + assert.NoError(t, err) } func Test_EntUserRepo_Update(t *testing.T) { @@ -119,7 +123,8 @@ func Test_EntUserRepo_Delete(t *testing.T) { allUsers, _ := testRepos.Users.GetAll(ctx) assert.Greater(t, len(allUsers), 0) - testRepos.Users.DeleteAll(ctx) + err := testRepos.Users.DeleteAll(ctx) + assert.NoError(t, err) allUsers, _ = testRepos.Users.GetAll(ctx) assert.Equal(t, len(allUsers), 0) @@ -154,5 +159,6 @@ func Test_EntUserRepo_GetSuperusers(t *testing.T) { } // Cleanup - testRepos.Users.DeleteAll(ctx) + err = testRepos.Users.DeleteAll(ctx) + assert.NoError(t, err) } diff --git a/backend/pkgs/automapper/README.md b/backend/pkgs/automapper/README.md deleted file mode 100644 index fc9b01b..0000000 --- a/backend/pkgs/automapper/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# Automapper - - -Automapper is an opinionated Go library that provides a dead simple interface to mapping 1-1 models To/From a database Model to a DTO or Schema using value semantics. It does not rely on code comments, but instead uses standard Go code to define your mapping and configuration to make it easy to use an refactor. - -Current Limitation -- flat/single level models -- single schema to model per config entry -- limited configuration (support lowercase, camelcase, snakecase, etc) - - -Future Considerations -- [ ] Recursive mapping of embed structs -- [ ] Optional generate time type checker. -- [ ] Ensure values are copied to the destination and not just a reference -- [ ] ?!?!? - - -## Example Configuration - -```go -package main - -import ( - "github.com/mealie-recipes/mealie-analytics/ent" - "github.com/mealie-recipes/mealie-analytics/internal/types" - "github.com/mealie-recipes/mealie-analytics/pkgs/automapper" -) - -// getMappers serialized the config file into a list of automapper struct -func getMappers() []automapper.AutoMapper { - return []automapper.AutoMapper{ - { - Package: "mapper", // generated package name - Prefix: "analytics", // generating file prefix -> analytics_automapper.go - Name: "Mealie Analytics", // For console output - Schema: automapper.Schema{ - Type: types.Analytics{}, - Prefix: "types", // Package namespace - }, - Model: automapper.Model{ - Type: ent.Analytics{}, - Prefix: "ent", // Package namespace - }, - Imports: []string{}, // Specify additional imports here - }, - } -} - -func main() { - automappers := getMappers() - conf := automapper.DefaultConf() - - automapper.Generate(automappers, conf) -} -``` \ No newline at end of file diff --git a/backend/pkgs/automapper/automapper.go b/backend/pkgs/automapper/automapper.go deleted file mode 100644 index f620c60..0000000 --- a/backend/pkgs/automapper/automapper.go +++ /dev/null @@ -1,92 +0,0 @@ -package automapper - -import ( - "bytes" - "fmt" - "go/format" - "os" - "reflect" - "strings" - "text/template" -) - -type FieldAssignment struct { - ModelField string - SchemaField string -} - -type Model struct { - Type interface{} - Prefix string - Fields []reflect.StructField - Reference string -} - -type Schema struct { - Name string - Type interface{} - Prefix string - Fields []reflect.StructField - Reference string -} - -type AutoMapper struct { - Name string - Package string - Prefix string - Schema Schema - Model Model - Imports []string - FieldAssignments []FieldAssignment -} - -func (mapper *AutoMapper) ExecuteTemplates(conf *AutoMapperConf) { - t := template.New("automapper") - t, err := t.Parse(automapperTemplate) - if err != nil { - fmt.Println(err) - } - - // Ensure the output directory exists - os.MkdirAll(conf.OutDir, 0755) - - var path = fmt.Sprintf("%s/%s", conf.OutDir, mapper.GetFileName()) - - f, err := os.Create(path) - if err != nil { - panic(err) - } - defer f.Close() - - var buf bytes.Buffer - - err = t.Execute(&buf, mapper) - if err != nil { - fmt.Println(err) - } - - text, err := format.Source(buf.Bytes()) - - if err != nil { - fmt.Println(err) - } - - f.Write(text) - -} - -// GetFileName returns the computed file name based off user preference. -// If the Prefix has been specified on the AutoMapper it will be used -// in place of the Struct name. If the Prefix is not specified, the -// Struct name will be used. -// -// Examples: -// prefix_automapper.go -// mystructname_automapper.go -func (mapper *AutoMapper) GetFileName() string { - if mapper.Prefix == "" { - return strings.ToLower(mapper.Schema.Reference) + "_" + "automapper.go" - } - return strings.ToLower(mapper.Prefix) + "_" + "automapper.go" - -} diff --git a/backend/pkgs/automapper/conf.go b/backend/pkgs/automapper/conf.go deleted file mode 100644 index 96f090a..0000000 --- a/backend/pkgs/automapper/conf.go +++ /dev/null @@ -1,11 +0,0 @@ -package automapper - -type AutoMapperConf struct { - OutDir string -} - -func DefaultConf() *AutoMapperConf { - return &AutoMapperConf{ - OutDir: "internal/mapper", - } -} diff --git a/backend/pkgs/automapper/main.go b/backend/pkgs/automapper/main.go deleted file mode 100644 index e3eba73..0000000 --- a/backend/pkgs/automapper/main.go +++ /dev/null @@ -1,48 +0,0 @@ -package automapper - -import ( - "fmt" - "reflect" - "strings" -) - -func Generate(automappers []AutoMapper, conf *AutoMapperConf) { - for _, mapper := range automappers { - modelType := reflect.TypeOf(mapper.Model.Type) - transferObjectType := reflect.TypeOf(mapper.Schema.Type) - - fmt.Printf("%s: %s -> %s\n", mapper.Name, modelType.Name(), transferObjectType.Name()) - - // From Fields - mapper.Imports = append(mapper.Imports, modelType.PkgPath()) - mapper.Model.Reference = modelType.Name() - mapper.Model.Fields = make([]reflect.StructField, 0) - for i := 0; i < modelType.NumField(); i++ { - mapper.Model.Fields = append(mapper.Model.Fields, modelType.Field(i)) - } - - // To Fields - mapper.Imports = append(mapper.Imports, transferObjectType.PkgPath()) - mapper.Schema.Reference = transferObjectType.Name() - mapper.Schema.Fields = make([]reflect.StructField, 0) - for i := 0; i < transferObjectType.NumField(); i++ { - mapper.Schema.Fields = append(mapper.Schema.Fields, transferObjectType.Field(i)) - } - - // Determine Field Assignments by matching the To fields and From fields by name - mapper.FieldAssignments = make([]FieldAssignment, 0) - - for _, toField := range mapper.Schema.Fields { - for _, fromField := range mapper.Model.Fields { - if strings.EqualFold(toField.Name, fromField.Name) { - mapper.FieldAssignments = append(mapper.FieldAssignments, FieldAssignment{ - ModelField: fromField.Name, - SchemaField: toField.Name, - }) - } - } - } - - mapper.ExecuteTemplates(conf) - } -} diff --git a/backend/pkgs/automapper/templates.go b/backend/pkgs/automapper/templates.go deleted file mode 100644 index b001f61..0000000 --- a/backend/pkgs/automapper/templates.go +++ /dev/null @@ -1,22 +0,0 @@ -package automapper - -var automapperTemplate = `// Code generated by "/pkgs/automapper"; DO NOT EDIT. -package {{ .Package }} - -import ( - {{ range $import := .Imports }}"{{ $import }}" - {{ end }} -) - -func {{ .Schema.Reference }}FromModel(from {{ .Model.Prefix}}.{{ .Model.Reference }}) {{ .Schema.Prefix}}.{{ .Schema.Reference }} { - return {{ .Schema.Prefix}}.{{ .Schema.Reference }}{ {{ range $i, $f := .FieldAssignments }} - {{ $f.SchemaField }}: from.{{ $f.ModelField }},{{ end }} - } -} - -func {{ .Schema.Reference }}ToModel(from {{ .Schema.Prefix}}.{{ .Schema.Reference }}) {{ .Model.Prefix}}.{{ .Model.Reference }} { - return {{ .Model.Prefix}}.{{ .Model.Reference }}{ {{ range $i, $f := .FieldAssignments }} - {{ $f.ModelField }}: from.{{ $f.SchemaField }},{{ end }} - } -} -` diff --git a/backend/pkgs/hasher/token.go b/backend/pkgs/hasher/token.go index 117eeca..8d98e10 100644 --- a/backend/pkgs/hasher/token.go +++ b/backend/pkgs/hasher/token.go @@ -13,7 +13,7 @@ type Token struct { func GenerateToken() Token { randomBytes := make([]byte, 16) - rand.Read(randomBytes) + _, _ = rand.Read(randomBytes) plainText := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(randomBytes) hash := HashToken(plainText) diff --git a/backend/pkgs/logger/struct_logger.go b/backend/pkgs/logger/struct_logger.go index 2ebd3b6..a593076 100644 --- a/backend/pkgs/logger/struct_logger.go +++ b/backend/pkgs/logger/struct_logger.go @@ -119,7 +119,7 @@ func (l *Logger) print(level Level, message string, properties map[string]string n, err := l.out.Write(line) if dumpTrace { - l.out.Write(debug.Stack()) + n, err = l.out.Write(debug.Stack()) } return n, err } diff --git a/backend/pkgs/logger/struct_logger_test.go b/backend/pkgs/logger/struct_logger_test.go index 9b8526d..0ab629d 100644 --- a/backend/pkgs/logger/struct_logger_test.go +++ b/backend/pkgs/logger/struct_logger_test.go @@ -8,6 +8,10 @@ import ( "github.com/stretchr/testify/assert" ) +func init() { + IncludeTrace = true +} + var lastWrite = []byte{} type testLogRecorder struct { @@ -57,6 +61,7 @@ func getTestLogger(t *testing.T, level Level) *Logger { } func checkLastEntry(t *testing.T, level Level, message string, props *Props) { + t.Helper() entry := &logEntry{} entry.Unmarshal(t, lastWrite) diff --git a/backend/pkgs/server/server_test.go b/backend/pkgs/server/server_test.go index 18eed9e..b69b3eb 100644 --- a/backend/pkgs/server/server_test.go +++ b/backend/pkgs/server/server_test.go @@ -12,7 +12,8 @@ func testServer(t *testing.T, r http.Handler) *Server { svr := NewServer("127.0.0.1", "19245") go func() { - svr.Start(r) + err := svr.Start(r) + assert.NoError(t, err) }() ping := func() error { @@ -85,7 +86,7 @@ func Test_GracefulServerShutdownWithRequests(t *testing.T) { // Make request to "/test" go func() { - http.Get("http://127.0.0.1:19245/test") // This is probably bad? + _, _ = http.Get("http://127.0.0.1:19245/test") // This is probably bad? }() time.Sleep(time.Second) // Hack to wait for the request to be made