Skip to content

Commit 50fab97

Browse files
committed
fix default command
1 parent c5b7ee4 commit 50fab97

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed

cmd/cmd.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,13 @@ func PrepareConsoleLoggerLevel(defaultLevel log.Level) func(context.Context, *cl
132132
return ctx, nil
133133
}
134134
}
135+
136+
func isValidDefaultSubCommand(cmd *cli.Command) (string, bool) {
137+
// Dirty patch for urfave/cli's strange design.
138+
// "./gitea bad-cmd" should not start the web server.
139+
rootArgs := cmd.Root().Args().Slice()
140+
if len(rootArgs) != 0 && rootArgs[0] != cmd.Name {
141+
return rootArgs[0], false
142+
}
143+
return "", true
144+
}

cmd/cmd_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2025 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package cmd
5+
6+
import (
7+
"context"
8+
"github.com/stretchr/testify/assert"
9+
"github.com/urfave/cli/v3"
10+
"testing"
11+
)
12+
13+
func TestDefaultCommand(t *testing.T) {
14+
test := func(t *testing.T, args []string, expectedRetName string, expectedRetValid bool) {
15+
called := false
16+
cmd := &cli.Command{
17+
DefaultCommand: "test",
18+
Commands: []*cli.Command{
19+
{
20+
Name: "test",
21+
Action: func(ctx context.Context, command *cli.Command) error {
22+
retName, retValid := isValidDefaultSubCommand(command)
23+
assert.Equal(t, expectedRetName, retName)
24+
assert.Equal(t, expectedRetValid, retValid)
25+
called = true
26+
return nil
27+
},
28+
},
29+
},
30+
}
31+
assert.NoError(t, cmd.Run(t.Context(), args))
32+
assert.True(t, called)
33+
}
34+
test(t, []string{"app"}, "", true)
35+
test(t, []string{"app", "test"}, "", true)
36+
test(t, []string{"app", "other"}, "other", false)
37+
}

cmd/main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ func NewMainApp(appVer AppVersion) *cli.Command {
152152
CmdDocs,
153153
}
154154

155+
// TODO: we should eventually drop the default command,
156+
// but not sure whether it would break Windows users who used to double-click the EXE to run.
155157
app.DefaultCommand = CmdWeb.Name
156158

157159
app.Flags = append(app.Flags, cli.VersionFlag)

cmd/web.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,10 @@ func runWeb(_ context.Context, cmd *cli.Command) error {
251251
}
252252
}()
253253

254+
if subCmdName, valid := isValidDefaultSubCommand(cmd); !valid {
255+
return fmt.Errorf("unknown command: %s", subCmdName)
256+
}
257+
254258
managerCtx, cancel := context.WithCancel(context.Background())
255259
graceful.InitManager(managerCtx)
256260
defer cancel()

0 commit comments

Comments
 (0)