From 9ce0ddb4f8f9bc70a7ebe4b5647ef0752055c346 Mon Sep 17 00:00:00 2001 From: Lea Anthony Date: Sun, 12 Nov 2023 12:30:49 +1100 Subject: [PATCH] [chore] lint fixes --- v2/cmd/wails/build.go | 2 - v2/cmd/wails/dev.go | 5 +- v2/cmd/wails/doctor.go | 4 +- v2/cmd/wails/flags/dev.go | 2 - v2/cmd/wails/flags/init.go | 1 - v2/cmd/wails/generate.go | 13 +++--- v2/cmd/wails/init.go | 16 +++---- v2/cmd/wails/internal/dev/dev.go | 5 +- v2/cmd/wails/internal/dev/watcher.go | 1 - v2/cmd/wails/internal/gomod/gomod.go | 2 +- v2/cmd/wails/main.go | 1 - v2/cmd/wails/update.go | 4 +- v2/examples/customlayout/go.mod | 6 ++- v2/examples/customlayout/go.sum | 1 + v2/go.mod | 4 +- v2/internal/app/app_devtools_not.go | 17 +++---- v2/internal/binding/binding.go | 4 +- v2/internal/binding/boundMethod.go | 1 - v2/internal/binding/db.go | 8 +--- v2/internal/binding/generate.go | 24 +++++----- v2/internal/binding/reflect.go | 2 - v2/internal/frontend/calls.go | 2 +- .../frontend/desktop/darwin/callbacks.go | 2 +- .../frontend/desktop/darwin/clipboard.go | 1 - v2/internal/frontend/desktop/darwin/dialog.go | 17 ++++--- .../frontend/desktop/darwin/frontend.go | 35 ++++++++------ .../frontend/desktop/darwin/inspector.go | 1 - v2/internal/frontend/desktop/darwin/menu.go | 2 +- .../frontend/desktop/darwin/menuitem.go | 11 +++-- v2/internal/frontend/desktop/darwin/screen.go | 1 + .../desktop/darwin/single_instance.go | 7 +-- v2/internal/frontend/desktop/darwin/window.go | 4 +- .../frontend/desktop/windows/dialog.go | 8 ++-- v2/internal/frontend/dispatcher/calls.go | 1 - v2/internal/frontend/dispatcher/events.go | 1 + .../frontend/dispatcher/securecalls.go | 2 +- .../frontend/dispatcher/systemcalls.go | 5 +- v2/internal/frontend/frontend.go | 4 +- v2/internal/frontend/runtime/events.go | 2 +- v2/internal/fs/fs.go | 14 +++--- v2/internal/github/github.go | 6 +-- .../cfd/CommonFileDialog_nonWindows.go | 10 ++-- .../go-common-file-dialog/cfd/errors.go | 4 +- .../cfd/iFileOpenDialog.go | 2 +- .../cfd/iShellItemArray.go | 2 +- .../cfd/vtblCommonFunc.go | 2 +- .../go-common-file-dialog/cfdutil/CFDUtil.go | 16 +++++-- v2/internal/gomod/gomod.go | 1 + v2/internal/gomod/gomod_data_unix.go | 4 ++ v2/internal/logger/custom_logger.go | 1 - v2/internal/logger/default_logger.go | 2 - v2/internal/menumanager/applicationmenu.go | 2 - v2/internal/menumanager/contextmenu.go | 2 - v2/internal/menumanager/menuitemmap.go | 7 +-- v2/internal/menumanager/menumanager.go | 5 +- v2/internal/menumanager/processedMenu.go | 28 +++++------ v2/internal/menumanager/traymenu.go | 8 ++-- v2/internal/process/process.go | 1 - v2/internal/project/project.go | 4 +- v2/internal/s/s.go | 16 +++---- v2/internal/shell/shell.go | 6 +-- v2/internal/signal/signal.go | 19 ++++---- v2/internal/staticanalysis/staticanalysis.go | 3 +- v2/internal/system/packagemanager/pm.go | 8 ++-- v2/internal/system/system.go | 13 ++---- v2/internal/typescriptify/typescriptify.go | 10 ++-- .../webview2runtime/webview2installer.go | 2 +- v2/pkg/application/application.go | 4 +- v2/pkg/assetserver/assethandler.go | 5 +- v2/pkg/assetserver/assetserver.go | 6 +-- v2/pkg/assetserver/assetserver_webview.go | 3 +- v2/pkg/assetserver/common.go | 4 +- v2/pkg/assetserver/webview/request_darwin.go | 5 +- v2/pkg/buildassets/buildassets.go | 4 +- v2/pkg/commands/bindings/bindings.go | 1 - v2/pkg/commands/build/base.go | 15 ++---- v2/pkg/commands/build/build.go | 7 +-- v2/pkg/commands/build/builder.go | 6 +-- v2/pkg/commands/build/nsis_installer.go | 4 +- v2/pkg/commands/build/packager.go | 27 +++++------ v2/pkg/logger/filelogger.go | 2 +- v2/pkg/mac/login_darwin.go | 2 +- v2/pkg/mac/notification_darwin.go | 2 +- v2/pkg/menu/callback.go | 2 +- v2/pkg/menu/colours/colours.go | 6 ++- v2/pkg/menu/keys/keys.go | 2 +- v2/pkg/menu/keys/parser.go | 3 -- v2/pkg/menu/keys/stringify.go | 9 ++-- v2/pkg/menu/menu.go | 3 +- v2/pkg/menu/menuitem.go | 14 ++---- v2/pkg/menu/menuroles.go | 46 +++++++++---------- v2/pkg/menu/styledlabel.go | 7 +++ v2/pkg/menu/tray.go | 3 +- v2/pkg/options/mac/mac.go | 4 +- v2/pkg/options/mac/preferences.go | 6 ++- v2/pkg/options/mac/titlebar.go | 2 - v2/pkg/options/options.go | 3 +- v2/pkg/options/windows/windows.go | 2 +- v2/pkg/runtime/dialog.go | 1 + v2/pkg/runtime/events.go | 4 +- v2/pkg/runtime/log.go | 1 + v2/pkg/runtime/menu.go | 1 + v2/pkg/runtime/runtime.go | 1 + v2/pkg/runtime/screen.go | 7 ++- v2/pkg/templates/generate/generate.go | 1 - v2/pkg/templates/templates.go | 7 --- v2/tools/release/release.go | 8 ++-- 107 files changed, 312 insertions(+), 355 deletions(-) mode change 100755 => 100644 v2/internal/binding/binding.go mode change 100755 => 100644 v2/internal/binding/reflect.go diff --git a/v2/cmd/wails/build.go b/v2/cmd/wails/build.go index 1c6b791ec85..858ecb4c9e2 100644 --- a/v2/cmd/wails/build.go +++ b/v2/cmd/wails/build.go @@ -18,7 +18,6 @@ import ( ) func buildApplication(f *flags.Build) error { - if f.NoColour { pterm.DisableColor() colour.ColourEnabled = false @@ -255,5 +254,4 @@ func buildApplication(f *flags.Build) error { } return nil - } diff --git a/v2/cmd/wails/dev.go b/v2/cmd/wails/dev.go index dbb2cf5d8fc..30213a68e13 100644 --- a/v2/cmd/wails/dev.go +++ b/v2/cmd/wails/dev.go @@ -1,16 +1,16 @@ package main import ( + "os" + "github.com/pterm/pterm" "github.com/wailsapp/wails/v2/cmd/wails/flags" "github.com/wailsapp/wails/v2/cmd/wails/internal/dev" "github.com/wailsapp/wails/v2/internal/colour" "github.com/wailsapp/wails/v2/pkg/clilogger" - "os" ) func devApplication(f *flags.Dev) error { - if f.NoColour { pterm.DisableColor() colour.ColourEnabled = false @@ -34,5 +34,4 @@ func devApplication(f *flags.Dev) error { } return dev.Application(f, logger) - } diff --git a/v2/cmd/wails/doctor.go b/v2/cmd/wails/doctor.go index ef73419ecc8..74f9ec6cc88 100644 --- a/v2/cmd/wails/doctor.go +++ b/v2/cmd/wails/doctor.go @@ -128,8 +128,8 @@ func diagnoseEnvironment(f *flags.Doctor) error { // Output Dependencies Status var dependenciesMissing []string var externalPackages []*packagemanager.Dependency - var dependenciesAvailableRequired = 0 - var dependenciesAvailableOptional = 0 + dependenciesAvailableRequired := 0 + dependenciesAvailableOptional := 0 dependenciesTableData := pterm.TableData{ {"Dependency", "Package Name", "Status", "Version"}, diff --git a/v2/cmd/wails/flags/dev.go b/v2/cmd/wails/flags/dev.go index 7e5e6239c74..501450a982e 100644 --- a/v2/cmd/wails/flags/dev.go +++ b/v2/cmd/wails/flags/dev.go @@ -47,7 +47,6 @@ func (*Dev) Default() *Dev { } func (d *Dev) Process() error { - var err error err = d.loadAndMergeProjectConfig() if err != nil { @@ -113,7 +112,6 @@ func (d *Dev) loadAndMergeProjectConfig() error { } return nil - } // GenerateBuildOptions creates a build.Options using the flags diff --git a/v2/cmd/wails/flags/init.go b/v2/cmd/wails/flags/init.go index 6e642ec9a2f..16d56a207d9 100644 --- a/v2/cmd/wails/flags/init.go +++ b/v2/cmd/wails/flags/init.go @@ -14,7 +14,6 @@ type Init struct { } func (i *Init) Default() *Init { - result := &Init{ TemplateName: "vanilla", } diff --git a/v2/cmd/wails/generate.go b/v2/cmd/wails/generate.go index a7b059ecfdd..159df90a1b5 100644 --- a/v2/cmd/wails/generate.go +++ b/v2/cmd/wails/generate.go @@ -2,6 +2,9 @@ package main import ( "fmt" + "os" + "path/filepath" + "github.com/leaanthony/debme" "github.com/leaanthony/gosod" "github.com/pterm/pterm" @@ -14,12 +17,9 @@ import ( "github.com/wailsapp/wails/v2/pkg/clilogger" "github.com/wailsapp/wails/v2/pkg/commands/bindings" "github.com/wailsapp/wails/v2/pkg/commands/buildtags" - "os" - "path/filepath" ) func generateModule(f *flags.GenerateModule) error { - if f.NoColour { pterm.DisableColor() colour.ColourEnabled = false @@ -55,7 +55,6 @@ func generateModule(f *flags.GenerateModule) error { } func generateTemplate(f *flags.GenerateTemplate) error { - if f.NoColour { pterm.DisableColor() colour.ColourEnabled = false @@ -77,7 +76,7 @@ func generateTemplate(f *flags.GenerateTemplate) error { } templateDir := filepath.Join(cwd, f.Name) if !fs.DirExists(templateDir) { - err := os.MkdirAll(templateDir, 0755) + err := os.MkdirAll(templateDir, 0o755) if err != nil { return err } @@ -200,7 +199,7 @@ func processPackageJSON(frontendDir string) error { json, _ = sjson.SetBytes(json, "name", "{{.ProjectName}}") json, _ = sjson.SetBytes(json, "author", "{{.AuthorName}}") - err = os.WriteFile(packageJSON, json, 0644) + err = os.WriteFile(packageJSON, json, 0o644) if err != nil { return err } @@ -231,7 +230,7 @@ func processPackageLockJSON(frontendDir string) error { printBulletPoint("Updating package-lock.json data...") json, _ = sjson.Set(json, "name", "{{.ProjectName}}") - err = os.WriteFile(filename, []byte(json), 0644) + err = os.WriteFile(filename, []byte(json), 0o644) if err != nil { return err } diff --git a/v2/cmd/wails/init.go b/v2/cmd/wails/init.go index f9a9c6b3f00..709905c0f17 100644 --- a/v2/cmd/wails/init.go +++ b/v2/cmd/wails/init.go @@ -3,6 +3,12 @@ package main import ( "bufio" "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + "github.com/flytam/filenamify" "github.com/leaanthony/slicer" "github.com/pkg/errors" @@ -13,15 +19,9 @@ import ( "github.com/wailsapp/wails/v2/pkg/clilogger" "github.com/wailsapp/wails/v2/pkg/git" "github.com/wailsapp/wails/v2/pkg/templates" - "os" - "os/exec" - "path/filepath" - "strings" - "time" ) func initProject(f *flags.Init) error { - if f.NoColour { pterm.DisableColor() colour.ColourEnabled = false @@ -215,7 +215,7 @@ func initGit(options *templates.Options) error { "frontend/dist", "frontend/node_modules", } - err = os.WriteFile(filepath.Join(options.TargetDir, ".gitignore"), []byte(strings.Join(ignore, "\n")), 0644) + err = os.WriteFile(filepath.Join(options.TargetDir, ".gitignore"), []byte(strings.Join(ignore, "\n")), 0o644) if err != nil { return errors.Wrap(err, "Unable to create gitignore") } @@ -271,7 +271,7 @@ func updateReplaceLine(targetPath string) { } } - err = os.WriteFile("go.mod", []byte(strings.Join(lines, "\n")), 0644) + err = os.WriteFile("go.mod", []byte(strings.Join(lines, "\n")), 0o644) if err != nil { fatal(err.Error()) } diff --git a/v2/cmd/wails/internal/dev/dev.go b/v2/cmd/wails/internal/dev/dev.go index 80d7a6d875c..1f9b95c8994 100644 --- a/v2/cmd/wails/internal/dev/dev.go +++ b/v2/cmd/wails/internal/dev/dev.go @@ -52,7 +52,6 @@ func sliceToMap(input []string) map[string]struct{} { // Application runs the application in dev mode func Application(f *flags.Dev, logger *clilogger.CLILogger) error { - cwd := lo.Must(os.Getwd()) // Update go.mod to use current wails version @@ -271,7 +270,6 @@ func runFrontendDevWatcherCommand(frontendDirectory string, devCommand string, d // restartApp does the actual rebuilding of the application when files change func restartApp(buildOptions *build.Options, debugBinaryProcess *process.Process, f *flags.Dev, exitCodeChannel chan int, legacyUseDevServerInsteadofCustomScheme bool) (*process.Process, string, error) { - appBinary, err := build.Build(buildOptions) println() if err != nil { @@ -298,7 +296,6 @@ func restartApp(buildOptions *build.Options, debugBinaryProcess *process.Process // parse appargs if any args, err := shlex.Split(f.AppArgs) - if err != nil { buildOptions.Logger.Fatal("Unable to parse appargs: %s", err.Error()) } @@ -345,7 +342,7 @@ func doWatcherLoop(cwd string, buildOptions *build.Options, debugBinaryProcess * logutils.LogGreen("Watching (sub)/directory: %s", cwd) // Main Loop - var extensionsThatTriggerARebuild = sliceToMap(strings.Split(f.Extensions, ",")) + extensionsThatTriggerARebuild := sliceToMap(strings.Split(f.Extensions, ",")) var dirsThatTriggerAReload []string for _, dir := range strings.Split(f.ReloadDirs, ",") { if dir == "" { diff --git a/v2/cmd/wails/internal/dev/watcher.go b/v2/cmd/wails/internal/dev/watcher.go index 499b76dfd38..4e7457ef942 100644 --- a/v2/cmd/wails/internal/dev/watcher.go +++ b/v2/cmd/wails/internal/dev/watcher.go @@ -18,7 +18,6 @@ type Watcher interface { // initialiseWatcher creates the project directory watcher that will trigger recompile func initialiseWatcher(cwd string) (*fsnotify.Watcher, error) { - // Ignore dot files, node_modules and build directories by default ignoreDirs := getIgnoreDirs(cwd) diff --git a/v2/cmd/wails/internal/gomod/gomod.go b/v2/cmd/wails/internal/gomod/gomod.go index 52e56344b33..5da14a5ff96 100644 --- a/v2/cmd/wails/internal/gomod/gomod.go +++ b/v2/cmd/wails/internal/gomod/gomod.go @@ -56,7 +56,7 @@ func SyncGoMod(logger *clilogger.CLILogger, updateWailsVersion bool) error { } if updated { - return os.WriteFile(gomodFilename, gomodData, 0755) + return os.WriteFile(gomodFilename, gomodData, 0o755) } return nil diff --git a/v2/cmd/wails/main.go b/v2/cmd/wails/main.go index a0a7d4a319a..ccf1576e9c1 100644 --- a/v2/cmd/wails/main.go +++ b/v2/cmd/wails/main.go @@ -66,7 +66,6 @@ func bool2Str(b bool) string { var app *clir.Cli func main() { - var err error app = clir.NewCli("Wails", "Go/HTML Appkit", internal.Version) diff --git a/v2/cmd/wails/update.go b/v2/cmd/wails/update.go index ac0e7375af2..9f8b6e60462 100644 --- a/v2/cmd/wails/update.go +++ b/v2/cmd/wails/update.go @@ -15,7 +15,6 @@ import ( // AddSubcommand adds the `init` command for the Wails application func update(f *flags.Update) error { - if f.NoColour { colour.ColourEnabled = false pterm.DisableColor() @@ -73,8 +72,7 @@ func update(f *flags.Update) error { } func updateToVersion(targetVersion *github.SemanticVersion, force bool, currentVersion string) error { - - var targetVersionString = "v" + targetVersion.String() + targetVersionString := "v" + targetVersion.String() if targetVersionString == currentVersion { pterm.Println("\nLooks like you're up to date!") diff --git a/v2/examples/customlayout/go.mod b/v2/examples/customlayout/go.mod index ccec36a7604..8947007a7b0 100644 --- a/v2/examples/customlayout/go.mod +++ b/v2/examples/customlayout/go.mod @@ -1,6 +1,8 @@ module changeme -go 1.18 +go 1.21 + +toolchain go1.21.0 require github.com/wailsapp/wails/v2 v2.1.0 @@ -24,7 +26,7 @@ require ( github.com/tkrajina/go-reflector v0.5.6 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect - github.com/wailsapp/go-webview2 v1.0.7 // indirect + github.com/wailsapp/go-webview2 v1.0.10 // indirect github.com/wailsapp/mimetype v1.4.1 // indirect golang.org/x/crypto v0.14.0 // indirect golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect diff --git a/v2/examples/customlayout/go.sum b/v2/examples/customlayout/go.sum index fb0946bc54c..4cdbdac671c 100644 --- a/v2/examples/customlayout/go.sum +++ b/v2/examples/customlayout/go.sum @@ -56,6 +56,7 @@ github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQ github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/wailsapp/go-webview2 v1.0.7 h1:s95+7irJsAsTy1RsjJ6N0cYX7tZ4gP7Uzawds0L2urs= github.com/wailsapp/go-webview2 v1.0.7/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo= +github.com/wailsapp/go-webview2 v1.0.10/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo= github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs= github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o= golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= diff --git a/v2/go.mod b/v2/go.mod index 88bd7c75cda..b166a30b2ef 100644 --- a/v2/go.mod +++ b/v2/go.mod @@ -1,6 +1,8 @@ module github.com/wailsapp/wails/v2 -go 1.18 +go 1.21 + +toolchain go1.21.0 require ( github.com/Masterminds/semver v1.5.0 diff --git a/v2/internal/app/app_devtools_not.go b/v2/internal/app/app_devtools_not.go index d37ee3124ac..91267204864 100644 --- a/v2/internal/app/app_devtools_not.go +++ b/v2/internal/app/app_devtools_not.go @@ -1,8 +1,9 @@ -//go:build !devtools - -package app - -// Note: devtools flag is also added in debug builds -func IsDevtoolsEnabled() bool { - return false -} +//go:build !devtools + +package app + +// IsDevtoolsEnabled returns true if devtools should be enabled +// Note: devtools flag is also added in debug builds +func IsDevtoolsEnabled() bool { + return false +} diff --git a/v2/internal/binding/binding.go b/v2/internal/binding/binding.go old mode 100755 new mode 100644 index 75b821f29ca..d911e12a3d7 --- a/v2/internal/binding/binding.go +++ b/v2/internal/binding/binding.go @@ -60,7 +60,6 @@ func NewBindings(logger *logger.Logger, structPointersToBind []interface{}, exem // Add the given struct methods to the Bindings func (b *Bindings) Add(structPtr interface{}) error { - methods, err := b.getMethods(structPtr) if err != nil { return fmt.Errorf("cannot bind value to app: %s", err.Error()) @@ -146,7 +145,6 @@ func (b *Bindings) GenerateModels() ([]byte, error) { } func (b *Bindings) WriteModels(modelsDir string) error { - modelsData, err := b.GenerateModels() if err != nil { return err @@ -157,7 +155,7 @@ func (b *Bindings) WriteModels(modelsDir string) error { } filename := filepath.Join(modelsDir, "models.ts") - err = os.WriteFile(filename, modelsData, 0755) + err = os.WriteFile(filename, modelsData, 0o755) if err != nil { return err } diff --git a/v2/internal/binding/boundMethod.go b/v2/internal/binding/boundMethod.go index f6ffdb600bc..c13e2ff37cc 100644 --- a/v2/internal/binding/boundMethod.go +++ b/v2/internal/binding/boundMethod.go @@ -28,7 +28,6 @@ func (b *BoundMethod) OutputCount() int { // ParseArgs method converts the input json into the types expected by the method func (b *BoundMethod) ParseArgs(args []json.RawMessage) ([]interface{}, error) { - result := make([]interface{}, b.InputCount()) if len(args) != b.InputCount() { return nil, fmt.Errorf("received %d arguments to method '%s', expected %d", len(args), b.Name, b.InputCount()) diff --git a/v2/internal/binding/db.go b/v2/internal/binding/db.go index f22798680ba..1fc7e8c662e 100644 --- a/v2/internal/binding/db.go +++ b/v2/internal/binding/db.go @@ -34,7 +34,6 @@ func newDB() *DB { // GetMethodFromStore returns the method for the given package/struct/method names // nil is returned if any one of those does not exist func (d *DB) GetMethodFromStore(packageName string, structName string, methodName string) *BoundMethod { - // Lock the db whilst processing and unlock on return d.lock.RLock() defer d.lock.RUnlock() @@ -53,7 +52,6 @@ func (d *DB) GetMethodFromStore(packageName string, structName string, methodNam // GetMethod returns the method for the given qualified method name // qualifiedMethodName is "packagename.structname.methodname" func (d *DB) GetMethod(qualifiedMethodName string) *BoundMethod { - // Lock the db whilst processing and unlock on return d.lock.RLock() defer d.lock.RUnlock() @@ -72,7 +70,6 @@ func (d *DB) GetObfuscatedMethod(id int) *BoundMethod { // AddMethod adds the given method definition to the db using the given qualified path: packageName.structName.methodName func (d *DB) AddMethod(packageName string, structName string, methodName string, methodDefinition *BoundMethod) { - // Lock the db whilst processing and unlock on return d.lock.Lock() defer d.lock.Unlock() @@ -99,12 +96,10 @@ func (d *DB) AddMethod(packageName string, structName string, methodName string, // Store in the methodMap key := packageName + "." + structName + "." + methodName d.methodMap[key] = methodDefinition - } // ToJSON converts the method map to JSON func (d *DB) ToJSON() (string, error) { - // Lock the db whilst processing and unlock on return d.lock.RLock() defer d.lock.RUnlock() @@ -120,8 +115,7 @@ func (d *DB) ToJSON() (string, error) { // UpdateObfuscatedCallMap sets up the secure call mappings func (d *DB) UpdateObfuscatedCallMap() map[string]int { - - var mappings = make(map[string]int) + mappings := make(map[string]int) // Iterate map keys and sort them keys := make([]string, 0, len(d.methodMap)) diff --git a/v2/internal/binding/generate.go b/v2/internal/binding/generate.go index 8416aade1ca..02a0bd29272 100644 --- a/v2/internal/binding/generate.go +++ b/v2/internal/binding/generate.go @@ -15,12 +15,14 @@ import ( "github.com/leaanthony/slicer" ) -var mapRegex *regexp.Regexp -var keyPackageIndex int -var keyTypeIndex int -var valueArrayIndex int -var valuePackageIndex int -var valueTypeIndex int +var ( + mapRegex *regexp.Regexp + keyPackageIndex int + keyTypeIndex int + valueArrayIndex int + valuePackageIndex int + valueTypeIndex int +) func init() { mapRegex = regexp.MustCompile(`(?:map\[(?:(?P\w+)\.)?(?P\w+)])?(?P\[])?(?:\*?(?P\w+)\.)?(?P.+)`) @@ -81,9 +83,7 @@ func (b *Bindings) GenerateGoBindings(baseDir string) error { } else { jsoutput.WriteString(fmt.Sprintf(" return window['go']['%s']['%s']['%s'](%s);", packageName, structName, methodName, argsString)) } - jsoutput.WriteString("\n") - jsoutput.WriteString(fmt.Sprintf("}")) - jsoutput.WriteString("\n") + jsoutput.WriteString("\n}\n") // Generate TS tsBody.WriteString(fmt.Sprintf("\nexport function %s(", methodName)) @@ -127,12 +127,12 @@ func (b *Bindings) GenerateGoBindings(baseDir string) error { tsContent.WriteString(tsBody.String()) jsfilename := filepath.Join(packageDir, structName+".js") - err = os.WriteFile(jsfilename, jsoutput.Bytes(), 0755) + err = os.WriteFile(jsfilename, jsoutput.Bytes(), 0o755) if err != nil { return err } tsfilename := filepath.Join(packageDir, structName+".d.ts") - err = os.WriteFile(tsfilename, tsContent.Bytes(), 0755) + err = os.WriteFile(tsfilename, tsContent.Bytes(), 0o755) if err != nil { return err } @@ -186,7 +186,7 @@ func goTypeToJSDocType(input string, importNamespaces *slicer.StringSlicer) stri valueArray := matches[valueArrayIndex] valuePackage := matches[valuePackageIndex] valueType := matches[valueTypeIndex] - //fmt.Printf("input=%s, keyPackage=%s, keyType=%s, valueArray=%s, valuePackage=%s, valueType=%s\n", + // fmt.Printf("input=%s, keyPackage=%s, keyType=%s, valueArray=%s, valuePackage=%s, valueType=%s\n", // input, // keyPackage, // keyType, diff --git a/v2/internal/binding/reflect.go b/v2/internal/binding/reflect.go old mode 100755 new mode 100644 index 66a9cf7bdea..263af29d1e9 --- a/v2/internal/binding/reflect.go +++ b/v2/internal/binding/reflect.go @@ -25,7 +25,6 @@ func isStruct(value interface{}) bool { } func (b *Bindings) getMethods(value interface{}) ([]*BoundMethod, error) { - // Create result placeholder var result []*BoundMethod @@ -169,7 +168,6 @@ func getPackageName(in string) string { func getSplitReturn(in string) (string, string) { result := strings.Split(in, ".") return result[0], result[1] - } func hasElements(typ reflect.Type) bool { diff --git a/v2/internal/frontend/calls.go b/v2/internal/frontend/calls.go index 3983c24bfcd..5401106bc5f 100644 --- a/v2/internal/frontend/calls.go +++ b/v2/internal/frontend/calls.go @@ -1,5 +1,5 @@ package frontend type Calls interface { - Callback(string) + Callback(message string) } diff --git a/v2/internal/frontend/desktop/darwin/callbacks.go b/v2/internal/frontend/desktop/darwin/callbacks.go index 7d930a2f9e5..ab0d18e47ab 100644 --- a/v2/internal/frontend/desktop/darwin/callbacks.go +++ b/v2/internal/frontend/desktop/darwin/callbacks.go @@ -12,6 +12,7 @@ package darwin #include */ import "C" + import ( "errors" "strconv" @@ -20,7 +21,6 @@ import ( ) func (f *Frontend) handleCallback(menuItemID uint) error { - menuItem := getMenuItemForID(menuItemID) if menuItem == nil { return errors.New("unknown menuItem ID: " + strconv.Itoa(int(menuItemID))) diff --git a/v2/internal/frontend/desktop/darwin/clipboard.go b/v2/internal/frontend/desktop/darwin/clipboard.go index eea6c79aedb..c40ba877175 100644 --- a/v2/internal/frontend/desktop/darwin/clipboard.go +++ b/v2/internal/frontend/desktop/darwin/clipboard.go @@ -16,7 +16,6 @@ func (f *Frontend) ClipboardGetText() (string, error) { } func (f *Frontend) ClipboardSetText(text string) error { - copyCmd := exec.Command("pbcopy") in, err := copyCmd.StdinPipe() if err != nil { diff --git a/v2/internal/frontend/desktop/darwin/dialog.go b/v2/internal/frontend/desktop/darwin/dialog.go index c6be559cbec..66bb2f13a6c 100644 --- a/v2/internal/frontend/desktop/darwin/dialog.go +++ b/v2/internal/frontend/desktop/darwin/dialog.go @@ -11,6 +11,7 @@ package darwin #import "WailsContext.h" */ import "C" + import ( "encoding/json" "fmt" @@ -23,10 +24,12 @@ import ( ) // Obj-C dialog methods send the response to this channel -var messageDialogResponse = make(chan int) -var openFileDialogResponse = make(chan string) -var saveFileDialogResponse = make(chan string) -var dialogLock sync.Mutex +var ( + messageDialogResponse = make(chan int) + openFileDialogResponse = make(chan string) + saveFileDialogResponse = make(chan string) + dialogLock sync.Mutex +) // OpenDirectoryDialog prompts the user to select a directory func (f *Frontend) OpenDirectoryDialog(options frontend.OpenDialogOptions) (string, error) { @@ -74,7 +77,7 @@ func (f *Frontend) openDialog(options *frontend.OpenDialogOptions, multiple bool filters := filterStrings.Join(";") C.OpenFileDialog(f.mainWindow.context, title, defaultFilename, defaultDirectory, allowDirectories, allowFiles, canCreateDirectories, treatPackagesAsDirectories, resolveAliases, showHiddenFiles, allowMultipleFileSelection, c.String(filters)) - var result = <-openFileDialogResponse + result := <-openFileDialogResponse var parsedResults []string err := json.Unmarshal([]byte(result), &parsedResults) @@ -130,7 +133,7 @@ func (f *Frontend) SaveFileDialog(options frontend.SaveDialogOptions) (string, e filters := filterStrings.Join(";") C.SaveFileDialog(f.mainWindow.context, title, defaultFilename, defaultDirectory, canCreateDirectories, treatPackagesAsDirectories, showHiddenFiles, c.String(filters)) - var result = <-saveFileDialogResponse + result := <-saveFileDialogResponse return result, nil } @@ -165,7 +168,7 @@ func (f *Frontend) MessageDialog(options frontend.MessageDialogOptions) (string, C.MessageDialog(f.mainWindow.context, dialogType, title, message, buttons[0], buttons[1], buttons[2], buttons[3], defaultButton, cancelButton, iconData, iconDataLength) - var result = <-messageDialogResponse + result := <-messageDialogResponse selectedC := buttons[result] var selected string diff --git a/v2/internal/frontend/desktop/darwin/frontend.go b/v2/internal/frontend/desktop/darwin/frontend.go index c792ae9c88e..bc8a4c64c34 100644 --- a/v2/internal/frontend/desktop/darwin/frontend.go +++ b/v2/internal/frontend/desktop/darwin/frontend.go @@ -14,6 +14,7 @@ package darwin #include */ import "C" + import ( "context" "encoding/json" @@ -36,15 +37,16 @@ import ( const startURL = "wails://wails/" -var messageBuffer = make(chan string, 100) -var requestBuffer = make(chan webview.Request, 100) -var callbackBuffer = make(chan uint, 10) -var openFilepathBuffer = make(chan string, 100) -var openUrlBuffer = make(chan string, 100) -var secondInstanceBuffer = make(chan options.SecondInstanceData, 1) +var ( + messageBuffer = make(chan string, 100) + requestBuffer = make(chan webview.Request, 100) + callbackBuffer = make(chan uint, 10) + openFilepathBuffer = make(chan string, 100) + openUrlBuffer = make(chan string, 100) + secondInstanceBuffer = make(chan options.SecondInstanceData, 1) +) type Frontend struct { - // Context ctx context.Context @@ -153,6 +155,7 @@ func (f *Frontend) startRequestProcessor() { f.assets.ServeWebViewRequest(request) } } + func (f *Frontend) startCallbackProcessor() { for callback := range callbackBuffer { err := f.handleCallback(callback) @@ -171,15 +174,12 @@ func (f *Frontend) WindowReloadApp() { } func (f *Frontend) WindowSetSystemDefaultTheme() { - return } func (f *Frontend) WindowSetLightTheme() { - return } func (f *Frontend) WindowSetDarkTheme() { - return } func (f *Frontend) Run(ctx context.Context) error { @@ -189,8 +189,8 @@ func (f *Frontend) Run(ctx context.Context) error { SetupSingleInstance(f.frontendOptions.SingleInstanceLock.UniqueId) } - var _debug = ctx.Value("debug") - var _devtoolsEnabled = ctx.Value("devtoolsEnabled") + _debug := ctx.Value("debug") + _devtoolsEnabled := ctx.Value("devtoolsEnabled") if _debug != nil { f.debug = _debug.(bool) @@ -215,6 +215,7 @@ func (f *Frontend) Run(ctx context.Context) error { func (f *Frontend) WindowCenter() { f.mainWindow.Center() } + func (f *Frontend) WindowSetAlwaysOnTop(onTop bool) { f.mainWindow.SetAlwaysOnTop(onTop) } @@ -222,6 +223,7 @@ func (f *Frontend) WindowSetAlwaysOnTop(onTop bool) { func (f *Frontend) WindowSetPosition(x, y int) { f.mainWindow.SetPosition(x, y) } + func (f *Frontend) WindowGetPosition() (int, int) { return f.mainWindow.GetPosition() } @@ -253,6 +255,7 @@ func (f *Frontend) WindowShow() { func (f *Frontend) WindowHide() { f.mainWindow.Hide() } + func (f *Frontend) Show() { f.mainWindow.ShowApplication() } @@ -260,18 +263,23 @@ func (f *Frontend) Show() { func (f *Frontend) Hide() { f.mainWindow.HideApplication() } + func (f *Frontend) WindowMaximise() { f.mainWindow.Maximise() } + func (f *Frontend) WindowToggleMaximise() { f.mainWindow.ToggleMaximise() } + func (f *Frontend) WindowUnmaximise() { f.mainWindow.UnMaximise() } + func (f *Frontend) WindowMinimise() { f.mainWindow.Minimise() } + func (f *Frontend) WindowUnminimise() { f.mainWindow.UnMinimise() } @@ -279,6 +287,7 @@ func (f *Frontend) WindowUnminimise() { func (f *Frontend) WindowSetMinSize(width int, height int) { f.mainWindow.SetMinSize(width, height) } + func (f *Frontend) WindowSetMaxSize(width int, height int) { f.mainWindow.SetMaxSize(width, height) } @@ -345,7 +354,6 @@ func (f *Frontend) Notify(name string, data ...interface{}) { } func (f *Frontend) processMessage(message string) { - if message == "DomReady" { if f.frontendOptions.OnDomReady != nil { f.frontendOptions.OnDomReady(f.ctx) @@ -388,7 +396,6 @@ func (f *Frontend) processMessage(message string) { f.logger.Info("Unknown message returned from dispatcher: %+v", result) } }() - } func (f *Frontend) ProcessOpenFileEvent(filePath string) { diff --git a/v2/internal/frontend/desktop/darwin/inspector.go b/v2/internal/frontend/desktop/darwin/inspector.go index 8499745d0fe..dc3f08969a0 100644 --- a/v2/internal/frontend/desktop/darwin/inspector.go +++ b/v2/internal/frontend/desktop/darwin/inspector.go @@ -7,5 +7,4 @@ import ( ) func showInspector(_ unsafe.Pointer) { - } diff --git a/v2/internal/frontend/desktop/darwin/menu.go b/v2/internal/frontend/desktop/darwin/menu.go index 08090f89a2c..24dbe32017d 100644 --- a/v2/internal/frontend/desktop/darwin/menu.go +++ b/v2/internal/frontend/desktop/darwin/menu.go @@ -13,6 +13,7 @@ package darwin #include */ import "C" + import ( "unsafe" @@ -122,7 +123,6 @@ func processMenuItem(parent *NSMenu, menuItem *menu.MenuItem) *MenuItem { } return parent.AddMenuItem(menuItem) - } func (f *Frontend) MenuSetApplicationMenu(menu *menu.Menu) { diff --git a/v2/internal/frontend/desktop/darwin/menuitem.go b/v2/internal/frontend/desktop/darwin/menuitem.go index 00ad57aa37f..64aab84a9a7 100644 --- a/v2/internal/frontend/desktop/darwin/menuitem.go +++ b/v2/internal/frontend/desktop/darwin/menuitem.go @@ -13,16 +13,19 @@ package darwin #include */ import "C" + import ( "log" "math" "sync" ) -var menuItemToID = make(map[*MenuItem]uint) -var idToMenuItem = make(map[uint]*MenuItem) -var menuItemLock sync.Mutex -var menuItemIDCounter uint = 0 +var ( + menuItemToID = make(map[*MenuItem]uint) + idToMenuItem = make(map[uint]*MenuItem) + menuItemLock sync.Mutex + menuItemIDCounter uint = 0 +) func createMenuItemID(item *MenuItem) uint { menuItemLock.Lock() diff --git a/v2/internal/frontend/desktop/darwin/screen.go b/v2/internal/frontend/desktop/darwin/screen.go index a96a8efa743..bd64a31f9eb 100644 --- a/v2/internal/frontend/desktop/darwin/screen.go +++ b/v2/internal/frontend/desktop/darwin/screen.go @@ -82,6 +82,7 @@ Screen GetNthScreen(int nth, void *inctx){ */ import "C" + import ( "unsafe" diff --git a/v2/internal/frontend/desktop/darwin/single_instance.go b/v2/internal/frontend/desktop/darwin/single_instance.go index 012baef0280..970f1f431f5 100644 --- a/v2/internal/frontend/desktop/darwin/single_instance.go +++ b/v2/internal/frontend/desktop/darwin/single_instance.go @@ -10,21 +10,22 @@ package darwin */ import "C" + import ( "encoding/json" "fmt" - "github.com/wailsapp/wails/v2/pkg/options" "os" "strings" "syscall" "unsafe" + + "github.com/wailsapp/wails/v2/pkg/options" ) func SetupSingleInstance(uniqueID string) { lockFilePath := getTempDir() lockFileName := uniqueID + ".lock" _, err := createLockFile(lockFilePath + "/" + lockFileName) - // if lockFile exist – send notification to second instance if err != nil { c := NewCalloc() @@ -63,7 +64,7 @@ func HandleSecondInstanceData(secondInstanceMessage *C.char) { // exclusive lock on it. If the file already exists AND is still locked, it will // fail. func createLockFile(filename string) (*os.File, error) { - file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0600) + file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { fmt.Printf("Failed to open lockfile %s: %s", filename, err) return nil, err diff --git a/v2/internal/frontend/desktop/darwin/window.go b/v2/internal/frontend/desktop/darwin/window.go index 740848df144..236026ee207 100644 --- a/v2/internal/frontend/desktop/darwin/window.go +++ b/v2/internal/frontend/desktop/darwin/window.go @@ -13,6 +13,7 @@ package darwin #include */ import "C" + import ( "log" "runtime" @@ -46,7 +47,6 @@ func bool2CboolPtr(value bool) *C.bool { } func NewWindow(frontendOptions *options.App, debug bool, devtools bool) *Window { - c := NewCalloc() defer c.Free() @@ -196,6 +196,7 @@ func (w *Window) SetTitle(title string) { func (w *Window) Maximise() { C.Maximise(w.context) } + func (w *Window) ToggleMaximise() { C.ToggleMaximise(w.context) } @@ -251,6 +252,7 @@ func (w *Window) Show() { func (w *Window) Hide() { C.Hide(w.context) } + func (w *Window) ShowApplication() { C.ShowApplication(w.context) } diff --git a/v2/internal/frontend/desktop/windows/dialog.go b/v2/internal/frontend/desktop/windows/dialog.go index 1ca422b7199..7aca4289438 100644 --- a/v2/internal/frontend/desktop/windows/dialog.go +++ b/v2/internal/frontend/desktop/windows/dialog.go @@ -47,7 +47,7 @@ func (f *Frontend) OpenDirectoryDialog(options frontend.OpenDialogOptions) (stri return cfd.NewSelectFolderDialog(config) }, false) - if err != nil && err != cfd.ErrorCancelled { + if err != nil && err != cfd.ErrCancelled { return "", err } return result.(string), nil @@ -72,7 +72,7 @@ func (f *Frontend) OpenFileDialog(options frontend.OpenDialogOptions) (string, e return cfd.NewOpenFileDialog(config) }, false) - if err != nil && err != cfd.ErrorCancelled { + if err != nil && err != cfd.ErrCancelled { return "", err } return result.(string), nil @@ -99,7 +99,7 @@ func (f *Frontend) OpenMultipleFilesDialog(options frontend.OpenDialogOptions) ( return cfd.NewOpenMultipleFilesDialog(config) }, true) - if err != nil && err != cfd.ErrorCancelled { + if err != nil && err != cfd.ErrCancelled { return nil, err } return result.([]string), nil @@ -126,7 +126,7 @@ func (f *Frontend) SaveFileDialog(options frontend.SaveDialogOptions) (string, e return cfd.NewSaveFileDialog(config) }, false) - if err != nil && err != cfd.ErrorCancelled { + if err != nil && err != cfd.ErrCancelled { return "", err } return result.(string), nil diff --git a/v2/internal/frontend/dispatcher/calls.go b/v2/internal/frontend/dispatcher/calls.go index 491d17fe2bd..ba10629137f 100644 --- a/v2/internal/frontend/dispatcher/calls.go +++ b/v2/internal/frontend/dispatcher/calls.go @@ -15,7 +15,6 @@ type callMessage struct { } func (d *Dispatcher) processCallMessage(message string, sender frontend.Frontend) (string, error) { - var payload callMessage err := json.Unmarshal([]byte(message[1:]), &payload) if err != nil { diff --git a/v2/internal/frontend/dispatcher/events.go b/v2/internal/frontend/dispatcher/events.go index 11680651bb1..12fe7b89e04 100644 --- a/v2/internal/frontend/dispatcher/events.go +++ b/v2/internal/frontend/dispatcher/events.go @@ -3,6 +3,7 @@ package dispatcher import ( "encoding/json" "errors" + "github.com/wailsapp/wails/v2/internal/frontend" ) diff --git a/v2/internal/frontend/dispatcher/securecalls.go b/v2/internal/frontend/dispatcher/securecalls.go index 40accaa26e6..8cdcdfb8507 100644 --- a/v2/internal/frontend/dispatcher/securecalls.go +++ b/v2/internal/frontend/dispatcher/securecalls.go @@ -3,6 +3,7 @@ package dispatcher import ( "encoding/json" "fmt" + "github.com/wailsapp/wails/v2/internal/frontend" ) @@ -13,7 +14,6 @@ type secureCallMessage struct { } func (d *Dispatcher) processSecureCallMessage(message string, sender frontend.Frontend) (string, error) { - var payload secureCallMessage err := json.Unmarshal([]byte(message[1:]), &payload) if err != nil { diff --git a/v2/internal/frontend/dispatcher/systemcalls.go b/v2/internal/frontend/dispatcher/systemcalls.go index b810d9beaf1..b090a416ef6 100644 --- a/v2/internal/frontend/dispatcher/systemcalls.go +++ b/v2/internal/frontend/dispatcher/systemcalls.go @@ -4,9 +4,10 @@ import ( "encoding/json" "errors" "fmt" - "github.com/wailsapp/wails/v2/pkg/runtime" "strings" + "github.com/wailsapp/wails/v2/pkg/runtime" + "github.com/wailsapp/wails/v2/internal/frontend" ) @@ -23,7 +24,6 @@ type size struct { } func (d *Dispatcher) processSystemCall(payload callMessage, sender frontend.Frontend) (interface{}, error) { - // Strip prefix name := strings.TrimPrefix(payload.Name, systemCallPrefix) @@ -64,5 +64,4 @@ func (d *Dispatcher) processSystemCall(payload callMessage, sender frontend.Fron default: return nil, fmt.Errorf("unknown systemcall message: %s", payload.Name) } - } diff --git a/v2/internal/frontend/frontend.go b/v2/internal/frontend/frontend.go index 27eb4a2e755..6b2ccbcae41 100644 --- a/v2/internal/frontend/frontend.go +++ b/v2/internal/frontend/frontend.go @@ -77,7 +77,7 @@ type MessageDialogOptions struct { } type Frontend interface { - Run(context.Context) error + Run(ctx context.Context) error RunMainLoop() ExecJS(js string) Hide() @@ -123,7 +123,7 @@ type Frontend interface { WindowClose() WindowPrint() - //Screen + // Screen ScreenGetAll() ([]Screen, error) // Menus diff --git a/v2/internal/frontend/runtime/events.go b/v2/internal/frontend/runtime/events.go index ac9d6299c3f..1f2e0a6e4b7 100644 --- a/v2/internal/frontend/runtime/events.go +++ b/v2/internal/frontend/runtime/events.go @@ -143,7 +143,7 @@ func (e *Events) notifyBackend(eventName string, data ...interface{}) { } // Do we have items to delete? - if itemsToDelete == true { + if itemsToDelete { // Create a new Listeners slice var newListeners []*eventListener diff --git a/v2/internal/fs/fs.go b/v2/internal/fs/fs.go index 5bfa71b1c0f..5662c020c01 100644 --- a/v2/internal/fs/fs.go +++ b/v2/internal/fs/fs.go @@ -2,6 +2,7 @@ package fs import ( "crypto/md5" + "encoding/hex" "fmt" "io" "io/fs" @@ -27,14 +28,14 @@ func RelativeToCwd(relativePath string) (string, error) { // Mkdir will create the given directory func Mkdir(dirname string) error { - return os.Mkdir(dirname, 0755) + return os.Mkdir(dirname, 0o755) } // MkDirs creates the given nested directories. // Returns error on failure func MkDirs(fullPath string, mode ...os.FileMode) error { var perms os.FileMode - perms = 0755 + perms = 0o755 if len(mode) == 1 { perms = mode[0] } @@ -111,7 +112,7 @@ func RelativePath(relativepath string, optionalpaths ...string) string { // I'm allowing this for 1 reason only: It's fatal if the path // supplied is wrong as it's only used internally in Wails. If we get // that path wrong, we should know about it immediately. The other reason is - // that it cuts down a ton of unnecassary error handling. + // that it cuts down a ton of unnecessary error handling. panic(err) } return result @@ -141,7 +142,7 @@ func MD5File(filename string) (string, error) { return "", err } - return fmt.Sprintf("%x", h.Sum(nil)), nil + return hex.EncodeToString(h.Sum(nil)), nil } // MustMD5File will call MD5File and abort the program on error @@ -157,7 +158,7 @@ func MustMD5File(filename string) string { // MustWriteString will attempt to write the given data to the given filename // It will abort the program in the event of a failure func MustWriteString(filename string, data string) { - err := os.WriteFile(filename, []byte(data), 0755) + err := os.WriteFile(filename, []byte(data), 0o755) if err != nil { fatal("Unable to write file", filename, ":", err.Error()) os.Exit(1) @@ -194,7 +195,6 @@ func GetSubdirectories(rootDir string) (*slicer.StringSlicer, error) { } func DirIsEmpty(dir string) (bool, error) { - // CREDIT: https://stackoverflow.com/a/30708914/8325411 f, err := os.Open(dir) if err != nil { @@ -284,7 +284,6 @@ func SetPermissions(dir string, perm os.FileMode) error { // Symlinks are ignored and skipped. // Credit: https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04 func CopyDirExtended(src string, dst string, ignore []string) (err error) { - ignoreList := slicer.String(ignore) src = filepath.Clean(src) dst = filepath.Clean(dst) @@ -382,7 +381,6 @@ func FindPathToFile(fsys fs.FS, file string) (string, error) { // FindFileInParents searches for a file in the current directory and all parent directories. // Returns the absolute path to the file if found, otherwise an empty string func FindFileInParents(path string, filename string) string { - // Check for bad paths if _, err := os.Stat(path); err != nil { return "" diff --git a/v2/internal/github/github.go b/v2/internal/github/github.go index db3b70c5850..c16e1d9dda4 100644 --- a/v2/internal/github/github.go +++ b/v2/internal/github/github.go @@ -3,13 +3,14 @@ package github import ( "encoding/json" "fmt" - "github.com/charmbracelet/glamour" "io" "net/http" "net/url" "runtime" "sort" "strings" + + "github.com/charmbracelet/glamour" ) func GetReleaseNotes(tagVersion string, noColour bool) string { @@ -57,7 +58,6 @@ func GetReleaseNotes(tagVersion string, noColour bool) string { // GetVersionTags gets the list of tags on the Wails repo // It returns a list of sorted tags in descending order func GetVersionTags() ([]*SemanticVersion, error) { - result := []*SemanticVersion{} var err error @@ -97,7 +97,6 @@ func GetVersionTags() ([]*SemanticVersion, error) { // GetLatestStableRelease gets the latest stable release on GitHub func GetLatestStableRelease() (result *SemanticVersion, err error) { - tags, err := GetVersionTags() if err != nil { return nil, err @@ -114,7 +113,6 @@ func GetLatestStableRelease() (result *SemanticVersion, err error) { // GetLatestPreRelease gets the latest prerelease on GitHub func GetLatestPreRelease() (result *SemanticVersion, err error) { - tags, err := GetVersionTags() if err != nil { return nil, err diff --git a/v2/internal/go-common-file-dialog/cfd/CommonFileDialog_nonWindows.go b/v2/internal/go-common-file-dialog/cfd/CommonFileDialog_nonWindows.go index 3ab96985059..04c7cbcfef2 100644 --- a/v2/internal/go-common-file-dialog/cfd/CommonFileDialog_nonWindows.go +++ b/v2/internal/go-common-file-dialog/cfd/CommonFileDialog_nonWindows.go @@ -5,24 +5,24 @@ package cfd import "fmt" -var unsupportedError = fmt.Errorf("common file dialogs are only available on windows") +var errUnsupported = fmt.Errorf("common file dialogs are only available on windows") // TODO doc func NewOpenFileDialog(config DialogConfig) (OpenFileDialog, error) { - return nil, unsupportedError + return nil, errUnsupported } // TODO doc func NewOpenMultipleFilesDialog(config DialogConfig) (OpenMultipleFilesDialog, error) { - return nil, unsupportedError + return nil, errUnsupported } // TODO doc func NewSelectFolderDialog(config DialogConfig) (SelectFolderDialog, error) { - return nil, unsupportedError + return nil, errUnsupported } // TODO doc func NewSaveFileDialog(config DialogConfig) (SaveFileDialog, error) { - return nil, unsupportedError + return nil, errUnsupported } diff --git a/v2/internal/go-common-file-dialog/cfd/errors.go b/v2/internal/go-common-file-dialog/cfd/errors.go index c097c8eb2f4..6f21fedbfb1 100644 --- a/v2/internal/go-common-file-dialog/cfd/errors.go +++ b/v2/internal/go-common-file-dialog/cfd/errors.go @@ -2,6 +2,4 @@ package cfd import "errors" -var ( - ErrorCancelled = errors.New("cancelled by user") -) +var ErrCancelled = errors.New("cancelled by user") diff --git a/v2/internal/go-common-file-dialog/cfd/iFileOpenDialog.go b/v2/internal/go-common-file-dialog/cfd/iFileOpenDialog.go index 8c82cda2c6d..4c080c916d4 100644 --- a/v2/internal/go-common-file-dialog/cfd/iFileOpenDialog.go +++ b/v2/internal/go-common-file-dialog/cfd/iFileOpenDialog.go @@ -178,7 +178,7 @@ func (vtbl *iFileOpenDialogVtbl) getResultsStrings(objPtr unsafe.Pointer) ([]str return nil, err } if shellItemArray == nil { - return nil, ErrorCancelled + return nil, ErrCancelled } defer shellItemArray.vtbl.release(unsafe.Pointer(shellItemArray)) count, err := shellItemArray.vtbl.getCount(unsafe.Pointer(shellItemArray)) diff --git a/v2/internal/go-common-file-dialog/cfd/iShellItemArray.go b/v2/internal/go-common-file-dialog/cfd/iShellItemArray.go index 84f26fa2008..d904e72b21c 100644 --- a/v2/internal/go-common-file-dialog/cfd/iShellItemArray.go +++ b/v2/internal/go-common-file-dialog/cfd/iShellItemArray.go @@ -60,7 +60,7 @@ func (vtbl *iShellItemArrayVtbl) getItemAt(objPtr unsafe.Pointer, index uintptr) return "", err } if shellItem == nil { - return "", ErrorCancelled + return "", ErrCancelled } defer shellItem.vtbl.release(unsafe.Pointer(shellItem)) return shellItem.vtbl.getDisplayName(unsafe.Pointer(shellItem)) diff --git a/v2/internal/go-common-file-dialog/cfd/vtblCommonFunc.go b/v2/internal/go-common-file-dialog/cfd/vtblCommonFunc.go index a9210001017..929d5a2b7ac 100644 --- a/v2/internal/go-common-file-dialog/cfd/vtblCommonFunc.go +++ b/v2/internal/go-common-file-dialog/cfd/vtblCommonFunc.go @@ -179,7 +179,7 @@ func (vtbl *iFileDialogVtbl) getResultString(objPtr unsafe.Pointer) (string, err return "", err } if shellItem == nil { - return "", ErrorCancelled + return "", ErrCancelled } defer shellItem.vtbl.release(unsafe.Pointer(shellItem)) return shellItem.vtbl.getDisplayName(unsafe.Pointer(shellItem)) diff --git a/v2/internal/go-common-file-dialog/cfdutil/CFDUtil.go b/v2/internal/go-common-file-dialog/cfdutil/CFDUtil.go index bde52d7439a..655266bc3fb 100644 --- a/v2/internal/go-common-file-dialog/cfdutil/CFDUtil.go +++ b/v2/internal/go-common-file-dialog/cfdutil/CFDUtil.go @@ -10,7 +10,9 @@ func ShowOpenFileDialog(config cfd.DialogConfig) (string, error) { if err != nil { return "", err } - defer dialog.Release() + defer func() { + _ = dialog.Release() + }() return dialog.ShowAndGetResult() } @@ -20,7 +22,9 @@ func ShowOpenMultipleFilesDialog(config cfd.DialogConfig) ([]string, error) { if err != nil { return nil, err } - defer dialog.Release() + defer func() { + _ = dialog.Release() + }() return dialog.ShowAndGetResults() } @@ -30,7 +34,9 @@ func ShowPickFolderDialog(config cfd.DialogConfig) (string, error) { if err != nil { return "", err } - defer dialog.Release() + defer func() { + _ = dialog.Release() + }() return dialog.ShowAndGetResult() } @@ -40,6 +46,8 @@ func ShowSaveFileDialog(config cfd.DialogConfig) (string, error) { if err != nil { return "", err } - defer dialog.Release() + defer func() { + _ = dialog.Release() + }() return dialog.ShowAndGetResult() } diff --git a/v2/internal/gomod/gomod.go b/v2/internal/gomod/gomod.go index 8ab7e0b6654..c38e60f0bac 100644 --- a/v2/internal/gomod/gomod.go +++ b/v2/internal/gomod/gomod.go @@ -2,6 +2,7 @@ package gomod import ( "fmt" + "github.com/Masterminds/semver" "golang.org/x/mod/modfile" ) diff --git a/v2/internal/gomod/gomod_data_unix.go b/v2/internal/gomod/gomod_data_unix.go index f3a5e04c347..c6004f4862f 100644 --- a/v2/internal/gomod/gomod_data_unix.go +++ b/v2/internal/gomod/gomod_data_unix.go @@ -10,6 +10,7 @@ require github.com/wailsapp/wails/v2 v2.0.0-beta.7 //replace github.com/wailsapp/wails/v2 v2.0.0-beta.7 => /home/lea/wails/v2 ` + const basicUpdated string = `module changeme go 1.17 @@ -29,6 +30,7 @@ require ( //replace github.com/wailsapp/wails/v2 v2.0.0-beta.7 => /home/lea/wails/v2 ` + const multilineReplace = `module changeme go 1.17 @@ -98,6 +100,7 @@ require ( replace github.com/wailsapp/wails/v2 v2.0.0-beta.20 => /home/lea/wails/v2 ` + const multilineReplaceNoVersionUpdated = `module changeme go 1.17 @@ -108,6 +111,7 @@ require ( replace github.com/wailsapp/wails/v2 => /home/lea/wails/v2 ` + const multilineReplaceNoVersionBlockUpdated = `module changeme go 1.17 diff --git a/v2/internal/logger/custom_logger.go b/v2/internal/logger/custom_logger.go index 5e24aa0938d..51e07c0fc3d 100644 --- a/v2/internal/logger/custom_logger.go +++ b/v2/internal/logger/custom_logger.go @@ -86,7 +86,6 @@ func (l *customLogger) Warning(format string, args ...interface{}) { func (l *customLogger) Error(format string, args ...interface{}) { format = fmt.Sprintf("%s | %s", l.name, format) l.logger.Error(format, args...) - } // Fatal level logging. Works like Sprintf. diff --git a/v2/internal/logger/default_logger.go b/v2/internal/logger/default_logger.go index fe5c0538793..5c72ae20988 100644 --- a/v2/internal/logger/default_logger.go +++ b/v2/internal/logger/default_logger.go @@ -84,7 +84,6 @@ func (l *Logger) Info(format string, args ...interface{}) { if l.logLevel <= logger.INFO { l.output.Info(fmt.Sprintf(format, args...)) } - } // Warning level logging. Works like Sprintf. @@ -99,7 +98,6 @@ func (l *Logger) Error(format string, args ...interface{}) { if l.logLevel <= logger.ERROR { l.output.Error(fmt.Sprintf(format, args...)) } - } // Fatal level logging. Works like Sprintf. diff --git a/v2/internal/menumanager/applicationmenu.go b/v2/internal/menumanager/applicationmenu.go index 424834e5351..4446a00cbf7 100644 --- a/v2/internal/menumanager/applicationmenu.go +++ b/v2/internal/menumanager/applicationmenu.go @@ -3,7 +3,6 @@ package menumanager import "github.com/wailsapp/wails/v2/pkg/menu" func (m *Manager) SetApplicationMenu(applicationMenu *menu.Menu) error { - if applicationMenu == nil { return nil } @@ -38,7 +37,6 @@ func (m *Manager) UpdateApplicationMenu() (string, error) { } func (m *Manager) processApplicationMenu() error { - // Process the menu m.processedApplicationMenu = NewWailsMenu(m.applicationMenuItemMap, m.applicationMenu) m.processRadioGroups(m.processedApplicationMenu, m.applicationMenuItemMap) diff --git a/v2/internal/menumanager/contextmenu.go b/v2/internal/menumanager/contextmenu.go index 77c47891c00..f05bcdc49b8 100644 --- a/v2/internal/menumanager/contextmenu.go +++ b/v2/internal/menumanager/contextmenu.go @@ -23,7 +23,6 @@ func (t *ContextMenu) AsJSON() (string, error) { } func NewContextMenu(contextMenu *menu.ContextMenu) *ContextMenu { - result := &ContextMenu{ ID: contextMenu.ID, menu: contextMenu.Menu, @@ -37,7 +36,6 @@ func NewContextMenu(contextMenu *menu.ContextMenu) *ContextMenu { } func (m *Manager) AddContextMenu(contextMenu *menu.ContextMenu) { - newContextMenu := NewContextMenu(contextMenu) // Save the references diff --git a/v2/internal/menumanager/menuitemmap.go b/v2/internal/menumanager/menuitemmap.go index 790d5d06d6c..e4e291be6bb 100644 --- a/v2/internal/menumanager/menuitemmap.go +++ b/v2/internal/menumanager/menuitemmap.go @@ -2,8 +2,10 @@ package menumanager import ( "fmt" - "github.com/wailsapp/wails/v2/pkg/menu" + "strconv" "sync" + + "github.com/wailsapp/wails/v2/pkg/menu" ) // MenuItemMap holds a mapping between menuIDs and menu items @@ -48,14 +50,13 @@ func (m *MenuItemMap) Dump() { // GenerateMenuID returns a unique string ID for a menu item func (m *MenuItemMap) generateMenuID() string { m.menuIDCounterMutex.Lock() - result := fmt.Sprintf("%d", m.menuIDCounter) + result := strconv.FormatInt(m.menuIDCounter, 10) m.menuIDCounter++ m.menuIDCounterMutex.Unlock() return result } func (m *MenuItemMap) processMenuItem(item *menu.MenuItem) { - if item.SubMenu != nil { for _, submenuitem := range item.SubMenu.Items { m.processMenuItem(submenuitem) diff --git a/v2/internal/menumanager/menumanager.go b/v2/internal/menumanager/menumanager.go index ea793941591..0c6be0df234 100644 --- a/v2/internal/menumanager/menumanager.go +++ b/v2/internal/menumanager/menumanager.go @@ -2,11 +2,11 @@ package menumanager import ( "fmt" + "github.com/wailsapp/wails/v2/pkg/menu" ) type Manager struct { - // The application menu. applicationMenu *menu.Menu applicationMenuJSON string @@ -43,7 +43,6 @@ func (m *Manager) getMenuItemByID(menuMap *MenuItemMap, menuId string) *menu.Men } func (m *Manager) ProcessClick(menuID string, data string, menuType string, parentID string) error { - var menuItemMap *MenuItemMap switch menuType { @@ -93,7 +92,7 @@ func (m *Manager) ProcessClick(menuID string, data string, menuType string, pare // Create new Callback struct callbackData := &menu.CallbackData{ MenuItem: menuItem, - //ContextData: data, + // ContextData: data, } // Call back! diff --git a/v2/internal/menumanager/processedMenu.go b/v2/internal/menumanager/processedMenu.go index 8d886e19e89..0f2351846ab 100644 --- a/v2/internal/menumanager/processedMenu.go +++ b/v2/internal/menumanager/processedMenu.go @@ -2,6 +2,7 @@ package menumanager import ( "encoding/json" + "github.com/wailsapp/wails/v2/pkg/menu" "github.com/wailsapp/wails/v2/pkg/menu/keys" ) @@ -11,7 +12,7 @@ type ProcessedMenuItem struct { // Label is what appears as the menu text Label string `json:",omitempty"` // Role is a predefined menu type - //Role menu.Role `json:",omitempty"` + // Role menu.Role `json:",omitempty"` // Accelerator holds a representation of a key binding Accelerator *keys.Accelerator `json:",omitempty"` // Type of MenuItem, EG: Checkbox, Text, Separator, Radio, Submenu @@ -23,7 +24,7 @@ type ProcessedMenuItem struct { // Checked indicates if the item is selected (used by Checkbox and Radio types only) Checked bool `json:",omitempty"` // Submenu contains a list of menu items that will be shown as a submenu - //SubMenu []*MenuItem `json:"SubMenu,omitempty"` + // SubMenu []*MenuItem `json:"SubMenu,omitempty"` SubMenu *ProcessedMenu `json:",omitempty"` /* // Colour @@ -47,7 +48,6 @@ type ProcessedMenuItem struct { } func NewProcessedMenuItem(menuItemMap *MenuItemMap, menuItem *menu.MenuItem) *ProcessedMenuItem { - ID := menuItemMap.menuItemToIDMap[menuItem] // Parse ANSI text @@ -63,21 +63,21 @@ func NewProcessedMenuItem(menuItemMap *MenuItemMap, menuItem *menu.MenuItem) *Pr result := &ProcessedMenuItem{ ID: ID, Label: menuItem.Label, - //Role: menuItem.Role, + // Role: menuItem.Role, Accelerator: menuItem.Accelerator, Type: menuItem.Type, Disabled: menuItem.Disabled, Hidden: menuItem.Hidden, Checked: menuItem.Checked, SubMenu: nil, - //BackgroundColour: menuItem.BackgroundColour, - //FontSize: menuItem.FontSize, - //FontName: menuItem.FontName, - //Image: menuItem.Image, - //MacTemplateImage: menuItem.MacTemplateImage, - //MacAlternate: menuItem.MacAlternate, - //Tooltip: menuItem.Tooltip, - //StyledLabel: styledLabel, + // BackgroundColour: menuItem.BackgroundColour, + // FontSize: menuItem.FontSize, + // FontName: menuItem.FontName, + // Image: menuItem.Image, + // MacTemplateImage: menuItem.MacTemplateImage, + // MacAlternate: menuItem.MacAlternate, + // Tooltip: menuItem.Tooltip, + // StyledLabel: styledLabel, } if menuItem.SubMenu != nil { @@ -92,7 +92,6 @@ type ProcessedMenu struct { } func NewProcessedMenu(menuItemMap *MenuItemMap, menu *menu.Menu) *ProcessedMenu { - result := &ProcessedMenu{} if menu != nil { for _, item := range menu.Items { @@ -131,7 +130,6 @@ func NewWailsMenu(menuItemMap *MenuItemMap, menu *menu.Menu) *WailsMenu { } func (w *WailsMenu) AsJSON() (string, error) { - menuAsJSON, err := json.Marshal(w) if err != nil { return "", err @@ -150,7 +148,6 @@ func (w *WailsMenu) processRadioGroups() { } func (w *WailsMenu) processMenuItem(item *ProcessedMenuItem) { - switch item.Type { // We need to recurse submenus @@ -172,7 +169,6 @@ func (w *WailsMenu) processMenuItem(item *ProcessedMenuItem) { } func (w *WailsMenu) finaliseRadioGroup() { - // If we were processing a radio group, fix up the references if len(w.currentRadioGroup) > 0 { diff --git a/v2/internal/menumanager/traymenu.go b/v2/internal/menumanager/traymenu.go index aed5b05ace6..5efc4a86192 100644 --- a/v2/internal/menumanager/traymenu.go +++ b/v2/internal/menumanager/traymenu.go @@ -13,8 +13,10 @@ import ( "github.com/wailsapp/wails/v2/pkg/menu" ) -var trayMenuID int -var trayMenuIDMutex sync.Mutex +var ( + trayMenuID int + trayMenuIDMutex sync.Mutex +) func generateTrayID() string { var idStr string @@ -51,7 +53,6 @@ func (t *TrayMenu) AsJSON() (string, error) { } func NewTrayMenu(trayMenu *menu.TrayMenu) *TrayMenu { - // Parse ANSI text var styledLabel []*ansi.StyledText tempLabel := trayMenu.Label @@ -205,7 +206,6 @@ func (m *Manager) UpdateTrayMenuLabel(trayMenu *menu.TrayMenu) (string, error) { } return string(data), nil - } func (m *Manager) GetContextMenus() ([]string, error) { diff --git a/v2/internal/process/process.go b/v2/internal/process/process.go index 6d497ed8e67..18c9f45da36 100644 --- a/v2/internal/process/process.go +++ b/v2/internal/process/process.go @@ -25,7 +25,6 @@ func NewProcess(cmd string, args ...string) *Process { // Start the process func (p *Process) Start(exitCodeChannel chan int) error { - err := p.cmd.Start() if err != nil { return err diff --git a/v2/internal/project/project.go b/v2/internal/project/project.go index d42977fee51..34cbe88da59 100644 --- a/v2/internal/project/project.go +++ b/v2/internal/project/project.go @@ -12,7 +12,6 @@ import ( // Project holds the data related to a Wails project type Project struct { - /*** Application Data ***/ Name string `json:"name"` AssetDirectory string `json:"assetdir,omitempty"` @@ -144,11 +143,10 @@ func (p *Project) Save() error { if err != nil { return err } - return os.WriteFile(p.filename, data, 0755) + return os.WriteFile(p.filename, data, 0o755) } func (p *Project) setDefaults() { - if p.Path == "" { p.Path = lo.Must(os.Getwd()) } diff --git a/v2/internal/s/s.go b/v2/internal/s/s.go index 86536e24c0c..f363d6541fe 100644 --- a/v2/internal/s/s.go +++ b/v2/internal/s/s.go @@ -2,6 +2,7 @@ package s import ( "crypto/md5" + "encoding/hex" "fmt" "io" "io/ioutil" @@ -74,9 +75,10 @@ func CD(dir string) { checkError(err) log("CD %s [%s]", dir, CWD()) } + func MKDIR(path string, mode ...os.FileMode) { var perms os.FileMode - perms = 0755 + perms = 0o755 if len(mode) == 1 { perms = mode[0] } @@ -88,7 +90,7 @@ func MKDIR(path string, mode ...os.FileMode) { // ENDIR ensures that the path gets created if it doesn't exist func ENDIR(path string, mode ...os.FileMode) { var perms os.FileMode - perms = 0755 + perms = 0o755 if len(mode) == 1 { perms = mode[0] } @@ -210,17 +212,13 @@ func ISDIR(path string) bool { // ISDIREMPTY returns true if the given directory is empty func ISDIREMPTY(dir string) bool { - // CREDIT: https://stackoverflow.com/a/30708914/8325411 f, err := os.Open(dir) checkError(err) defer closefile(f) _, err = f.Readdirnames(1) // Or f.Readdir(1) - if err == io.EOF { - return true - } - return false + return err == io.EOF } // ISFILE returns true if the given file exists @@ -270,7 +268,7 @@ func LOADSTRING(filename string) string { // SAVEBYTES will create a file with the given string func SAVEBYTES(filename string, data []byte) { log("SAVEBYTES %s", filename) - err := os.WriteFile(filename, data, 0755) + err := os.WriteFile(filename, data, 0o755) checkError(err) } @@ -297,7 +295,7 @@ func MD5FILE(filename string) string { _, err = io.Copy(h, f) checkError(err) - return fmt.Sprintf("%x", h.Sum(nil)) + return hex.EncodeToString(h.Sum(nil)) } // Sub is the substitution type diff --git a/v2/internal/shell/shell.go b/v2/internal/shell/shell.go index badea2b3941..349e27bff7e 100644 --- a/v2/internal/shell/shell.go +++ b/v2/internal/shell/shell.go @@ -42,6 +42,7 @@ func (c *Command) Run() error { func (c *Command) Stdout() string { return c.stdo.String() } + func (c *Command) Stderr() string { return c.stde.String() } @@ -93,8 +94,5 @@ func RunCommandVerbose(directory string, command string, args ...string) error { // CommandExists returns true if the given command can be found on the shell func CommandExists(name string) bool { _, err := exec.LookPath(name) - if err != nil { - return false - } - return true + return err == nil } diff --git a/v2/internal/signal/signal.go b/v2/internal/signal/signal.go index 96e10bee683..fa797453f85 100644 --- a/v2/internal/signal/signal.go +++ b/v2/internal/signal/signal.go @@ -9,8 +9,10 @@ import ( var signalChannel = make(chan os.Signal, 2) -var callbacks []func() -var lock sync.Mutex +var ( + callbacks []func() + lock sync.Mutex +) func OnShutdown(callback func()) { lock.Lock() @@ -20,20 +22,17 @@ func OnShutdown(callback func()) { // Start the Signal Manager func Start() { - // Hook into interrupts gosignal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) // Spin off signal listener and wait for either a cancellation // or signal go func() { - select { - case <-signalChannel: - println("") - println("Ctrl+C detected. Shutting down...") - for _, callback := range callbacks { - callback() - } + <-signalChannel + println("") + println("Ctrl+C detected. Shutting down...") + for _, callback := range callbacks { + callback() } }() } diff --git a/v2/internal/staticanalysis/staticanalysis.go b/v2/internal/staticanalysis/staticanalysis.go index 0d8fb92d3f0..d5cc8c6e522 100644 --- a/v2/internal/staticanalysis/staticanalysis.go +++ b/v2/internal/staticanalysis/staticanalysis.go @@ -2,9 +2,10 @@ package staticanalysis import ( "go/ast" - "golang.org/x/tools/go/packages" "path/filepath" "strings" + + "golang.org/x/tools/go/packages" ) type EmbedDetails struct { diff --git a/v2/internal/system/packagemanager/pm.go b/v2/internal/system/packagemanager/pm.go index dfd39429984..bba45cd05ea 100644 --- a/v2/internal/system/packagemanager/pm.go +++ b/v2/internal/system/packagemanager/pm.go @@ -16,9 +16,9 @@ type packagemap = map[string][]*Package type PackageManager interface { Name() string Packages() packagemap - PackageInstalled(*Package) (bool, error) - PackageAvailable(*Package) (bool, error) - InstallCommand(*Package) string + PackageInstalled(pkg *Package) (bool, error) + PackageAvailable(pkg *Package) (bool, error) + InstallCommand(pkg *Package) string } // Dependency represents a system package that we require @@ -37,7 +37,6 @@ type DependencyList []*Dependency // InstallAllRequiredCommand returns the command you need to use to install all required dependencies func (d DependencyList) InstallAllRequiredCommand() string { - result := "" for _, dependency := range d { if !dependency.Installed && !dependency.Optional { @@ -50,7 +49,6 @@ func (d DependencyList) InstallAllRequiredCommand() string { // InstallAllOptionalCommand returns the command you need to use to install all optional dependencies func (d DependencyList) InstallAllOptionalCommand() string { - result := "" for _, dependency := range d { if !dependency.Installed && dependency.Optional { diff --git a/v2/internal/system/system.go b/v2/internal/system/system.go index a633989efc5..67453538fc0 100644 --- a/v2/internal/system/system.go +++ b/v2/internal/system/system.go @@ -9,12 +9,10 @@ import ( "github.com/wailsapp/wails/v2/internal/system/packagemanager" ) -var ( - IsAppleSilicon bool -) +var IsAppleSilicon bool // Info holds information about the current operating system, -// package manager and required dependancies +// package manager and required dependencies type Info struct { OS *operatingsystem.OS PM packagemanager.PackageManager @@ -23,7 +21,7 @@ type Info struct { // GetInfo scans the system for operating system details, // the system package manager and the status of required -// dependancies. +// dependencies. func GetInfo() (*Info, error) { var result Info err := result.discover() @@ -34,7 +32,6 @@ func GetInfo() (*Info, error) { } func checkNodejs() *packagemanager.Dependency { - // Check for Nodejs output, err := exec.Command("node", "-v").Output() installed := true @@ -58,7 +55,6 @@ func checkNodejs() *packagemanager.Dependency { } func checkNPM() *packagemanager.Dependency { - // Check for npm output, err := exec.Command("npm", "-version").Output() installed := true @@ -80,7 +76,6 @@ func checkNPM() *packagemanager.Dependency { } func checkUPX() *packagemanager.Dependency { - // Check for npm output, err := exec.Command("upx", "-V").Output() installed := true @@ -102,7 +97,6 @@ func checkUPX() *packagemanager.Dependency { } func checkNSIS() *packagemanager.Dependency { - // Check for nsis installer output, err := exec.Command("makensis", "-VERSION").Output() installed := true @@ -141,7 +135,6 @@ func checkLibrary(name string) func() *packagemanager.Dependency { } func checkDocker() *packagemanager.Dependency { - // Check for npm output, err := exec.Command("docker", "version").Output() installed := true diff --git a/v2/internal/typescriptify/typescriptify.go b/v2/internal/typescriptify/typescriptify.go index b14059a51af..bb72e6fb8b5 100644 --- a/v2/internal/typescriptify/typescriptify.go +++ b/v2/internal/typescriptify/typescriptify.go @@ -156,10 +156,10 @@ func (t *TypeScriptify) deepFields(typeOf reflect.Type) []reflect.StructField { kind := f.Type.Kind() isPointer := kind == reflect.Ptr && f.Type.Elem().Kind() == reflect.Struct if f.Anonymous && kind == reflect.Struct { - //fmt.Println(v.Interface()) + // fmt.Println(v.Interface()) fields = append(fields, t.deepFields(f.Type)...) } else if f.Anonymous && isPointer { - //fmt.Println(v.Interface()) + // fmt.Println(v.Interface()) fields = append(fields, t.deepFields(f.Type.Elem())...) } else { // Check we have a json tag @@ -439,7 +439,7 @@ func (t TypeScriptify) backup(fileName string) error { backupFn = path.Join(t.BackupDir, backupFn) } - return ioutil.WriteFile(backupFn, bytes, os.FileMode(0700)) + return ioutil.WriteFile(backupFn, bytes, os.FileMode(0o700)) } func (t TypeScriptify) ConvertToFile(fileName string, packageName string) error { @@ -697,7 +697,7 @@ func (t *TypeScriptify) convertType(depth int, typeOf reflect.Type, customCode m builder.AddMapField(jsonFieldName, field) } else if field.Type.Kind() == reflect.Slice || field.Type.Kind() == reflect.Array { // Slice: - if field.Type.Elem().Kind() == reflect.Ptr { //extract ptr type + if field.Type.Elem().Kind() == reflect.Ptr { // extract ptr type field.Type = field.Type.Elem() } @@ -935,6 +935,6 @@ func typeClashWithReservedKeyword(input string) bool { func warnAboutTypesClash(entity string) { // TODO: Refactor logging l := log.New(os.Stderr, "", 0) - l.Println(fmt.Sprintf("Usage of reserved keyword found and not supported: %s", entity)) + l.Printf("Usage of reserved keyword found and not supported: %s", entity) log.Println("Please rename returned type or consider adding bindings config to your wails.json") } diff --git a/v2/internal/webview2runtime/webview2installer.go b/v2/internal/webview2runtime/webview2installer.go index a2a2922dc20..3645dae02c3 100644 --- a/v2/internal/webview2runtime/webview2installer.go +++ b/v2/internal/webview2runtime/webview2installer.go @@ -11,7 +11,7 @@ var setupexe []byte // WriteInstallerToFile writes the installer file to the given file. func WriteInstallerToFile(targetFile string) error { - return os.WriteFile(targetFile, setupexe, 0755) + return os.WriteFile(targetFile, setupexe, 0o755) } // WriteInstaller writes the installer exe file to the given directory and returns the path to it. diff --git a/v2/pkg/application/application.go b/v2/pkg/application/application.go index 8d8d72ef6ab..8ba5869699a 100644 --- a/v2/pkg/application/application.go +++ b/v2/pkg/application/application.go @@ -2,11 +2,12 @@ package application import ( "context" + "sync" + "github.com/wailsapp/wails/v2/internal/app" "github.com/wailsapp/wails/v2/internal/signal" "github.com/wailsapp/wails/v2/pkg/menu" "github.com/wailsapp/wails/v2/pkg/options" - "sync" ) // Application is the main Wails application @@ -86,7 +87,6 @@ func (a *Application) Bind(boundStruct any) { } func (a *Application) On(eventType EventType, callback func()) { - c := func(ctx context.Context) { callback() } diff --git a/v2/pkg/assetserver/assethandler.go b/v2/pkg/assetserver/assethandler.go index c85bf81e65d..76d41147816 100644 --- a/v2/pkg/assetserver/assethandler.go +++ b/v2/pkg/assetserver/assethandler.go @@ -10,6 +10,7 @@ import ( "net/http" "os" "path" + "strconv" "strings" "github.com/wailsapp/wails/v2/pkg/options/assetserver" @@ -37,7 +38,6 @@ type assetHandler struct { } func NewAssetHandler(options assetserver.Options, log Logger) (http.Handler, error) { - vfs := options.Assets if vfs != nil { if _, err := vfs.Open("."); err != nil { @@ -178,7 +178,8 @@ func (d *assetHandler) serveFSFile(rw http.ResponseWriter, req *http.Request, fi return nil } - rw.Header().Set(HeaderContentLength, fmt.Sprintf("%d", statInfo.Size())) + size := strconv.FormatInt(statInfo.Size(), 10) + rw.Header().Set(HeaderContentLength, size) // Write the first 512 bytes used for MimeType sniffing _, err = io.Copy(rw, bytes.NewReader(buf[:n])) diff --git a/v2/pkg/assetserver/assetserver.go b/v2/pkg/assetserver/assetserver.go index 7fd6508ea10..54fe5d0636f 100644 --- a/v2/pkg/assetserver/assetserver.go +++ b/v2/pkg/assetserver/assetserver.go @@ -123,10 +123,8 @@ func (d *AssetServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { path := req.URL.Path if path == runtimeJSPath { d.writeBlob(rw, path, d.runtimeJS) - } else if path == runtimePath && d.runtimeHandler != nil { d.runtimeHandler.HandleRuntimeCall(rw, req) - } else if path == ipcJSPath { content := d.runtime.DesktopIPC() if d.ipcJS != nil { @@ -136,7 +134,6 @@ func (d *AssetServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { } else if script, ok := d.pluginScripts[path]; ok { d.writeBlob(rw, path, []byte(script)) - } else if d.isRuntimeInjectionMatch(path) { recorder := &bodyRecorder{ ResponseWriter: rw, @@ -150,7 +147,8 @@ func (d *AssetServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { } return strings.Contains(h.Get(HeaderContentType), "text/html") - }} + }, + } handler.ServeHTTP(recorder, req) diff --git a/v2/pkg/assetserver/assetserver_webview.go b/v2/pkg/assetserver/assetserver_webview.go index 575c81bb1d1..dfab1f2d78d 100644 --- a/v2/pkg/assetserver/assetserver_webview.go +++ b/v2/pkg/assetserver/assetserver_webview.go @@ -133,7 +133,8 @@ func (d *AssetServer) processWebViewRequestInternal(r webview.Request) { if req.ContentLength == 0 { req.ContentLength, _ = strconv.ParseInt(req.Header.Get(HeaderContentLength), 10, 64) } else { - req.Header.Set(HeaderContentLength, fmt.Sprintf("%d", req.ContentLength)) + size := strconv.FormatInt(req.ContentLength, 10) + req.Header.Set(HeaderContentLength, size) } if host := req.Header.Get(HeaderHost); host != "" { diff --git a/v2/pkg/assetserver/common.go b/v2/pkg/assetserver/common.go index 01e51f2be82..57934e08e14 100644 --- a/v2/pkg/assetserver/common.go +++ b/v2/pkg/assetserver/common.go @@ -3,9 +3,9 @@ package assetserver import ( "bytes" "errors" - "fmt" "io" "net/http" + "strconv" "strings" "github.com/wailsapp/wails/v2/pkg/options" @@ -44,7 +44,7 @@ const ( func serveFile(rw http.ResponseWriter, filename string, blob []byte) error { header := rw.Header() - header.Set(HeaderContentLength, fmt.Sprintf("%d", len(blob))) + header.Set(HeaderContentLength, strconv.Itoa(len(blob))) if mimeType := header.Get(HeaderContentType); mimeType == "" { mimeType = GetMimetype(filename, blob) header.Set(HeaderContentType, mimeType) diff --git a/v2/pkg/assetserver/webview/request_darwin.go b/v2/pkg/assetserver/webview/request_darwin.go index f0e85780b3d..c44e5f1969d 100644 --- a/v2/pkg/assetserver/webview/request_darwin.go +++ b/v2/pkg/assetserver/webview/request_darwin.go @@ -197,7 +197,10 @@ func (r *request) Close() error { if r.body != nil { err = r.body.Close() } - r.Response().Finish() + err = r.Response().Finish() + if err != nil { + return err + } C.URLSchemeTaskRelease(r.task) return err } diff --git a/v2/pkg/buildassets/buildassets.go b/v2/pkg/buildassets/buildassets.go index 26401745db3..778d97fbfd5 100644 --- a/v2/pkg/buildassets/buildassets.go +++ b/v2/pkg/buildassets/buildassets.go @@ -128,12 +128,12 @@ func writeFileSystemFile(projectData *project.Project, file string, content []by targetPath := GetLocalPath(projectData, file) if dir := filepath.Dir(targetPath); !fs.DirExists(dir) { - if err := fs.MkDirs(dir, 0755); err != nil { + if err := fs.MkDirs(dir, 0o755); err != nil { return fmt.Errorf("Unable to create directory: %w", err) } } - if err := os.WriteFile(targetPath, content, 0644); err != nil { + if err := os.WriteFile(targetPath, content, 0o644); err != nil { return err } return nil diff --git a/v2/pkg/commands/bindings/bindings.go b/v2/pkg/commands/bindings/bindings.go index 71c1747b736..1432acee11c 100644 --- a/v2/pkg/commands/bindings/bindings.go +++ b/v2/pkg/commands/bindings/bindings.go @@ -26,7 +26,6 @@ type Options struct { // GenerateBindings generates bindings for the Wails project in the given ProjectDirectory. // If no project directory is given then the current working directory is used. func GenerateBindings(options Options) (string, error) { - filename, _ := lo.Coalesce(options.Filename, "wailsbindings") if runtime.GOOS == "windows" { filename += ".exe" diff --git a/v2/pkg/commands/build/base.go b/v2/pkg/commands/build/base.go index abfbafff51c..6595aff0f6b 100644 --- a/v2/pkg/commands/build/base.go +++ b/v2/pkg/commands/build/base.go @@ -74,7 +74,6 @@ func (b *BaseBuilder) convertFileToIntegerString(filename string) (string, error } func (b *BaseBuilder) convertByteSliceToIntegerString(data []byte) string { - // Create string builder var result strings.Builder @@ -85,8 +84,7 @@ func (b *BaseBuilder) convertByteSliceToIntegerString(data []byte) string { result.WriteString(fmt.Sprintf("%v,", data[i])) } - result.WriteString(fmt.Sprintf("%v", data[len(data)-1])) - + result.WriteString(strconv.FormatUint(uint64(data[len(data)-1]), 10)) } return result.String() @@ -94,10 +92,8 @@ func (b *BaseBuilder) convertByteSliceToIntegerString(data []byte) string { // CleanUp does post-build housekeeping func (b *BaseBuilder) CleanUp() { - // Delete all the files b.filesToDelete.Each(func(filename string) { - // if file doesn't exist, ignore if !b.fileExists(filename) { return @@ -106,7 +102,6 @@ func (b *BaseBuilder) CleanUp() { // Delete file. We ignore errors because these files will be overwritten // by the next build anyway. _ = os.Remove(filename) - }) } @@ -159,7 +154,6 @@ func (b *BaseBuilder) OutputFilename(options *Options) string { // CompileProject compiles the project func (b *BaseBuilder) CompileProject(options *Options) error { - // Check if the runtime wrapper exists err := generateRuntimeWrapper(options) if err != nil { @@ -402,7 +396,7 @@ Please reinstall by doing the following: return nil } - var args = []string{"--best", "--no-color", "--no-progress", options.CompiledBinary} + args := []string{"--best", "--no-color", "--no-progress", options.CompiledBinary} if options.CompressFlags != "" { args = strings.Split(options.CompressFlags, " ") @@ -426,7 +420,6 @@ Please reinstall by doing the following: } func generateRuntimeWrapper(options *Options) error { - if options.WailsJSDir == "" { cwd, err := os.Getwd() if err != nil { @@ -452,7 +445,6 @@ func (b *BaseBuilder) NpmInstall(sourceDir string, verbose bool) error { // NpmInstallUsingCommand runs the given install command in the specified npm project directory func (b *BaseBuilder) NpmInstallUsingCommand(sourceDir string, installCommand string, verbose bool) error { - packageJSON := filepath.Join(sourceDir, "package.json") // Check package.json exists @@ -492,7 +484,7 @@ func (b *BaseBuilder) NpmInstallUsingCommand(sourceDir string, installCommand st } // Shortcut installation - if install == false { + if !install { if verbose { pterm.Println("Skipping npm install") } @@ -549,7 +541,6 @@ func (b *BaseBuilder) NpmRunWithEnvironment(projectDir, buildTarget string, verb // BuildFrontend executes the `npm build` command for the frontend directory func (b *BaseBuilder) BuildFrontend(outputLogger *clilogger.CLILogger) error { - verbose := b.options.Verbosity == VERBOSE frontendDir := b.projectData.GetFrontendDir() diff --git a/v2/pkg/commands/build/build.go b/v2/pkg/commands/build/build.go index a29840b1bde..2223bf575f0 100644 --- a/v2/pkg/commands/build/build.go +++ b/v2/pkg/commands/build/build.go @@ -73,7 +73,6 @@ type Options struct { // Build the project! func Build(options *Options) (string, error) { - // Extract logger outputLogger := options.Logger @@ -171,7 +170,7 @@ func CreateEmbedDirectories(cwd string, buildOptions *Options) error { for _, embedDetail := range embedDetails { fullPath := embedDetail.GetFullPath() if _, err := os.Stat(fullPath); os.IsNotExist(err) { - err := os.MkdirAll(fullPath, 0755) + err := os.MkdirAll(fullPath, 0o755) if err != nil { return err } @@ -184,7 +183,6 @@ func CreateEmbedDirectories(cwd string, buildOptions *Options) error { } return nil - } func fatal(message string) { @@ -213,7 +211,6 @@ func printBulletPoint(text string, args ...any) { } func GenerateBindings(buildOptions *Options) error { - obfuscated := buildOptions.Obfuscated if obfuscated { printBulletPoint("Generating obfuscated bindings: ") @@ -371,7 +368,6 @@ func execPostBuildHook(outputLogger *clilogger.CLILogger, options *Options, hook } return executeBuildHook(outputLogger, options, hookIdentifier, argReplacements, postBuildHook, "post") - } func executeBuildHook(_ *clilogger.CLILogger, options *Options, hookIdentifier string, argReplacements map[string]string, buildHook string, hookName string) error { @@ -407,7 +403,6 @@ func executeBuildHook(_ *clilogger.CLILogger, options *Options, hookIdentifier s if options.Verbosity == VERBOSE { pterm.Info.Println(strings.Join(args, " ")) - } if !fs.DirExists(options.BinDirectory) { diff --git a/v2/pkg/commands/build/builder.go b/v2/pkg/commands/build/builder.go index 4840341c031..6a220c530bd 100644 --- a/v2/pkg/commands/build/builder.go +++ b/v2/pkg/commands/build/builder.go @@ -8,8 +8,8 @@ import ( // Builder defines a builder that can build Wails applications type Builder interface { SetProjectData(projectData *project.Project) - BuildFrontend(*clilogger.CLILogger) error - CompileProject(*Options) error - OutputFilename(*Options) string + BuildFrontend(logger *clilogger.CLILogger) error + CompileProject(options *Options) error + OutputFilename(options *Options) string CleanUp() } diff --git a/v2/pkg/commands/build/nsis_installer.go b/v2/pkg/commands/build/nsis_installer.go index 11f1407a388..820df2d1d36 100644 --- a/v2/pkg/commands/build/nsis_installer.go +++ b/v2/pkg/commands/build/nsis_installer.go @@ -41,7 +41,7 @@ func GenerateNSISInstaller(options *Options, amd64Binary string, arm64Binary str // Write the WebView2 SetupFile webviewSetup := buildassets.GetLocalPath(options.ProjectData, path.Join(nsisFolder, nsisWebView2SetupFile)) if dir := filepath.Dir(webviewSetup); !fs.DirExists(dir) { - if err := fs.MkDirs(dir, 0755); err != nil { + if err := fs.MkDirs(dir, 0o755); err != nil { return err } } @@ -92,7 +92,7 @@ func makeNSIS(options *Options, installerKind string, amd64Binary string, arm64B outputLogger := options.Logger outputLogger.Print(" - Building '%s' installer: ", installerKind) - var args = []string{} + args := []string{} if amd64Binary != "" { args = append(args, "-DARG_WAILS_AMD64_BINARY="+amd64Binary) } diff --git a/v2/pkg/commands/build/packager.go b/v2/pkg/commands/build/packager.go index beca47c5bea..54aea2e674e 100644 --- a/v2/pkg/commands/build/packager.go +++ b/v2/pkg/commands/build/packager.go @@ -3,13 +3,14 @@ package build import ( "bytes" "fmt" + "image" + "os" + "path/filepath" + "github.com/leaanthony/winicon" "github.com/tc-hib/winres" "github.com/tc-hib/winres/version" "github.com/wailsapp/wails/v2/internal/project" - "image" - "os" - "path/filepath" "github.com/jackmordaunt/icns" "github.com/pkg/errors" @@ -20,7 +21,6 @@ import ( // PackageProject packages the application func packageProject(options *Options, platform string) error { - var err error switch platform { case "darwin": @@ -42,7 +42,6 @@ func packageProject(options *Options, platform string) error { // cleanBinDirectory will remove an existing bin directory and recreate it func cleanBinDirectory(options *Options) error { - buildDirectory := options.BinDirectory // Clear out old builds @@ -54,7 +53,7 @@ func cleanBinDirectory(options *Options) error { } // Create clean directory - err := os.MkdirAll(buildDirectory, 0700) + err := os.MkdirAll(buildDirectory, 0o700) if err != nil { return err } @@ -63,7 +62,6 @@ func cleanBinDirectory(options *Options) error { } func packageApplicationForDarwin(options *Options) error { - var err error // Create directory structure @@ -74,12 +72,12 @@ func packageApplicationForDarwin(options *Options) error { contentsDirectory := filepath.Join(options.BinDirectory, bundlename, "/Contents") exeDir := filepath.Join(contentsDirectory, "/MacOS") - err = fs.MkDirs(exeDir, 0755) + err = fs.MkDirs(exeDir, 0o755) if err != nil { return err } resourceDir := filepath.Join(contentsDirectory, "/Resources") - err = fs.MkDirs(resourceDir, 0755) + err = fs.MkDirs(resourceDir, 0o755) if err != nil { return err } @@ -116,7 +114,6 @@ func packageApplicationForDarwin(options *Options) error { } func processPList(options *Options, contentsDirectory string) error { - sourcePList := "Info.plist" if options.Mode == Dev { // Use Info.dev.plist if using build mode @@ -130,7 +127,7 @@ func processPList(options *Options, contentsDirectory string) error { } targetFile := filepath.Join(contentsDirectory, "Info.plist") - return os.WriteFile(targetFile, content, 0644) + return os.WriteFile(targetFile, content, 0o644) } func processDarwinIcon(projectData *project.Project, iconName string, resourceDir string, destIconName string) (err error) { @@ -152,7 +149,6 @@ func processDarwinIcon(projectData *project.Project, iconName string, resourceDi dest, err := os.Create(tgtBundle) if err != nil { return err - } defer func() { err = dest.Close() @@ -206,12 +202,12 @@ func generateIcoFile(options *Options, iconName string, destIconName string) err icoFile := buildassets.GetLocalPath(options.ProjectData, "windows/"+destIconName+".ico") if !fs.FileExists(icoFile) { if dir := filepath.Dir(icoFile); !fs.DirExists(dir) { - if err := fs.MkDirs(dir, 0755); err != nil { + if err := fs.MkDirs(dir, 0o755); err != nil { return err } } - output, err := os.OpenFile(icoFile, os.O_CREATE|os.O_WRONLY, 0644) + output, err := os.OpenFile(icoFile, os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return err } @@ -226,13 +222,12 @@ func generateIcoFile(options *Options, iconName string, destIconName string) err } func compileResources(options *Options) error { - currentDir, err := os.Getwd() if err != nil { return err } defer func() { - os.Chdir(currentDir) + _ = os.Chdir(currentDir) }() windowsDir := filepath.Join(options.ProjectData.GetBuildDir(), "windows") err = os.Chdir(windowsDir) diff --git a/v2/pkg/logger/filelogger.go b/v2/pkg/logger/filelogger.go index 5cf68fc1a55..954c46f599b 100644 --- a/v2/pkg/logger/filelogger.go +++ b/v2/pkg/logger/filelogger.go @@ -19,7 +19,7 @@ func NewFileLogger(filename string) Logger { // Print works like Sprintf. func (l *FileLogger) Print(message string) { - f, err := os.OpenFile(l.filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + f, err := os.OpenFile(l.filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { log.Fatal(err) } diff --git a/v2/pkg/mac/login_darwin.go b/v2/pkg/mac/login_darwin.go index 2ff49be83b5..b2390e3059d 100644 --- a/v2/pkg/mac/login_darwin.go +++ b/v2/pkg/mac/login_darwin.go @@ -33,7 +33,7 @@ func StartAtLogin(enabled bool) error { } _, stde, err := shell.RunCommand("/tmp", "osascript", "-e", command) if err != nil { - errors.Wrap(err, stde) + return errors.Wrap(err, stde) } return nil } diff --git a/v2/pkg/mac/notification_darwin.go b/v2/pkg/mac/notification_darwin.go index a06ecb53ad7..b7743df97d4 100644 --- a/v2/pkg/mac/notification_darwin.go +++ b/v2/pkg/mac/notification_darwin.go @@ -24,7 +24,7 @@ func ShowNotification(title string, subtitle string, message string, sound strin } _, stde, err := shell.RunCommand("/tmp", "osascript", "-e", command) if err != nil { - errors.Wrap(err, stde) + return errors.Wrap(err, stde) } return nil } diff --git a/v2/pkg/menu/callback.go b/v2/pkg/menu/callback.go index fe616036147..a02664ac099 100644 --- a/v2/pkg/menu/callback.go +++ b/v2/pkg/menu/callback.go @@ -2,7 +2,7 @@ package menu type CallbackData struct { MenuItem *MenuItem - //ContextData string + // ContextData string } type Callback func(*CallbackData) diff --git a/v2/pkg/menu/colours/colours.go b/v2/pkg/menu/colours/colours.go index 28564a09e24..5fb74eabd0b 100644 --- a/v2/pkg/menu/colours/colours.go +++ b/v2/pkg/menu/colours/colours.go @@ -36,7 +36,6 @@ type InputCol struct { var Template string func main() { - var Cols []InputCol resp, err := http.Get("https://jonasjacek.github.io/colors/data.json") @@ -62,5 +61,8 @@ func main() { if err != nil { log.Fatal(err) } - os.WriteFile(filepath.Join("..", "cols.go"), buffer.Bytes(), 0755) + err = os.WriteFile(filepath.Join("..", "cols.go"), buffer.Bytes(), 0o755) + if err != nil { + log.Fatal(err) + } } diff --git a/v2/pkg/menu/keys/keys.go b/v2/pkg/menu/keys/keys.go index fa8027a3347..961edab2d8e 100644 --- a/v2/pkg/menu/keys/keys.go +++ b/v2/pkg/menu/keys/keys.go @@ -16,7 +16,7 @@ const ( // ShiftKey represents the shift key on all systems ShiftKey Modifier = "shift" // SuperKey represents Command on Mac and the Windows key on the other platforms - //SuperKey Modifier = "super" + // SuperKey Modifier = "super" // ControlKey represents the control key on all systems ControlKey Modifier = "ctrl" ) diff --git a/v2/pkg/menu/keys/parser.go b/v2/pkg/menu/keys/parser.go index 91a05783d41..6e8e123766e 100644 --- a/v2/pkg/menu/keys/parser.go +++ b/v2/pkg/menu/keys/parser.go @@ -11,7 +11,6 @@ import ( var namedKeys = slicer.String([]string{"backspace", "tab", "return", "enter", "escape", "left", "right", "up", "down", "space", "delete", "home", "end", "page up", "page down", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34", "f35", "numlock"}) func parseKey(key string) (string, bool) { - // Lowercase! key = strings.ToLower(key) @@ -38,11 +37,9 @@ func parseKey(key string) (string, bool) { } return "", false - } func Parse(shortcut string) (*Accelerator, error) { - var result Accelerator // Split the shortcut by + diff --git a/v2/pkg/menu/keys/stringify.go b/v2/pkg/menu/keys/stringify.go index ccc8c5e9e70..92498f5d49c 100644 --- a/v2/pkg/menu/keys/stringify.go +++ b/v2/pkg/menu/keys/stringify.go @@ -1,8 +1,9 @@ package keys import ( - "github.com/leaanthony/slicer" "strings" + + "github.com/leaanthony/slicer" ) var modifierStringMap = map[string]map[Modifier]string{ @@ -11,21 +12,21 @@ var modifierStringMap = map[string]map[Modifier]string{ ControlKey: "Ctrl", OptionOrAltKey: "Alt", ShiftKey: "Shift", - //SuperKey: "Win", + // SuperKey: "Win", }, "darwin": { CmdOrCtrlKey: "Cmd", ControlKey: "Ctrl", OptionOrAltKey: "Option", ShiftKey: "Shift", - //SuperKey: "Cmd", + // SuperKey: "Cmd", }, "linux": { CmdOrCtrlKey: "Ctrl", ControlKey: "Ctrl", OptionOrAltKey: "Alt", ShiftKey: "Shift", - //SuperKey: "Super", + // SuperKey: "Super", }, } diff --git a/v2/pkg/menu/menu.go b/v2/pkg/menu/menu.go index 819939bbfaa..86acbd1d098 100644 --- a/v2/pkg/menu/menu.go +++ b/v2/pkg/menu/menu.go @@ -59,8 +59,7 @@ func (m *Menu) Prepend(item *MenuItem) { } func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu { - - var result = NewMenu() + result := NewMenu() result.Append(first) for _, item := range rest { result.Append(item) diff --git a/v2/pkg/menu/menuitem.go b/v2/pkg/menu/menuitem.go index f6ea681d7ad..264b2ebd41a 100644 --- a/v2/pkg/menu/menuitem.go +++ b/v2/pkg/menu/menuitem.go @@ -23,7 +23,7 @@ type MenuItem struct { // Checked indicates if the item is selected (used by Checkbox and Radio types only) Checked bool // Submenu contains a list of menu items that will be shown as a submenu - //SubMenu []*MenuItem `json:"SubMenu,omitempty"` + // SubMenu []*MenuItem `json:"SubMenu,omitempty"` SubMenu *Menu // Callback function when menu clicked @@ -106,7 +106,6 @@ func (m *MenuItem) removeChild(item *MenuItem) { // menu. If there is no parent menu (we are a top level menu) then false is // returned func (m *MenuItem) InsertAfter(item *MenuItem) bool { - // We need to find my parent if m.parent == nil { return false @@ -120,7 +119,6 @@ func (m *MenuItem) InsertAfter(item *MenuItem) bool { // menu. If there is no parent menu (we are a top level menu) then false is // returned func (m *MenuItem) InsertBefore(item *MenuItem) bool { - // We need to find my parent if m.parent == nil { return false @@ -134,8 +132,8 @@ func (m *MenuItem) InsertBefore(item *MenuItem) bool { // in this item's submenu. If we are not a submenu, // then something bad has happened :/ func (m *MenuItem) insertNewItemAfterGivenItem(target *MenuItem, - newItem *MenuItem) bool { - + newItem *MenuItem, +) bool { if !m.isSubMenu() { return false } @@ -154,8 +152,8 @@ func (m *MenuItem) insertNewItemAfterGivenItem(target *MenuItem, // target in this item's submenu. If we are not a submenu, then something bad // has happened :/ func (m *MenuItem) insertNewItemBeforeGivenItem(target *MenuItem, - newItem *MenuItem) bool { - + newItem *MenuItem, +) bool { if !m.isSubMenu() { return false } @@ -176,7 +174,6 @@ func (m *MenuItem) isSubMenu() bool { // getItemIndex returns the index of the given target relative to this menu func (m *MenuItem) getItemIndex(target *MenuItem) int { - // This should only be called on submenus if !m.isSubMenu() { return -1 @@ -196,7 +193,6 @@ func (m *MenuItem) getItemIndex(target *MenuItem) int { // the given index // Credit: https://stackoverflow.com/a/61822301 func (m *MenuItem) insertItemAtIndex(index int, target *MenuItem) bool { - // If index is OOB, return false if index > len(m.SubMenu.Items) { return false diff --git a/v2/pkg/menu/menuroles.go b/v2/pkg/menu/menuroles.go index e6b15b2433b..bcc0657fc81 100644 --- a/v2/pkg/menu/menuroles.go +++ b/v2/pkg/menu/menuroles.go @@ -11,29 +11,29 @@ const ( AppMenuRole Role = 1 EditMenuRole = 2 WindowMenuRole = 3 - //AboutRole Role = "about" - //UndoRole Role = "undo" - //RedoRole Role = "redo" - //CutRole Role = "cut" - //CopyRole Role = "copy" - //PasteRole Role = "paste" - //PasteAndMatchStyleRole Role = "pasteAndMatchStyle" - //SelectAllRole Role = "selectAll" - //DeleteRole Role = "delete" - //MinimizeRole Role = "minimize" - //QuitRole Role = "quit" - //TogglefullscreenRole Role = "togglefullscreen" - //FileMenuRole Role = "fileMenu" - //ViewMenuRole Role = "viewMenu" - //WindowMenuRole Role = "windowMenu" - //HideRole Role = "hide" - //HideOthersRole Role = "hideOthers" - //UnhideRole Role = "unhide" - //FrontRole Role = "front" - //ZoomRole Role = "zoom" - //WindowSubMenuRole Role = "windowSubMenu" - //HelpSubMenuRole Role = "helpSubMenu" - //SeparatorItemRole Role = "separatorItem" + // AboutRole Role = "about" + // UndoRole Role = "undo" + // RedoRole Role = "redo" + // CutRole Role = "cut" + // CopyRole Role = "copy" + // PasteRole Role = "paste" + // PasteAndMatchStyleRole Role = "pasteAndMatchStyle" + // SelectAllRole Role = "selectAll" + // DeleteRole Role = "delete" + // MinimizeRole Role = "minimize" + // QuitRole Role = "quit" + // TogglefullscreenRole Role = "togglefullscreen" + // FileMenuRole Role = "fileMenu" + // ViewMenuRole Role = "viewMenu" + // WindowMenuRole Role = "windowMenu" + // HideRole Role = "hide" + // HideOthersRole Role = "hideOthers" + // UnhideRole Role = "unhide" + // FrontRole Role = "front" + // ZoomRole Role = "zoom" + // WindowSubMenuRole Role = "windowSubMenu" + // HelpSubMenuRole Role = "helpSubMenu" + // SeparatorItemRole Role = "separatorItem" ) /* diff --git a/v2/pkg/menu/styledlabel.go b/v2/pkg/menu/styledlabel.go index 11a0254c9e6..1e996b9717d 100644 --- a/v2/pkg/menu/styledlabel.go +++ b/v2/pkg/menu/styledlabel.go @@ -29,24 +29,31 @@ type StyledText struct { func (s *StyledText) Bold() bool { return s.Style&Bold == Bold } + func (s *StyledText) Faint() bool { return s.Style&Faint == Faint } + func (s *StyledText) Italic() bool { return s.Style&Italic == Italic } + func (s *StyledText) Blinking() bool { return s.Style&Blinking == Blinking } + func (s *StyledText) Inversed() bool { return s.Style&Inversed == Inversed } + func (s *StyledText) Invisible() bool { return s.Style&Invisible == Invisible } + func (s *StyledText) Underlined() bool { return s.Style&Underlined == Underlined } + func (s *StyledText) Strikethrough() bool { return s.Style&Strikethrough == Strikethrough } diff --git a/v2/pkg/menu/tray.go b/v2/pkg/menu/tray.go index 7554795ada4..c8728f1f7f1 100644 --- a/v2/pkg/menu/tray.go +++ b/v2/pkg/menu/tray.go @@ -2,7 +2,6 @@ package menu // TrayMenu are the options type TrayMenu struct { - // Label is the text we wish to display in the tray Label string @@ -27,7 +26,7 @@ type TrayMenu struct { Tooltip string // Callback function when menu clicked - //Click Callback `json:"-"` + // Click Callback `json:"-"` // Disabled makes the item unselectable Disabled bool diff --git a/v2/pkg/options/mac/mac.go b/v2/pkg/options/mac/mac.go index 5758befd011..9d2ccc953c9 100644 --- a/v2/pkg/options/mac/mac.go +++ b/v2/pkg/options/mac/mac.go @@ -21,9 +21,9 @@ type Options struct { WebviewIsTransparent bool WindowIsTranslucent bool Preferences *Preferences - //ActivationPolicy ActivationPolicy + // ActivationPolicy ActivationPolicy About *AboutInfo OnFileOpen func(filePath string) `json:"-"` OnUrlOpen func(filePath string) `json:"-"` - //URLHandlers map[string]func(string) + // URLHandlers map[string]func(string) } diff --git a/v2/pkg/options/mac/preferences.go b/v2/pkg/options/mac/preferences.go index dbc20c805a3..0749ccb18f5 100644 --- a/v2/pkg/options/mac/preferences.go +++ b/v2/pkg/options/mac/preferences.go @@ -2,8 +2,10 @@ package mac import "github.com/leaanthony/u" -var Enabled = u.True -var Disabled = u.False +var ( + Enabled = u.True + Disabled = u.False +) // Preferences allows to set webkit preferences type Preferences struct { diff --git a/v2/pkg/options/mac/titlebar.go b/v2/pkg/options/mac/titlebar.go index c18c4eea8ca..51e0832cab5 100644 --- a/v2/pkg/options/mac/titlebar.go +++ b/v2/pkg/options/mac/titlebar.go @@ -41,7 +41,6 @@ func TitleBarHidden() *TitleBar { // TitleBarHiddenInset results in a hidden title bar with an alternative look where // the traffic light buttons are slightly more inset from the window edge. func TitleBarHiddenInset() *TitleBar { - return &TitleBar{ TitlebarAppearsTransparent: true, HideTitle: true, @@ -50,5 +49,4 @@ func TitleBarHiddenInset() *TitleBar { UseToolbar: true, HideToolbarSeparator: true, } - } diff --git a/v2/pkg/options/options.go b/v2/pkg/options/options.go index 1ecad7fb919..088e7c46ab8 100644 --- a/v2/pkg/options/options.go +++ b/v2/pkg/options/options.go @@ -28,8 +28,7 @@ const ( Fullscreen WindowStartState = 3 ) -type Experimental struct { -} +type Experimental struct{} // App contains options for creating the App type App struct { diff --git a/v2/pkg/options/windows/windows.go b/v2/pkg/options/windows/windows.go index 7adf0bf7237..073450c9f68 100644 --- a/v2/pkg/options/windows/windows.go +++ b/v2/pkg/options/windows/windows.go @@ -36,7 +36,7 @@ const ( ) func RGB(r, g, b uint8) int32 { - var col = int32(b) + col := int32(b) col = col<<8 | int32(g) col = col<<8 | int32(r) return col diff --git a/v2/pkg/runtime/dialog.go b/v2/pkg/runtime/dialog.go index d53a89c1557..16ae659e106 100644 --- a/v2/pkg/runtime/dialog.go +++ b/v2/pkg/runtime/dialog.go @@ -3,6 +3,7 @@ package runtime import ( "context" "fmt" + "github.com/wailsapp/wails/v2/internal/frontend" "github.com/wailsapp/wails/v2/internal/fs" ) diff --git a/v2/pkg/runtime/events.go b/v2/pkg/runtime/events.go index 493d811689a..84aff7d7407 100644 --- a/v2/pkg/runtime/events.go +++ b/v2/pkg/runtime/events.go @@ -10,7 +10,7 @@ func EventsOn(ctx context.Context, eventName string, callback func(optionalData return events.On(eventName, callback) } -// EventsOff unregisters a listener for the given event name, optionally multiple listeneres can be unregistered via `additionalEventNames` +// EventsOff unregisters a listener for the given event name, optionally multiple listeners can be unregistered via `additionalEventNames` func EventsOff(ctx context.Context, eventName string, additionalEventNames ...string) { events := getEvents(ctx) events.Off(eventName) @@ -22,7 +22,7 @@ func EventsOff(ctx context.Context, eventName string, additionalEventNames ...st } } -// EventsOff unregisters a listener for the given event name, optionally multiple listeneres can be unregistered via `additionalEventNames` +// EventsOff unregisters a listener for the given event name, optionally multiple listeners can be unregistered via `additionalEventNames` func EventsOffAll(ctx context.Context) { events := getEvents(ctx) events.OffAll() diff --git a/v2/pkg/runtime/log.go b/v2/pkg/runtime/log.go index 4d3f56d3f20..3c2756f06ca 100644 --- a/v2/pkg/runtime/log.go +++ b/v2/pkg/runtime/log.go @@ -3,6 +3,7 @@ package runtime import ( "context" "fmt" + "github.com/wailsapp/wails/v2/pkg/logger" ) diff --git a/v2/pkg/runtime/menu.go b/v2/pkg/runtime/menu.go index 176c9bb1db9..09bd640c5e9 100644 --- a/v2/pkg/runtime/menu.go +++ b/v2/pkg/runtime/menu.go @@ -2,6 +2,7 @@ package runtime import ( "context" + "github.com/wailsapp/wails/v2/pkg/menu" ) diff --git a/v2/pkg/runtime/runtime.go b/v2/pkg/runtime/runtime.go index 4702b439a8a..6de5ea79892 100644 --- a/v2/pkg/runtime/runtime.go +++ b/v2/pkg/runtime/runtime.go @@ -27,6 +27,7 @@ func getFrontend(ctx context.Context) frontend.Frontend { log.Fatalf("cannot call '%s': %s", funcName, contextError) return nil } + func getLogger(ctx context.Context) *logger.Logger { if ctx == nil { pc, _, _, _ := goruntime.Caller(1) diff --git a/v2/pkg/runtime/screen.go b/v2/pkg/runtime/screen.go index d92ed8308c5..af8fb626ed9 100644 --- a/v2/pkg/runtime/screen.go +++ b/v2/pkg/runtime/screen.go @@ -1,7 +1,10 @@ package runtime -import "context" -import "github.com/wailsapp/wails/v2/internal/frontend" +import ( + "context" + + "github.com/wailsapp/wails/v2/internal/frontend" +) type Screen = frontend.Screen diff --git a/v2/pkg/templates/generate/generate.go b/v2/pkg/templates/generate/generate.go index 3b01e5f2a67..6842dc19678 100644 --- a/v2/pkg/templates/generate/generate.go +++ b/v2/pkg/templates/generate/generate.go @@ -159,7 +159,6 @@ var templates = []*template{ } func main() { - rebuildRuntime() for _, t := range templates { diff --git a/v2/pkg/templates/templates.go b/v2/pkg/templates/templates.go index d982454d04d..9b42ef36559 100644 --- a/v2/pkg/templates/templates.go +++ b/v2/pkg/templates/templates.go @@ -72,7 +72,6 @@ type Options struct { // Template holds data relating to a template // including the metadata stored in template.json type Template struct { - // Template details Name string `json:"name"` ShortName string `json:"shortname"` @@ -100,7 +99,6 @@ func parseTemplate(template gofs.FS) (Template, error) { // List returns the list of available templates func List() ([]Template, error) { - // If the cache isn't loaded, load it if templateCache == nil { err := loadTemplateCache() @@ -114,7 +112,6 @@ func List() ([]Template, error) { // getTemplateByShortname returns the template with the given short name func getTemplateByShortname(shortname string) (Template, error) { - var result Template // If the cache isn't loaded, load it @@ -136,7 +133,6 @@ func getTemplateByShortname(shortname string) (Template, error) { // Loads the template cache func loadTemplateCache() error { - templatesFS, err := debme.FS(templates, "templates") if err != nil { return err @@ -309,11 +305,9 @@ func gitclone(options *Options) (string, error) { _, err = git.PlainClone(dirname, false, cloneOption) return dirname, err - } func generateIDEFiles(options *Options) error { - switch options.IDE { case "vscode": return generateVSCodeFiles(options) @@ -361,7 +355,6 @@ func generateVSCodeFiles(options *Options) error { options: options, } return installIDEFiles(ideoptions) - } func installIDEFiles(o ideOptions) error { diff --git a/v2/tools/release/release.go b/v2/tools/release/release.go index dc6299ed73e..4178fcc950f 100644 --- a/v2/tools/release/release.go +++ b/v2/tools/release/release.go @@ -33,7 +33,7 @@ func updateVersion() string { minorVersion++ vsplit[len(vsplit)-1] = strconv.Itoa(minorVersion) newVersion := strings.Join(vsplit, ".") - err = os.WriteFile(versionFile, []byte(newVersion), 0755) + err = os.WriteFile(versionFile, []byte(newVersion), 0o755) checkError(err) return newVersion } @@ -68,7 +68,7 @@ func main() { newVersion = os.Args[1] currentVersion, err := os.ReadFile(versionFile) checkError(err) - err = os.WriteFile(versionFile, []byte(newVersion), 0755) + err = os.WriteFile(versionFile, []byte(newVersion), 0o755) checkError(err) isPointRelease = IsPointRelease(string(currentVersion), newVersion) } else { @@ -89,7 +89,7 @@ func main() { // Add the new version to the top of the changelog newChangelog := changelogSplit[0] + "## [Unreleased]\n\n## " + newVersion + " - " + today + changelogSplit[1] // Write the changelog back - err = os.WriteFile("src/pages/changelog.mdx", []byte(newChangelog), 0755) + err = os.WriteFile("src/pages/changelog.mdx", []byte(newChangelog), 0o755) checkError(err) if !isPointRelease { @@ -112,7 +112,7 @@ func main() { versions = versions[0 : len(versions)-1] newVersions, err := json.Marshal(&versions) checkError(err) - err = os.WriteFile("versions.json", newVersions, 0755) + err = os.WriteFile("versions.json", newVersions, 0o755) checkError(err) s.ECHO("Removing old version: " + oldestVersion)