1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-07-03 00:57:52 +02:00

Enable revive linter, and fix a bunch of warnings

I took the set of enabled checks from revive's recommended configuration [1],
and removed some that I didn't like. There might be other useful checks in
revive that we might want to enable, but this is a nice improvement already.

The bulk of the changes here are removing unnecessary else statements after
returns, but there are a few others too.

[1] https://github.com/mgechev/revive?tab=readme-ov-file#recommended-configuration
This commit is contained in:
Stefan Haller
2025-06-30 19:13:12 +02:00
parent 7aa426fa71
commit ca05a2ccea
47 changed files with 152 additions and 170 deletions

View File

@ -11,6 +11,7 @@ linters:
- nakedret - nakedret
- nolintlint - nolintlint
- prealloc - prealloc
- revive
- thelper - thelper
- tparallel - tparallel
- unconvert - unconvert
@ -76,6 +77,20 @@ linters:
dot-import-whitelist: dot-import-whitelist:
- github.com/jesseduffield/lazygit/pkg/integration/components - github.com/jesseduffield/lazygit/pkg/integration/components
revive:
severity: warning
rules:
- name: atomic
- name: context-as-argument
- name: context-keys-type
- name: error-naming
- name: var-declaration
- name: package-comments
- name: range
- name: time-naming
- name: indent-error-flow
- name: errorf
- name: superfluous-else
exclusions: exclusions:
generated: lax generated: lax
presets: presets:

View File

@ -86,9 +86,9 @@ func newLogger(cfg config.AppConfigurer) *logrus.Entry {
log.Fatal(err) log.Fatal(err)
} }
return logs.NewDevelopmentLogger(logPath) return logs.NewDevelopmentLogger(logPath)
} else {
return logs.NewProductionLogger()
} }
return logs.NewProductionLogger()
} }
// NewApp bootstrap a new application // NewApp bootstrap a new application

View File

@ -21,9 +21,8 @@ type TodoLine struct {
func (self *TodoLine) ToString() string { func (self *TodoLine) ToString() string {
if self.Action == "break" { if self.Action == "break" {
return self.Action + "\n" return self.Action + "\n"
} else {
return self.Action + " " + self.Commit.Hash() + " " + self.Commit.Name + "\n"
} }
return self.Action + " " + self.Commit.Hash() + " " + self.Commit.Name + "\n"
} }
func TodoLinesToString(todoLines []TodoLine) string { func TodoLinesToString(todoLines []TodoLine) string {

View File

@ -356,9 +356,8 @@ func parseDifference(track string, regexStr string) string {
match := re.FindStringSubmatch(track) match := re.FindStringSubmatch(track)
if len(match) > 1 { if len(match) > 1 {
return match[1] return match[1]
} else {
return "0"
} }
return "0"
} }
// TODO: only look at the new reflog commits, and otherwise store the recencies in // TODO: only look at the new reflog commits, and otherwise store the recencies in

View File

@ -149,9 +149,8 @@ func (self *CommitCommands) CommitEditorCmdObj() *oscommands.CmdObj {
func (self *CommitCommands) signoffFlag() string { func (self *CommitCommands) signoffFlag() string {
if self.UserConfig().Git.Commit.SignOff { if self.UserConfig().Git.Commit.SignOff {
return "--signoff" return "--signoff"
} else {
return ""
} }
return ""
} }
func (self *CommitCommands) GetCommitMessage(commitHash string) (string, error) { func (self *CommitCommands) GetCommitMessage(commitHash string) (string, error) {

View File

@ -97,7 +97,7 @@ func buildGitCommon(deps commonDeps) *GitCommon {
func buildRepo() *gogit.Repository { func buildRepo() *gogit.Repository {
// TODO: think of a way to actually mock this out // TODO: think of a way to actually mock this out
var repo *gogit.Repository = nil var repo *gogit.Repository
return repo return repo
} }

View File

@ -32,9 +32,8 @@ func (self *GitCommandBuilder) ArgIf(condition bool, ifTrue ...string) *GitComma
func (self *GitCommandBuilder) ArgIfElse(condition bool, ifTrue string, ifFalse string) *GitCommandBuilder { func (self *GitCommandBuilder) ArgIfElse(condition bool, ifTrue string, ifFalse string) *GitCommandBuilder {
if condition { if condition {
return self.Arg(ifTrue) return self.Arg(ifTrue)
} else {
return self.Arg(ifFalse)
} }
return self.Arg(ifFalse)
} }
func (self *GitCommandBuilder) Config(value string) *GitCommandBuilder { func (self *GitCommandBuilder) Config(value string) *GitCommandBuilder {

View File

@ -327,9 +327,8 @@ func (self *RebaseCommands) MoveFixupCommitDown(commits []*models.Commit, target
func todoFromCommit(commit *models.Commit) utils.Todo { func todoFromCommit(commit *models.Commit) utils.Todo {
if commit.Action == todo.UpdateRef { if commit.Action == todo.UpdateRef {
return utils.Todo{Ref: commit.Name} return utils.Todo{Ref: commit.Name}
} else {
return utils.Todo{Hash: commit.Hash()}
} }
return utils.Todo{Hash: commit.Hash()}
} }
// Sets the action for the given commits in the git-rebase-todo file // Sets the action for the given commits in the git-rebase-todo file
@ -412,9 +411,9 @@ func (self *RebaseCommands) BeginInteractiveRebaseForCommit(
instruction: daemon.NewInsertBreakInstruction(), instruction: daemon.NewInsertBreakInstruction(),
keepCommitsThatBecomeEmpty: keepCommitsThatBecomeEmpty, keepCommitsThatBecomeEmpty: keepCommitsThatBecomeEmpty,
}).Run() }).Run()
} else {
return self.BeginInteractiveRebaseForCommitRange(commits, commitIndex, commitIndex, keepCommitsThatBecomeEmpty)
} }
return self.BeginInteractiveRebaseForCommitRange(commits, commitIndex, commitIndex, keepCommitsThatBecomeEmpty)
} }
func (self *RebaseCommands) BeginInteractiveRebaseForCommitRange( func (self *RebaseCommands) BeginInteractiveRebaseForCommitRange(
@ -574,7 +573,7 @@ func getBaseHashOrRoot(commits []*models.Commit, index int) string {
// at time of writing) // at time of writing)
if index < len(commits) { if index < len(commits) {
return commits[index].Hash() return commits[index].Hash()
} else { }
return "--root" return "--root"
} }
}

View File

@ -21,7 +21,7 @@ type RepoPaths struct {
isBareRepo bool isBareRepo bool
} }
var gitPathFormatVersion GitVersion = GitVersion{2, 31, 0, ""} var gitPathFormatVersion = GitVersion{2, 31, 0, ""}
// Path to the current worktree. If we're in the main worktree, this will // Path to the current worktree. If we're in the main worktree, this will
// be the same as RepoPath() // be the same as RepoPath()

View File

@ -184,9 +184,7 @@ func TestGetRepoPaths(t *testing.T) {
Expected: nil, Expected: nil,
Err: func(getRevParseArgs argFn) error { Err: func(getRevParseArgs argFn) error {
args := strings.Join(getRevParseArgs(), " ") args := strings.Join(getRevParseArgs(), " ")
return errors.New( return fmt.Errorf("'git %v --show-toplevel --absolute-git-dir --git-common-dir --is-bare-repository --show-superproject-working-tree' failed: fatal: invalid gitfile format: /path/to/repo/worktree2/.git", args)
fmt.Sprintf("'git %v --show-toplevel --absolute-git-dir --git-common-dir --is-bare-repository --show-superproject-working-tree' failed: fatal: invalid gitfile format: /path/to/repo/worktree2/.git", args),
)
}, },
}, },
} }

View File

@ -49,9 +49,8 @@ func (self *SubmoduleCommands) GetConfigs(parentModule *models.SubmoduleConfig)
if len(matches) > 0 { if len(matches) > 0 {
return matches[1], true return matches[1], true
} else {
return "", false
} }
return "", false
} }
configs := []*models.SubmoduleConfig{} configs := []*models.SubmoduleConfig{}

View File

@ -66,9 +66,8 @@ func (self *WorkingTreeCommands) UnstageAll() error {
func (self *WorkingTreeCommands) UnStageFile(paths []string, tracked bool) error { func (self *WorkingTreeCommands) UnStageFile(paths []string, tracked bool) error {
if tracked { if tracked {
return self.UnstageTrackedFiles(paths) return self.UnstageTrackedFiles(paths)
} else {
return self.UnstageUntrackedFiles(paths)
} }
return self.UnstageUntrackedFiles(paths)
} }
func (self *WorkingTreeCommands) UnstageTrackedFiles(paths []string) error { func (self *WorkingTreeCommands) UnstageTrackedFiles(paths []string) error {

View File

@ -46,9 +46,8 @@ func (self *HostingServiceMgr) GetPullRequestURL(from string, to string) (string
if to == "" { if to == "" {
return gitService.getPullRequestURLIntoDefaultBranch(url.QueryEscape(from)), nil return gitService.getPullRequestURLIntoDefaultBranch(url.QueryEscape(from)), nil
} else {
return gitService.getPullRequestURLIntoTargetBranch(url.QueryEscape(from), url.QueryEscape(to)), nil
} }
return gitService.getPullRequestURLIntoTargetBranch(url.QueryEscape(from), url.QueryEscape(to)), nil
} }
func (self *HostingServiceMgr) GetCommitURL(commitHash string) (string, error) { func (self *HostingServiceMgr) GetCommitURL(commitHash string) (string, error) {

View File

@ -211,9 +211,8 @@ func (p *PatchBuilder) RenderPatchForFile(opts RenderPatchForFileOpts) string {
if opts.Plain { if opts.Plain {
return patch.FormatPlain() return patch.FormatPlain()
} else {
return patch.FormatView(FormatViewOpts{})
} }
return patch.FormatView(FormatViewOpts{})
} }
func (p *PatchBuilder) renderEachFilePatch(plain bool) []string { func (p *PatchBuilder) renderEachFilePatch(plain bool) []string {

View File

@ -84,9 +84,9 @@ func (self *patchTransformer) transformHeader() []string {
result = append(result, line) result = append(result, line)
} }
return result return result
} else {
return self.patch.header
} }
return self.patch.header
} }
func (self *patchTransformer) transformHunks() []*Hunk { func (self *patchTransformer) transformHunks() []*Hunk {

View File

@ -144,7 +144,7 @@ func (self *MenuViewModel) GetNonModelItems() []*NonModelItem {
} }
menuItems := self.FilteredListViewModel.GetItems() menuItems := self.FilteredListViewModel.GetItems()
var prevSection *types.MenuSection = nil var prevSection *types.MenuSection
for i, menuItem := range menuItems { for i, menuItem := range menuItems {
if menuItem.Section != nil && menuItem.Section != prevSection { if menuItem.Section != nil && menuItem.Section != prevSection {
if prevSection != nil { if prevSection != nil {

View File

@ -79,9 +79,8 @@ func (self *SuggestionsContext) RefreshSuggestions() {
if findSuggestionsFn != nil { if findSuggestionsFn != nil {
suggestions := findSuggestionsFn(self.c.GetPromptInput()) suggestions := findSuggestionsFn(self.c.GetPromptInput())
return func() { self.SetSuggestions(suggestions) } return func() { self.SetSuggestions(suggestions) }
} else {
return func() {}
} }
return func() {}
}) })
} }

View File

@ -77,9 +77,8 @@ func (self *ListCursor) SetSelectionRangeAndMode(selectedIdx, rangeStartIdx int,
func (self *ListCursor) GetSelectionRangeAndMode() (int, int, RangeSelectMode) { func (self *ListCursor) GetSelectionRangeAndMode() (int, int, RangeSelectMode) {
if self.IsSelectingRange() { if self.IsSelectingRange() {
return self.selectedIdx, self.rangeStartIdx, self.rangeSelectMode return self.selectedIdx, self.rangeStartIdx, self.rangeSelectMode
} else {
return self.selectedIdx, self.selectedIdx, self.rangeSelectMode
} }
return self.selectedIdx, self.selectedIdx, self.rangeSelectMode
} }
func (self *ListCursor) clampValue(value int) int { func (self *ListCursor) clampValue(value int) int {

View File

@ -24,7 +24,7 @@ func OnFocusWrapper(f func() error) func(opts types.OnFocusOpts) error {
func (gui *Gui) defaultSideContext() types.Context { func (gui *Gui) defaultSideContext() types.Context {
if gui.State.Modes.Filtering.Active() { if gui.State.Modes.Filtering.Active() {
return gui.State.Contexts.LocalCommits return gui.State.Contexts.LocalCommits
} else { }
return gui.State.Contexts.Files return gui.State.Contexts.Files
} }
}

View File

@ -54,9 +54,8 @@ func (self *BisectController) openMenu(commit *models.Commit) error {
info := self.c.Git().Bisect.GetInfo() info := self.c.Git().Bisect.GetInfo()
if info.Started() { if info.Started() {
return self.openMidBisectMenu(info, commit) return self.openMidBisectMenu(info, commit)
} else {
return self.openStartBisectMenu(info, commit)
} }
return self.openStartBisectMenu(info, commit)
} }
func (self *BisectController) openMidBisectMenu(info *git_commands.BisectInfo, commit *models.Commit) error { func (self *BisectController) openMidBisectMenu(info *git_commands.BisectInfo, commit *models.Commit) error {
@ -280,12 +279,12 @@ func (self *BisectController) afterBisectMarkRefresh(selectCurrent bool, waitToR
if waitToReselect { if waitToReselect {
return self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{}, Then: selectFn}) return self.c.Refresh(types.RefreshOptions{Mode: types.SYNC, Scope: []types.RefreshableView{}, Then: selectFn})
} else { }
_ = selectFn() _ = selectFn()
return self.c.Helpers().Bisect.PostBisectCommandRefresh() return self.c.Helpers().Bisect.PostBisectCommandRefresh()
} }
}
func (self *BisectController) selectCurrentBisectCommit() { func (self *BisectController) selectCurrentBisectCommit() {
info := self.c.Git().Bisect.GetInfo() info := self.c.Git().Bisect.GetInfo()

View File

@ -657,7 +657,8 @@ func (self *BranchesController) fastForward(branch *models.Branch) error {
) )
_ = self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC}) _ = self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC})
return err return err
} else { }
self.c.LogAction(action) self.c.LogAction(action)
err := self.c.Git().Sync.FastForward( err := self.c.Git().Sync.FastForward(
@ -665,7 +666,6 @@ func (self *BranchesController) fastForward(branch *models.Branch) error {
) )
_ = self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}}) _ = self.c.Refresh(types.RefreshOptions{Mode: types.ASYNC, Scope: []types.RefreshableView{types.BRANCHES}})
return err return err
}
}) })
} }

View File

@ -189,9 +189,9 @@ func (self *CustomPatchOptionsMenuAction) handleMovePatchIntoWorkingTree() error
}) })
return nil return nil
} else {
return pull(false)
} }
return pull(false)
} }
func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommit() error { func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommit() error {

View File

@ -901,11 +901,10 @@ func (self *FilesController) setStatusFiltering(filter filetree.FileTreeDisplayF
// because the untracked files filter applies when running `git status`. // because the untracked files filter applies when running `git status`.
if previousFilter != filter && (previousFilter == filetree.DisplayUntracked || filter == filetree.DisplayUntracked) { if previousFilter != filter && (previousFilter == filetree.DisplayUntracked || filter == filetree.DisplayUntracked) {
return self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC}) return self.c.Refresh(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}, Mode: types.ASYNC})
} else {
self.c.PostRefreshUpdate(self.context())
return nil
} }
self.c.PostRefreshUpdate(self.context())
return nil
} }
func (self *FilesController) edit(nodes []*filetree.FileNode) error { func (self *FilesController) edit(nodes []*filetree.FileNode) error {

View File

@ -37,9 +37,9 @@ func (self *GpgHelper) WithGpgHandling(cmdObj *oscommands.CmdObj, configKey git_
} }
return err return err
} else {
return self.runAndStream(cmdObj, waitingStatus, onSuccess, refreshScope)
} }
return self.runAndStream(cmdObj, waitingStatus, onSuccess, refreshScope)
} }
func (self *GpgHelper) runAndStream(cmdObj *oscommands.CmdObj, waitingStatus string, onSuccess func() error, refreshScope []types.RefreshableView) error { func (self *GpgHelper) runAndStream(cmdObj *oscommands.CmdObj, waitingStatus string, onSuccess func() error, refreshScope []types.RefreshableView) error {

View File

@ -162,9 +162,8 @@ func (self *MergeAndRebaseHelper) CheckMergeOrRebaseWithRefreshOptions(result er
} else if strings.Contains(result.Error(), "No rebase in progress?") { } else if strings.Contains(result.Error(), "No rebase in progress?") {
// assume in this case that we're already done // assume in this case that we're already done
return nil return nil
} else {
return self.CheckForConflicts(result)
} }
return self.CheckForConflicts(result)
} }
func (self *MergeAndRebaseHelper) CheckMergeOrRebase(result error) error { func (self *MergeAndRebaseHelper) CheckMergeOrRebase(result error) error {

View File

@ -56,9 +56,9 @@ func (self *RefsHelper) CheckoutRef(ref string, options types.CheckoutRefOptions
withCheckoutStatus := func(f func(gocui.Task) error) error { withCheckoutStatus := func(f func(gocui.Task) error) error {
if found { if found {
return self.c.WithInlineStatus(localBranch, types.ItemOperationCheckingOut, context.LOCAL_BRANCHES_CONTEXT_KEY, f) return self.c.WithInlineStatus(localBranch, types.ItemOperationCheckingOut, context.LOCAL_BRANCHES_CONTEXT_KEY, f)
} else {
return self.c.WithWaitingStatus(waitingStatus, f)
} }
return self.c.WithWaitingStatus(waitingStatus, f)
} }
return withCheckoutStatus(func(gocui.Task) error { return withCheckoutStatus(func(gocui.Task) error {

View File

@ -385,9 +385,8 @@ func splitMainPanelSideBySide(args WindowArrangementArgs) bool {
default: default:
if args.Width < 200 && args.Height > 30 { // 2 80 character width panels + 40 width for side panel if args.Width < 200 && args.Height > 30 { // 2 80 character width panels + 40 width for side panel
return false return false
} else {
return true
} }
return true
} }
} }
@ -431,13 +430,13 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [
Window: window, Window: window,
Weight: 1, Weight: 1,
} }
} else { }
return &boxlayout.Box{ return &boxlayout.Box{
Window: window, Window: window,
Size: 0, Size: 0,
} }
} }
}
return []*boxlayout.Box{ return []*boxlayout.Box{
fullHeightBox("status"), fullHeightBox("status"),
@ -469,7 +468,8 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [
accordionBox(&boxlayout.Box{Window: "commits", Weight: 1}), accordionBox(&boxlayout.Box{Window: "commits", Weight: 1}),
accordionBox(getDefaultStashWindowBox(args)), accordionBox(getDefaultStashWindowBox(args)),
} }
} else { }
squashedHeight := 1 squashedHeight := 1
if height >= 21 { if height >= 21 {
squashedHeight = 3 squashedHeight = 3
@ -481,13 +481,13 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [
Window: window, Window: window,
Weight: 1, Weight: 1,
} }
} else { }
return &boxlayout.Box{ return &boxlayout.Box{
Window: window, Window: window,
Size: squashedHeight, Size: squashedHeight,
} }
} }
}
return []*boxlayout.Box{ return []*boxlayout.Box{
squashedSidePanelBox("status"), squashedSidePanelBox("status"),
@ -498,4 +498,3 @@ func sidePanelChildren(args WindowArrangementArgs) func(width int, height int) [
} }
} }
} }
}

View File

@ -245,7 +245,7 @@ func (self *WorkingTreeHelper) commitPrefixConfigsForRepo() []config.CommitPrefi
cfg, ok := self.c.UserConfig().Git.CommitPrefixes[self.c.Git().RepoPaths.RepoName()] cfg, ok := self.c.UserConfig().Git.CommitPrefixes[self.c.Git().RepoPaths.RepoName()]
if ok { if ok {
return append(cfg, self.c.UserConfig().Git.CommitPrefix...) return append(cfg, self.c.UserConfig().Git.CommitPrefix...)
} else { }
return self.c.UserConfig().Git.CommitPrefix return self.c.UserConfig().Git.CommitPrefix
} }
}

View File

@ -133,7 +133,8 @@ func (self *WorktreeHelper) NewWorktreeCheckout(base string, canCheckoutBase boo
}) })
return nil return nil
} else { }
// prompt for the new branch name where a blank means we just check out the branch // prompt for the new branch name where a blank means we just check out the branch
self.c.Prompt(types.PromptOpts{ self.c.Prompt(types.PromptOpts{
Title: self.c.Tr.NewBranchName, Title: self.c.Tr.NewBranchName,
@ -149,7 +150,6 @@ func (self *WorktreeHelper) NewWorktreeCheckout(base string, canCheckoutBase boo
}) })
return nil return nil
}
}, },
}) })

View File

@ -92,13 +92,15 @@ func (self *SyncController) push(currentBranch *models.Branch) error {
opts := pushOpts{remoteBranchStoredLocally: currentBranch.RemoteBranchStoredLocally()} opts := pushOpts{remoteBranchStoredLocally: currentBranch.RemoteBranchStoredLocally()}
if currentBranch.IsBehindForPush() { if currentBranch.IsBehindForPush() {
return self.requestToForcePush(currentBranch, opts) return self.requestToForcePush(currentBranch, opts)
} else { }
return self.pushAux(currentBranch, opts) return self.pushAux(currentBranch, opts)
} }
} else {
if self.c.Git().Config.GetPushToCurrent() { if self.c.Git().Config.GetPushToCurrent() {
return self.pushAux(currentBranch, pushOpts{setUpstream: true}) return self.pushAux(currentBranch, pushOpts{setUpstream: true})
} else { }
return self.c.Helpers().Upstream.PromptForUpstreamWithInitialContent(currentBranch, func(upstream string) error { return self.c.Helpers().Upstream.PromptForUpstreamWithInitialContent(currentBranch, func(upstream string) error {
upstreamRemote, upstreamBranch, err := self.c.Helpers().Upstream.ParseUpstream(upstream) upstreamRemote, upstreamBranch, err := self.c.Helpers().Upstream.ParseUpstream(upstream)
if err != nil { if err != nil {
@ -112,8 +114,6 @@ func (self *SyncController) push(currentBranch *models.Branch) error {
}) })
}) })
} }
}
}
func (self *SyncController) pull(currentBranch *models.Branch) error { func (self *SyncController) pull(currentBranch *models.Branch) error {
action := self.c.Tr.Actions.Pull action := self.c.Tr.Actions.Pull

View File

@ -138,9 +138,8 @@ func (self *FileTreeViewModel) findNewSelectedIdx(prevNodes []*FileNode, currNod
} }
if node.File != nil && node.File.IsRename() { if node.File != nil && node.File.IsRename() {
return node.File.Names() return node.File.Names()
} else {
return []string{node.path}
} }
return []string{node.path}
} }
for _, prevNode := range prevNodes { for _, prevNode := range prevNodes {

View File

@ -611,9 +611,9 @@ func initialScreenMode(startArgs appTypes.StartArgs, config config.AppConfigurer
return parseScreenModeArg(startArgs.ScreenMode) return parseScreenModeArg(startArgs.ScreenMode)
} else if startArgs.FilterPath != "" || startArgs.GitArg != appTypes.GitArgNone { } else if startArgs.FilterPath != "" || startArgs.GitArg != appTypes.GitArgNone {
return types.SCREEN_HALF return types.SCREEN_HALF
} else {
return parseScreenModeArg(config.GetUserConfig().Gui.ScreenMode)
} }
return parseScreenModeArg(config.GetUserConfig().Gui.ScreenMode)
} }
func parseScreenModeArg(screenModeArg string) types.ScreenMode { func parseScreenModeArg(screenModeArg string) types.ScreenMode {

View File

@ -17,9 +17,9 @@ func (gui *Gui) informationStr() string {
donate := style.FgMagenta.Sprint(style.PrintHyperlink(gui.c.Tr.Donate, constants.Links.Donate)) donate := style.FgMagenta.Sprint(style.PrintHyperlink(gui.c.Tr.Donate, constants.Links.Donate))
askQuestion := style.FgYellow.Sprint(style.PrintHyperlink(gui.c.Tr.AskQuestion, constants.Links.Discussions)) askQuestion := style.FgYellow.Sprint(style.PrintHyperlink(gui.c.Tr.AskQuestion, constants.Links.Discussions))
return fmt.Sprintf("%s %s %s", donate, askQuestion, gui.Config.GetVersion()) return fmt.Sprintf("%s %s %s", donate, askQuestion, gui.Config.GetVersion())
} else {
return gui.Config.GetVersion()
} }
return gui.Config.GetVersion()
} }
func (gui *Gui) handleInfoClick() error { func (gui *Gui) handleInfoClick() error {

View File

@ -41,9 +41,8 @@ func GetKey(key string) types.Key {
binding, ok := config.KeyByLabel[strings.ToLower(key)] binding, ok := config.KeyByLabel[strings.ToLower(key)]
if !ok { if !ok {
log.Fatalf("Unrecognized key %s for keybinding. For permitted values see %s", strings.ToLower(key), constants.Links.Docs.CustomKeybindings) log.Fatalf("Unrecognized key %s for keybinding. For permitted values see %s", strings.ToLower(key), constants.Links.Docs.CustomKeybindings)
} else {
return binding
} }
return binding
} else if runeCount == 1 { } else if runeCount == 1 {
return []rune(key)[0] return []rune(key)[0]
} }

View File

@ -50,9 +50,8 @@ func (s Selection) bounds(c *mergeConflict) (int, int) {
case TOP: case TOP:
if c.hasAncestor() { if c.hasAncestor() {
return c.start, c.ancestor return c.start, c.ancestor
} else {
return c.start, c.target
} }
return c.start, c.target
case MIDDLE: case MIDDLE:
return c.ancestor, c.target return c.ancestor, c.target
case BOTTOM: case BOTTOM:
@ -72,7 +71,6 @@ func (s Selection) selected(c *mergeConflict, idx int) bool {
func availableSelections(c *mergeConflict) []Selection { func availableSelections(c *mergeConflict) []Selection {
if c.hasAncestor() { if c.hasAncestor() {
return []Selection{TOP, MIDDLE, BOTTOM} return []Selection{TOP, MIDDLE, BOTTOM}
} else { }
return []Selection{TOP, BOTTOM} return []Selection{TOP, BOTTOM}
} }
}

View File

@ -25,9 +25,8 @@ func calculateNewOriginWithNeededAndWantedIdx(currentOrigin int, bufferHeight in
requiredChange := wantToSeeIdx - bottom requiredChange := wantToSeeIdx - bottom
allowedChange := needToSeeIdx - origin allowedChange := needToSeeIdx - origin
return origin + min(requiredChange, allowedChange) return origin + min(requiredChange, allowedChange)
} else {
return origin
} }
return origin
} }
func getNeedAndWantLineIdx(firstLineIdx int, lastLineIdx int, selectedLineIdx int, mode selectMode) (int, int) { func getNeedAndWantLineIdx(firstLineIdx int, lastLineIdx int, selectedLineIdx int, mode selectMode) (int, int) {
@ -37,9 +36,8 @@ func getNeedAndWantLineIdx(firstLineIdx int, lastLineIdx int, selectedLineIdx in
case RANGE: case RANGE:
if selectedLineIdx == firstLineIdx { if selectedLineIdx == firstLineIdx {
return firstLineIdx, lastLineIdx return firstLineIdx, lastLineIdx
} else {
return lastLineIdx, firstLineIdx
} }
return lastLineIdx, firstLineIdx
case HUNK: case HUNK:
return firstLineIdx, lastLineIdx return firstLineIdx, lastLineIdx
default: default:

View File

@ -267,9 +267,8 @@ func (s *State) SelectedViewRange() (int, int) {
case RANGE: case RANGE:
if s.rangeStartLineIdx > s.selectedLineIdx { if s.rangeStartLineIdx > s.selectedLineIdx {
return s.selectedLineIdx, s.rangeStartLineIdx return s.selectedLineIdx, s.rangeStartLineIdx
} else {
return s.rangeStartLineIdx, s.selectedLineIdx
} }
return s.rangeStartLineIdx, s.selectedLineIdx
case LINE: case LINE:
return s.selectedLineIdx, s.selectedLineIdx return s.selectedLineIdx, s.selectedLineIdx
default: default:

View File

@ -145,9 +145,8 @@ func GetCommitListDisplayStrings(
getGraphLine = func(idx int) string { getGraphLine = func(idx int) string {
if idx >= graphOffset { if idx >= graphOffset {
return graphLines[idx-graphOffset] return graphLines[idx-graphOffset]
} else {
return ""
} }
return ""
} }
} }
} else { } else {
@ -305,9 +304,8 @@ func getBisectStatus(index int, commitHash string, bisectInfo *git_commands.Bise
} else { } else {
if bisectBounds != nil && index >= bisectBounds.newIndex && index <= bisectBounds.oldIndex { if bisectBounds != nil && index >= bisectBounds.newIndex && index <= bisectBounds.oldIndex {
return BisectStatusCandidate return BisectStatusCandidate
} else {
return BisectStatusNone
} }
return BisectStatusNone
} }
// should never land here // should never land here

View File

@ -63,9 +63,8 @@ func commitFilePatchStatus(node *filetree.Node[models.CommitFile], tree *filetre
return patchBuilder.GetFileStatus(file.Path, tree.GetRef().RefName()) == patch.UNSELECTED return patchBuilder.GetFileStatus(file.Path, tree.GetRef().RefName()) == patch.UNSELECTED
}) { }) {
return patch.UNSELECTED return patch.UNSELECTED
} else {
return patch.PART
} }
return patch.PART
} }
func renderAux[T any]( func renderAux[T any](

View File

@ -177,7 +177,7 @@ func getBoxDrawingChars(up, down, left, right bool) (string, string) {
return "╶", "─" return "╶", "─"
} else if !up && !down && !left && !right { } else if !up && !down && !left && !right {
return " ", " " return " ", " "
} else { }
panic("should not be possible") panic("should not be possible")
} }
}

View File

@ -246,9 +246,8 @@ func getNextPipes(prevPipes []Pipe, commit *models.Commit, getStyle func(c *mode
for i := pipe.toPos; i > pos; i-- { for i := pipe.toPos; i > pos; i-- {
if takenSpots.Includes(int(i)) || traversedSpots.Includes(int(i)) { if takenSpots.Includes(int(i)) || traversedSpots.Includes(int(i)) {
break break
} else {
last = i
} }
last = i
} }
newPipes = append(newPipes, Pipe{ newPipes = append(newPipes, Pipe{
fromPos: pipe.toPos, fromPos: pipe.toPos,

View File

@ -260,7 +260,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (*exec.Cmd, io.Reader), p
callThen() callThen()
break outer break outer
case line, ok = <-lineChan: case line, ok = <-lineChan:
break // process line below
} }
loadingMutex.Lock() loadingMutex.Lock()

View File

@ -167,7 +167,7 @@ func (d *BlankLineReader) Read(p []byte) (n int, err error) {
return 0, io.EOF return 0, io.EOF
} }
d.linesYielded += 1 d.linesYielded++
p[0] = '\n' p[0] = '\n'
return 1, nil return 1, nil
} }

View File

@ -44,9 +44,8 @@ func WithPadding(str string, padding int, alignment Alignment) string {
space := strings.Repeat(" ", padding-width) space := strings.Repeat(" ", padding-width)
if alignment == AlignLeft { if alignment == AlignLeft {
return str + space return str + space
} else {
return space + str
} }
return space + str
} }
// defaults to left-aligning each column. If you want to set the alignment of // defaults to left-aligning each column. If you want to set the alignment of
@ -187,9 +186,8 @@ func TruncateWithEllipsis(str string, limit int) string {
func SafeTruncate(str string, limit int) string { func SafeTruncate(str string, limit int) string {
if len(str) > limit { if len(str) > limit {
return str[0:limit] return str[0:limit]
} else {
return str
} }
return str
} }
const COMMIT_HASH_SHORT_SIZE = 8 const COMMIT_HASH_SHORT_SIZE = 8

View File

@ -9,7 +9,7 @@ func TestOnceWriter(t *testing.T) {
innerWriter := bytes.NewBuffer(nil) innerWriter := bytes.NewBuffer(nil)
counter := 0 counter := 0
onceWriter := NewOnceWriter(innerWriter, func() { onceWriter := NewOnceWriter(innerWriter, func() {
counter += 1 counter++
}) })
_, _ = onceWriter.Write([]byte("hello")) _, _ = onceWriter.Write([]byte("hello"))
_, _ = onceWriter.Write([]byte("hello")) _, _ = onceWriter.Write([]byte("hello"))

View File

@ -45,9 +45,8 @@ func ModuloWithWrap(n, max int) int {
return n % max return n % max
} else if n < 0 { } else if n < 0 {
return max + n return max + n
} else {
return n
} }
return n
} }
func FindStringSubmatch(str string, regexpStr string) (bool, []string) { func FindStringSubmatch(str string, regexpStr string) (bool, []string) {

View File

@ -224,13 +224,11 @@ func TestTransformNode(t *testing.T) {
} else if node.ShortTag() == "!!str" { } else if node.ShortTag() == "!!str" {
// We have already transformed it, // We have already transformed it,
return nil return nil
} else { }
return fmt.Errorf("Node was of bad type") return fmt.Errorf("Node was of bad type")
} }
} else {
return fmt.Errorf("Node was not a scalar") return fmt.Errorf("Node was not a scalar")
} }
}
tests := []struct { tests := []struct {
name string name string