Skip to content

Commit 45a9375

Browse files
committed
introduce git.InitSimple and git.InitWithConfigSync, make serv cmd use gitconfig
1 parent dac2594 commit 45a9375

File tree

11 files changed

+59
-41
lines changed

11 files changed

+59
-41
lines changed

cmd/serv.go

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package cmd
77

88
import (
9+
"context"
910
"fmt"
1011
"net/http"
1112
"net/url"
@@ -64,6 +65,19 @@ func setup(logPath string, debug bool) {
6465
if debug {
6566
setting.RunMode = "dev"
6667
}
68+
69+
// Check if setting.RepoRootPath exists. It could be the case that it doesn't exist, this can happen when
70+
// `[repository]` `ROOT` is a relative path and $GITEA_WORK_DIR isn't passed to the SSH connection.
71+
if _, err := os.Stat(setting.RepoRootPath); err != nil {
72+
if os.IsNotExist(err) {
73+
_ = fail("Incorrect configuration.", "Directory `[repository].ROOT` was not found, please check if $GITEA_WORK_DIR is passed to the SSH connection or make `[repository].ROOT` an absolute value.")
74+
return
75+
}
76+
}
77+
78+
if err := git.InitSimple(context.Background()); err != nil {
79+
_ = fail("Failed to init git", "Failed to init git")
80+
}
6781
}
6882

6983
var (
@@ -79,8 +93,8 @@ var (
7993
func fail(userMessage, logMessage string, args ...interface{}) error {
8094
// There appears to be a chance to cause a zombie process and failure to read the Exit status
8195
// if nothing is outputted on stdout.
82-
fmt.Fprintln(os.Stdout, "")
83-
fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
96+
_, _ = fmt.Fprintln(os.Stdout, "")
97+
_, _ = fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
8498

8599
if len(logMessage) > 0 {
86100
if !setting.IsProd {
@@ -297,19 +311,11 @@ func runServ(c *cli.Context) error {
297311
gitcmd = exec.CommandContext(ctx, verb, repoPath)
298312
}
299313

300-
// Check if setting.RepoRootPath exists. It could be the case that it doesn't exist, this can happen when
301-
// `[repository]` `ROOT` is a relative path and $GITEA_WORK_DIR isn't passed to the SSH connection.
302-
if _, err := os.Stat(setting.RepoRootPath); err != nil {
303-
if os.IsNotExist(err) {
304-
return fail("Incorrect configuration.",
305-
"Directory `[repository]` `ROOT` was not found, please check if $GITEA_WORK_DIR is passed to the SSH connection or make `[repository]` `ROOT` an absolute value.")
306-
}
307-
}
308-
309314
gitcmd.Dir = setting.RepoRootPath
310315
gitcmd.Stdout = os.Stdout
311316
gitcmd.Stdin = os.Stdin
312317
gitcmd.Stderr = os.Stderr
318+
gitcmd.Env = append(gitcmd.Env, git.CommonEnvs()...)
313319
if err = gitcmd.Run(); err != nil {
314320
return fail("Internal error", "Failed to execute git command: %v", err)
315321
}

integrations/integration_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ func prepareTestEnv(t testing.TB, skip ...int) func() {
262262
assert.NoError(t, unittest.LoadFixtures())
263263
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
264264
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
265-
assert.NoError(t, git.Init(context.Background()))
265+
assert.NoError(t, git.InitWithConfigSync(context.Background()))
266266
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
267267
if err != nil {
268268
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
@@ -563,7 +563,7 @@ func resetFixtures(t *testing.T) {
563563
assert.NoError(t, unittest.LoadFixtures())
564564
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
565565
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
566-
assert.NoError(t, git.Init(context.Background()))
566+
assert.NoError(t, git.InitWithConfigSync(context.Background()))
567567
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
568568
if err != nil {
569569
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)

integrations/migration-test/migration_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ func initMigrationTest(t *testing.T) func() {
6262
assert.True(t, len(setting.RepoRootPath) != 0)
6363
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
6464
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
65-
assert.NoError(t, git.Init(context.Background()))
65+
assert.NoError(t, git.InitWithConfigSync(context.Background()))
6666
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
6767
if err != nil {
6868
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)

models/migrations/migrations_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En
203203
deferFn := PrintCurrentTest(t, ourSkip)
204204
assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
205205
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
206-
assert.NoError(t, git.Init(context.Background()))
206+
assert.NoError(t, git.InitWithConfigSync(context.Background()))
207207
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
208208
if err != nil {
209209
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)

models/unittest/testdb.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func MainTest(m *testing.M, testOpts *TestOptions) {
107107

108108
setting.Packages.Storage.Path = filepath.Join(setting.AppDataPath, "packages")
109109

110-
if err = git.Init(context.Background()); err != nil {
110+
if err = git.InitWithConfigSync(context.Background()); err != nil {
111111
fatalTestError("git.Init: %v\n", err)
112112
}
113113

@@ -203,7 +203,7 @@ func PrepareTestEnv(t testing.TB) {
203203
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
204204
metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta")
205205
assert.NoError(t, CopyDir(metaPath, setting.RepoRootPath))
206-
assert.NoError(t, git.Init(context.Background()))
206+
assert.NoError(t, git.InitWithConfigSync(context.Background()))
207207

208208
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
209209
assert.NoError(t, err)

modules/git/command.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,16 @@ type RunOpts struct {
106106
PipelineFunc func(context.Context, context.CancelFunc) error
107107
}
108108

109+
func CommonEnvs() []string {
110+
return []string{
111+
fmt.Sprintf("LC_ALL=%s", DefaultLocale),
112+
"GIT_TERMINAL_PROMPT=0", // avoid prompting for credentials interactively, supported since git v2.3
113+
"GIT_NO_REPLACE_OBJECTS=1", // ignore replace references (https://git-scm.com/docs/git-replace)
114+
"GIT_CONFIG_NOSYSTEM=1", // https://git-scm.com/docs/git-config
115+
"GIT_CONFIG_GLOBAL=" + GlobalConfigFile, // make Gitea use internal git config only, to prevent conflicts with user's git config
116+
}
117+
}
118+
109119
// Run runs the command with the RunOpts
110120
func (c *Command) Run(opts *RunOpts) error {
111121
if opts == nil {
@@ -158,15 +168,7 @@ func (c *Command) Run(opts *RunOpts) error {
158168
log.Warn("GlobalConfigFile is empty, the git module is not initialized correctly, using a temp gitconfig (%s) temporarily", GlobalConfigFile)
159169
}
160170

161-
cmd.Env = append(
162-
cmd.Env,
163-
fmt.Sprintf("LC_ALL=%s", DefaultLocale),
164-
"GIT_TERMINAL_PROMPT=0", // avoid prompting for credentials interactively, supported since git v2.3
165-
"GIT_NO_REPLACE_OBJECTS=1", // ignore replace references (https://git-scm.com/docs/git-replace)
166-
"GIT_CONFIG_NOSYSTEM=1", // https://git-scm.com/docs/git-config
167-
"GIT_CONFIG_GLOBAL="+GlobalConfigFile, // make Gitea use internal git config only, to prevent conflicts with user's git config
168-
)
169-
171+
cmd.Env = append(cmd.Env, CommonEnvs()...)
170172
cmd.Dir = opts.Dir
171173
cmd.Stdout = opts.Stdout
172174
cmd.Stderr = opts.Stderr

modules/git/git.go

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ var (
3535
GlobalConfigFile string
3636

3737
// DefaultContext is the default context to run git commands in
38-
// will be overwritten by Init with HammerContext
38+
// will be overwritten by InitWithConfigSync with HammerContext
3939
DefaultContext = context.Background()
4040

4141
// SupportProcReceive version >= 2.29.0
@@ -129,8 +129,9 @@ func VersionInfo() string {
129129
return fmt.Sprintf(format, args...)
130130
}
131131

132-
// Init initializes git module
133-
func Init(ctx context.Context) error {
132+
// InitSimple initializes git module with a very simple step, no config changes, no global command arguments.
133+
// This method doesn't change anything to filesystem
134+
func InitSimple(ctx context.Context) error {
134135
DefaultContext = ctx
135136

136137
if setting.Git.Timeout.Default > 0 {
@@ -141,9 +142,6 @@ func Init(ctx context.Context) error {
141142
return errors.New("RepoRootPath is empty, git module needs that setting before initialization")
142143
}
143144

144-
if err := os.MkdirAll(setting.RepoRootPath, os.ModePerm); err != nil {
145-
return fmt.Errorf("unable to create directory %s, err:%w", setting.RepoRootPath, err)
146-
}
147145
GlobalConfigFile = setting.RepoRootPath + "/gitconfig"
148146

149147
if err := SetExecutablePath(setting.Git.Path); err != nil {
@@ -153,6 +151,20 @@ func Init(ctx context.Context) error {
153151
// force cleanup args
154152
globalCommandArgs = []string{}
155153

154+
return nil
155+
}
156+
157+
// InitWithConfigSync initializes git module. This method may create directories or write files into filesystem
158+
func InitWithConfigSync(ctx context.Context) error {
159+
err := InitSimple(ctx)
160+
if err != nil {
161+
return err
162+
}
163+
164+
if err = os.MkdirAll(setting.RepoRootPath, os.ModePerm); err != nil {
165+
return fmt.Errorf("unable to create directory %s, err:%w", setting.RepoRootPath, err)
166+
}
167+
156168
if CheckGitVersionAtLeast("2.9") == nil {
157169
// Explicitly disable credential helper, otherwise Git credentials might leak
158170
globalCommandArgs = append(globalCommandArgs, "-c", "credential.helper=")
@@ -223,13 +235,11 @@ func Init(ctx context.Context) error {
223235
if err := configSet("core.longpaths", "true"); err != nil {
224236
return err
225237
}
226-
}
227-
if setting.Git.DisableCoreProtectNTFS {
228-
if err := configSet("core.protectntfs", "false"); err != nil {
229-
return err
238+
if setting.Git.DisableCoreProtectNTFS {
239+
globalCommandArgs = append(globalCommandArgs, "-c", "core.protectntfs=false")
230240
}
231-
globalCommandArgs = append(globalCommandArgs, "-c", "core.protectntfs=false")
232241
}
242+
233243
return nil
234244
}
235245

modules/git/git_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func testRun(m *testing.M) error {
2828
defer util.RemoveAll(repoRootPath)
2929
setting.RepoRootPath = repoRootPath
3030

31-
if err = Init(context.Background()); err != nil {
31+
if err = InitWithConfigSync(context.Background()); err != nil {
3232
return fmt.Errorf("failed to call Init: %w", err)
3333
}
3434

modules/git/repo_attribute.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ type CheckAttributeReader struct {
121121
cancel context.CancelFunc
122122
}
123123

124-
// Init initializes the cmd
124+
// InitWithConfigSync initializes the cmd
125125
func (c *CheckAttributeReader) Init(ctx context.Context) error {
126126
cmdArgs := []string{"check-attr", "--stdin", "-z"}
127127

modules/indexer/stats/indexer_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func TestMain(m *testing.M) {
2929
}
3030

3131
func TestRepoStatsIndex(t *testing.T) {
32-
if err := git.Init(context.Background()); !assert.NoError(t, err) {
32+
if err := git.InitWithConfigSync(context.Background()); !assert.NoError(t, err) {
3333
return
3434
}
3535

routers/init.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ func GlobalInitInstalled(ctx context.Context) {
102102
log.Fatal("Gitea is not installed")
103103
}
104104

105-
mustInitCtx(ctx, git.Init)
105+
mustInitCtx(ctx, git.InitWithConfigSync)
106106
log.Info("Git Version: %s (config: %s)", git.VersionInfo(), git.GlobalConfigFile)
107107

108108
git.CheckLFSVersion()

0 commit comments

Comments
 (0)