fix(context): improve local repo detection logic and test (#999)

Fix https://gitea.com/gitea/tea/issues/995

Reviewed-on: https://gitea.com/gitea/tea/pulls/999
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Minjie Fang <wingsallen@gmail.com>
Co-committed-by: Minjie Fang <wingsallen@gmail.com>
This commit is contained in:
Minjie Fang
2026-05-25 22:12:19 +00:00
committed by Lunny Xiao
parent a664449282
commit 579099f9d9
2 changed files with 34 additions and 13 deletions
+13 -11
View File
@@ -103,21 +103,23 @@ func InitCommand(cmd *cli.Command) (*TeaContext, error) {
// try to read local git repo & extract context: if repoFlag specifies a valid path, read repo in that dir,
// otherwise attempt PWD. if no repo is found, continue with default login
if c.RepoSlug == "" {
if repoPath == "" {
if repoPath, err = os.Getwd(); err != nil {
return nil, err
}
if repoPath == "" {
if repoPath, err = os.Getwd(); err != nil {
return nil, err
}
}
if c.LocalRepo, c.Login, c.RepoSlug, err = contextFromLocalRepo(repoPath, remoteFlag, extraLogins); err != nil {
if err == errNotAGiteaRepo || err == git.ErrRepositoryNotExists {
// we can deal with that, commands needing the optional values use ctx.Ensure()
} else {
return nil, err
}
var localSlug string
if c.LocalRepo, c.Login, localSlug, err = contextFromLocalRepo(repoPath, remoteFlag, extraLogins); err != nil {
if err == errNotAGiteaRepo || err == git.ErrRepositoryNotExists {
// we can deal with that, commands needing the optional values use ctx.Ensure()
} else {
return nil, err
}
}
if c.RepoSlug == "" && localSlug != "" {
c.RepoSlug = localSlug
}
// If env vars are set, always use the env login (but repo slug was already
// resolved by contextFromLocalRepo with the env login in the match list)
+21 -2
View File
@@ -15,7 +15,7 @@ import (
teacontext "gitea.dev/tea/modules/context"
)
func TestInitCommand_WithRepoSlugSkipsLocalRepoDetection(t *testing.T) {
func TestInitCommand_WithRepoSlugKeepsLocalRepoDetection(t *testing.T) {
tmpDir := t.TempDir()
config.SetConfigForTesting(config.LocalConfig{
Logins: []config.Login{{
@@ -54,7 +54,26 @@ func TestInitCommand_WithRepoSlugSkipsLocalRepoDetection(t *testing.T) {
require.Equal(t, "owner", ctx.Owner)
require.Equal(t, "repo", ctx.Repo)
require.Equal(t, "owner/repo", ctx.RepoSlug)
require.Nil(t, ctx.LocalRepo)
require.NotNil(t, ctx.LocalRepo)
require.NotNil(t, ctx.Login)
require.Equal(t, "test-login", ctx.Login.Name)
cliCmd = cli.Command{
Name: "pr",
Flags: []cli.Flag{
&cli.StringFlag{Name: "repo"},
&cli.StringFlag{Name: "base"},
},
}
require.NoError(t, cliCmd.Set("repo", "owner/repo"))
require.NoError(t, cliCmd.Set("base", "main"))
ctx, err = teacontext.InitCommand(&cliCmd)
require.NoError(t, err)
require.Equal(t, "repo", ctx.Repo)
require.Equal(t, "owner/repo", ctx.RepoSlug)
require.Equal(t, "main", ctx.String("base"))
require.NotNil(t, ctx.LocalRepo)
require.NotNil(t, ctx.Login)
require.Equal(t, "test-login", ctx.Login.Name)
}