Skip to content

Linter fixes, new feature of allowing multiple directories at startup, other code improvements #764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Apr 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
e4b4cab
feat: Add wastedassign linter and fix errors
lazysegtree Apr 6, 2025
68fea07
feat: Add whitespace linter and auto fix errors via golangci-lint ru…
lazysegtree Apr 6, 2025
969eca7
feat: Add intrange linter and fix issues
lazysegtree Apr 6, 2025
eeabdd0
fix: Add errorlint and fix issues
lazysegtree Apr 6, 2025
a48a7f7
fix: Fix issue in makePrintable after intrange linter's fix
lazysegtree Apr 6, 2025
47dee2d
fix: Add gocritic linter and fix errors
lazysegtree Apr 6, 2025
55a472e
fix: Add nonamedreturns linter and fix issues
lazysegtree Apr 6, 2025
9d8f23d
fix: Add reassign linter and fix issues
lazysegtree Apr 6, 2025
ecca3d1
feat: Add revive and stylycheck liner and fix issues
lazysegtree Apr 6, 2025
b0c3e41
feat: Added gochecknoglobals and add Todos and exclusions
lazysegtree Apr 6, 2025
4d50c14
fix: PR comments: handle unexpected message in wheel function
lazysegtree Apr 6, 2025
4afb2b7
fix: Fix in log.Fatal calls, resolves issue#758
lazysegtree Apr 7, 2025
8a71560
fix: PR fix, Use named returns in initialConfig(), etc
lazysegtree Apr 7, 2025
9653d8a
Merge pull request #757 from yorukot/golangci_lint_fixes_2
lazysegtree Apr 8, 2025
6f90021
feat: Allow specifying multiple panels at startup
lazysegtree Apr 7, 2025
d69cc95
Merge pull request #759 from yorukot/multiple_panel_at_startup
lazysegtree Apr 8, 2025
025753d
fix: remove redundant function containsKey
lazysegtree Apr 8, 2025
9cf929c
Merge pull request #765 from yorukot/remove_containskey
lazysegtree Apr 8, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 38 additions & 31 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ linters-settings:
# Ignore comments when counting lines.
# Default false
ignore-comments: true

gochecksumtype:
# Presence of `default` case in switch statements satisfies exhaustiveness, if all members are not listed.
# Default: true
Expand Down Expand Up @@ -276,8 +275,7 @@ linters:
- dupl # tool for code clone detection
- durationcheck # checks for two durations multiplied together
- errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error
# Todo enable
#- errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13
- errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13
- exhaustive # checks exhaustiveness of enum switch statements
- exptostd # detects functions from golang.org/x/exp/ that can be replaced by std functions
- fatcontext # detects nested contexts in loops
Expand All @@ -286,27 +284,24 @@ linters:
#- funlen # tool for detection of long functions
- gocheckcompilerdirectives # validates go compiler directive comments (//go:)
# Todo enable - This is too much for us right now
# - gochecknoglobals # checks that no global variables exist
- gochecknoglobals # checks that no global variables exist
- gochecknoinits # checks that no init functions are present in Go code
- gochecksumtype # checks exhaustiveness on Go "sum types"
# Todo enable - Need to refactor many functions
# - gocognit # computes and checks the cognitive complexity of functions
- goconst # finds repeated strings that could be replaced by a constant
# Todo enable - Some few changes. There are good suggestions
# - gocritic # provides diagnostics that check for bugs, performance and style issues
- gocritic # provides diagnostics that check for bugs, performance and style issues
# Todo enable
#- gocyclo # computes and checks the cyclomatic complexity of functions
# Todo enable - too much for us
#- godot # checks if comments end in a period
#- godot # checks if comments end in a period # Too much for us right now
- goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt
- gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod
- goprintffuncname # checks that printf-like functions are named with f at the end
# Todo enable - ignore for a few int overflow, and fix file permissions
# weak md5 cryptography, Subprocess launched with a potential tainted input
# - gosec # inspects source code for security problems
- iface # checks the incorrect use of interfaces, helping developers avoid interface pollution
# Todo enable : Need fixes
# - intrange # finds places where for loops could make use of an integer range
- intrange # finds places where for loops could make use of an integer range
# Todo enable : Need many fixes
# - lll # reports long lines
- loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap)
Expand All @@ -323,39 +318,32 @@ linters:
- nilnil # checks that there is no simultaneous return of nil error and an invalid value
- noctx # finds sending http request without context.Context
- nolintlint # reports ill-formed or insufficient nolint directives
# Todo enable - maybe too strict for us
# - nonamedreturns # reports all named returns
- nonamedreturns # reports all named returns
- nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL
- perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative
- predeclared # finds code that shadows one of Go's predeclared identifiers
- promlinter # checks Prometheus metrics naming via promlint
- protogetter # reports direct reads from proto message fields when getters should be used
# Todo enable - Some hard to fix things
# - reassign # checks that package variables are not reassigned
- reassign # checks that package variables are not reassigned
# Todo enable - Issue due to model struct
# - recvcheck # checks for receiver type consistency
# Todo enable : Many changes
# - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint
- revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint
- rowserrcheck # checks whether Err of rows is checked successfully
# Todo enable - Need to use non-root logger
# - sloglint # ensure consistent code style when using log/slog
- spancheck # checks for mistakes with OpenTelemetry/Census spans
- sqlclosecheck # checks that sql.Rows and sql.Stmt are closed
# Todo enable : Many changes, but good changes.
# - stylecheck # is a replacement for golint
- stylecheck # is a replacement for golint
- testableexamples # checks if examples are testable (have an expected output)
- testifylint # checks usage of github.com/stretchr/testify
# Todo enable - Might be too strict for us
# - testpackage # makes you use a separate _test package
# - testpackage # makes you use a separate _test package # Not needed - Makes it harder to test unexported package functions.
- tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes
- unconvert # removes unnecessary type conversions
- unparam # reports unused function parameters
- usestdlibvars # detects the possibility to use variables/constants from the Go standard library
- usetesting # reports uses of functions with replacement inside the testing package
# Todo enable - many required fixes
# - wastedassign # finds wasted assignment statements
# Todo enable - many fixes
# - whitespace # detects leading and trailing whitespace
- wastedassign # finds wasted assignment statements
- whitespace # detects leading and trailing whitespace

## Todo : Enable some of them
## you may want to enable
Expand Down Expand Up @@ -390,13 +378,12 @@ linters:
# - dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
# False positives
# - dupword # [useless without config] checks for duplicate words in the source code
# Todo : It gave some useful errors. Should fix
# - err113 # [too strict] checks the errors handling expressions

# It gave some useful errors optimization. Should fix eventually. But this is low priority
# - err113 # [too strict] checks the errors handling expressions #
# - errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted
# - forcetypeassert # [replaced by errcheck] finds forced type assertions
# Todo : rely on this, and skip separate go fmt check in cicd
# - gofmt # [replaced by goimports] checks whether code was gofmt-ed
# Todo : Check this
#- gofumpt # [replaced by goimports, gofumports is not available yet] checks whether code was gofumpt-ed
#- gomodguard # [use more powerful depguard] allow and block lists linter for direct Go module dependencies
- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase
Expand All @@ -405,14 +392,34 @@ linters:
- maintidx # measures the maintainability index of each function
- misspell # [useless] finds commonly misspelled English words in comments
# - nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity
# Todo : might make tests parallel
#- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test
# Todo : Check this. There are some issues to be fixed
# - tagliatelle # checks the struct tags
# - tenv # [deprecated, replaced by usetesting] detects using os.Setenv instead of t.Setenv since Go1.17
#- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers
# - wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines

exclusions:
rules:
# Stores globally accessible icon strings
- path: 'src/config/icon/icon.go'
linters:
- gochecknoglobals
# Stores prerendered styles
- path: 'src/internal/common/style.go'
linters:
- gochecknoglobals
# Some fixed variables like default config paths, version, etc.
- path: 'src/config/fixed_variable.go'
linters:
- gochecknoglobals
# Stores predefined variables, like re-used non-const strings
- path: 'src/internal/common/predefined_variable.go'
linters:
- gochecknoglobals
# Global variables storing config
- path: 'src/internal/common/default_config.go'
linters:
- gochecknoglobals


issues:
# Maximum count of issues with the same text.
Expand Down
60 changes: 17 additions & 43 deletions src/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"os"
Expand All @@ -26,11 +25,10 @@ import (

// Run superfile app
func Run(content embed.FS) {

// Before we open log file, set all "non debug" logs to stdout
utils.SetRootLoggerToStdout(false)

common.LoadInitial_PrerenderedVariables()
common.LoadInitialPrerenderedVariables()
common.LoadAllDefaultConfig(content)

app := &cli.App{
Expand All @@ -43,7 +41,7 @@ func Run(content embed.FS) {
Name: "path-list",
Aliases: []string{"pl"},
Usage: "Print the path to the configuration and directory",
Action: func(c *cli.Context) error {
Action: func(_ *cli.Context) error {
fmt.Printf("%-*s %s\n", 55, lipgloss.NewStyle().Foreground(lipgloss.Color("#66b2ff")).Render("[Configuration file path]"), variable.ConfigFile)
fmt.Printf("%-*s %s\n", 55, lipgloss.NewStyle().Foreground(lipgloss.Color("#ffcc66")).Render("[Hotkeys file path]"), variable.HotkeysFile)
fmt.Printf("%-*s %s\n", 55, lipgloss.NewStyle().Foreground(lipgloss.Color("#66ff66")).Render("[Log file path]"), variable.LogFile)
Expand Down Expand Up @@ -86,32 +84,12 @@ func Run(content embed.FS) {
},
Action: func(c *cli.Context) error {
// If no args are called along with "spf" use current dir
path := ""
firstFilePanelDirs := []string{""}
if c.Args().Present() {
path = c.Args().First()
}

// Setting the config file path
configFileArg := c.String("config-file")

// Validate the config file exists
if configFileArg != "" {
if _, err := os.Stat(configFileArg); err != nil {
log.Fatalf("Error: While reading config file '%s' from argument : %v", configFileArg, err)
} else {
variable.ConfigFile = configFileArg
}
firstFilePanelDirs = c.Args().Slice()
}

hotkeyFileArg := c.String("hotkey-file")

if hotkeyFileArg != "" {
if _, err := os.Stat(hotkeyFileArg); err != nil {
log.Fatalf("Error: While reading hotkey file '%s' from argument : %v", hotkeyFileArg, err)
} else {
variable.HotkeysFile = hotkeyFileArg
}
}
variable.UpdateVarFromCliArgs(c)

InitConfigFile()

Expand All @@ -120,15 +98,11 @@ func Run(content embed.FS) {
hasTrash = false
}

variable.FixHotkeys = c.Bool("fix-hotkeys")
variable.FixConfigFile = c.Bool("fix-config-file")
variable.PrintLastDir = c.Bool("print-last-dir")

firstUse := checkFirstUse()

p := tea.NewProgram(internal.InitialModel(path, firstUse, hasTrash), tea.WithAltScreen(), tea.WithMouseCellMotion())
p := tea.NewProgram(internal.InitialModel(firstFilePanelDirs, firstUse, hasTrash), tea.WithAltScreen(), tea.WithMouseCellMotion())
if _, err := p.Run(); err != nil {
log.Fatalf("Alas, there's been an error: %v", err)
utils.PrintfAndExit("Alas, there's been an error: %v", err)
}

// This must be after calling internal.InitialModel()
Expand All @@ -147,7 +121,7 @@ func Run(content embed.FS) {

err := app.Run(os.Args)
if err != nil {
log.Fatalln(err)
utils.PrintlnAndExit(err)
}
}

Expand All @@ -161,7 +135,7 @@ func InitConfigFile() {
variable.SuperFileStateDir,
variable.ThemeFolder,
); err != nil {
log.Fatalln("Error creating directories:", err)
utils.PrintlnAndExit("Error creating directories:", err)
}

// Create files
Expand All @@ -171,27 +145,27 @@ func InitConfigFile() {
variable.ThemeFileVersion,
variable.ToggleFooter,
); err != nil {
log.Fatalln("Error creating files:", err)
utils.PrintlnAndExit("Error creating files:", err)
}

// Write config file
if err := writeConfigFile(variable.ConfigFile, common.ConfigTomlString); err != nil {
log.Fatalln("Error writing config file:", err)
utils.PrintlnAndExit("Error writing config file:", err)
}

if err := writeConfigFile(variable.HotkeysFile, common.HotkeysTomlString); err != nil {
log.Fatalln("Error writing config file:", err)
utils.PrintlnAndExit("Error writing config file:", err)
}

if err := initJsonFile(variable.PinnedFile); err != nil {
log.Fatalln("Error initializing json file:", err)
if err := initJSONFile(variable.PinnedFile); err != nil {
utils.PrintlnAndExit("Error initializing json file:", err)
}
}

// We are initializing these, but not sure if we are ever using them
func InitTrash() error {
// Create trash directories
if runtime.GOOS != variable.OS_DARWIN {
if runtime.GOOS != utils.OsDarwin {
err := createDirectories(
variable.CustomTrashDirectory,
variable.CustomTrashDirectoryFiles,
Expand Down Expand Up @@ -240,7 +214,7 @@ func checkFirstUse() bool {
if _, err := os.Stat(file); os.IsNotExist(err) {
firstUse = true
if err = os.WriteFile(file, nil, 0644); err != nil {
log.Fatalf("Failed to create file: %v", err)
utils.PrintfAndExit("Failed to create file: %v", err)
}
}
return firstUse
Expand All @@ -256,7 +230,7 @@ func writeConfigFile(path, data string) error {
return nil
}

func initJsonFile(path string) error {
func initJSONFile(path string) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
if err = os.WriteFile(path, []byte("null"), 0644); err != nil {
return fmt.Errorf("failed to initialize json file %s: %w", path, err)
Expand Down
Loading
Loading