Refactor models.NewRepoContext to extract git related codes to modules/git (#6941)

* refactor models.NewRepoContext to extract git related codes to modules/git

* fix imports

* refactor
This commit is contained in:
Lunny Xiao 2019-05-15 09:57:00 +08:00 committed by GitHub
parent 95d3d42c5f
commit 710245e81e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 34 additions and 49 deletions

View File

@ -13,7 +13,6 @@ import (
"io/ioutil" "io/ioutil"
"net/url" "net/url"
"os" "os"
"os/exec"
"path" "path"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -32,11 +31,9 @@ import (
"code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/sync"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/Unknwon/cae/zip"
"github.com/Unknwon/com" "github.com/Unknwon/com"
"github.com/go-xorm/builder" "github.com/go-xorm/builder"
"github.com/go-xorm/xorm" "github.com/go-xorm/xorm"
version "github.com/mcuadros/go-version"
ini "gopkg.in/ini.v1" ini "gopkg.in/ini.v1"
) )
@ -67,8 +64,8 @@ var (
ItemsPerPage = 40 ItemsPerPage = 40
) )
// LoadRepoConfig loads the repository config // loadRepoConfig loads the repository config
func LoadRepoConfig() { func loadRepoConfig() {
// Load .gitignore and license files and readme templates. // Load .gitignore and license files and readme templates.
types := []string{"gitignore", "license", "readme", "label"} types := []string{"gitignore", "license", "readme", "label"}
typeFiles := make([][]string, 4) typeFiles := make([][]string, 4)
@ -119,45 +116,7 @@ func LoadRepoConfig() {
// NewRepoContext creates a new repository context // NewRepoContext creates a new repository context
func NewRepoContext() { func NewRepoContext() {
zip.Verbose = false loadRepoConfig()
// Check Git installation.
if _, err := exec.LookPath("git"); err != nil {
log.Fatal("Failed to test 'git' command: %v (forgotten install?)", err)
}
// Check Git version.
var err error
setting.Git.Version, err = git.BinVersion()
if err != nil {
log.Fatal("Failed to get Git version: %v", err)
}
log.Info("Git Version: %s", setting.Git.Version)
if version.Compare("1.7.1", setting.Git.Version, ">") {
log.Fatal("Gitea requires Git version greater or equal to 1.7.1")
}
// Git requires setting user.name and user.email in order to commit changes.
for configKey, defaultValue := range map[string]string{"user.name": "Gitea", "user.email": "gitea@fake.local"} {
if stdout, stderr, err := process.GetManager().Exec("NewRepoContext(get setting)", "git", "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
// ExitError indicates this config is not set
if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
if _, stderr, gerr := process.GetManager().Exec("NewRepoContext(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
log.Fatal("Failed to set git %s(%s): %s", configKey, gerr, stderr)
}
log.Info("Git config %s set to %s", configKey, defaultValue)
} else {
log.Fatal("Failed to get git %s(%s): %s", configKey, err, stderr)
}
}
}
// Set git some configurations.
if _, stderr, err := process.GetManager().Exec("NewRepoContext(git config --global core.quotepath false)",
"git", "config", "--global", "core.quotepath", "false"); err != nil {
log.Fatal("Failed to execute 'git config --global core.quotepath false': %s", stderr)
}
RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp")) RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
} }

View File

@ -11,6 +11,8 @@ import (
"strings" "strings"
"time" "time"
"code.gitea.io/gitea/modules/process"
"github.com/mcuadros/go-version" "github.com/mcuadros/go-version"
) )
@ -31,6 +33,8 @@ var (
// GitExecutable is the command name of git // GitExecutable is the command name of git
// Could be updated to an absolute path while initialization // Could be updated to an absolute path while initialization
GitExecutable = "git" GitExecutable = "git"
gitVersion string
) )
func log(format string, args ...interface{}) { func log(format string, args ...interface{}) {
@ -46,8 +50,6 @@ func log(format string, args ...interface{}) {
} }
} }
var gitVersion string
// BinVersion returns current Git version from shell. // BinVersion returns current Git version from shell.
func BinVersion() (string, error) { func BinVersion() (string, error) {
if len(gitVersion) > 0 { if len(gitVersion) > 0 {
@ -89,6 +91,26 @@ func init() {
if version.Compare(gitVersion, GitVersionRequired, "<") { if version.Compare(gitVersion, GitVersionRequired, "<") {
panic(fmt.Sprintf("Git version not supported. Requires version > %v", GitVersionRequired)) panic(fmt.Sprintf("Git version not supported. Requires version > %v", GitVersionRequired))
} }
// Git requires setting user.name and user.email in order to commit changes.
for configKey, defaultValue := range map[string]string{"user.name": "Gitea", "user.email": "gitea@fake.local"} {
if stdout, stderr, err := process.GetManager().Exec("git.Init(get setting)", GitExecutable, "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
// ExitError indicates this config is not set
if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
if _, stderr, gerr := process.GetManager().Exec("git.Init(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
panic(fmt.Sprintf("Failed to set git %s(%s): %s", configKey, gerr, stderr))
}
} else {
panic(fmt.Sprintf("Failed to get git %s(%s): %s", configKey, err, stderr))
}
}
}
// Set git some configurations.
if _, stderr, err := process.GetManager().Exec("git.Init(git config --global core.quotepath false)",
GitExecutable, "config", "--global", "core.quotepath", "false"); err != nil {
panic(fmt.Sprintf("Failed to execute 'git config --global core.quotepath false': %s", stderr))
}
} }
// Fsck verifies the connectivity and validity of the objects in the database // Fsck verifies the connectivity and validity of the objects in the database

View File

@ -16,7 +16,6 @@ import (
var ( var (
// Git settings // Git settings
Git = struct { Git = struct {
Version string `ini:"-"`
DisableDiffHighlight bool DisableDiffHighlight bool
MaxGitDiffLines int MaxGitDiffLines int
MaxGitDiffLineCharacters int MaxGitDiffLineCharacters int
@ -65,6 +64,8 @@ func newGit() {
log.Fatal("Error retrieving git version: %v", err) log.Fatal("Error retrieving git version: %v", err)
} }
log.Info("Git Version: %s", binVersion)
if version.Compare(binVersion, "2.9", ">=") { if version.Compare(binVersion, "2.9", ">=") {
// Explicitly disable credential helper, otherwise Git credentials might leak // Explicitly disable credential helper, otherwise Git credentials might leak
git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "credential.helper=") git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "credential.helper=")

View File

@ -27,6 +27,7 @@ import (
_ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services _ "code.gitea.io/gitea/modules/minwinsvc" // import minwinsvc for windows services
"code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/user"
"github.com/Unknwon/cae/zip"
"github.com/Unknwon/com" "github.com/Unknwon/com"
_ "github.com/go-macaron/cache/memcache" // memcache plugin for cache _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
_ "github.com/go-macaron/cache/redis" _ "github.com/go-macaron/cache/redis"
@ -931,6 +932,8 @@ func NewContext() {
sec = Cfg.Section("U2F") sec = Cfg.Section("U2F")
U2F.TrustedFacets, _ = shellquote.Split(sec.Key("TRUSTED_FACETS").MustString(strings.TrimRight(AppURL, "/"))) U2F.TrustedFacets, _ = shellquote.Split(sec.Key("TRUSTED_FACETS").MustString(strings.TrimRight(AppURL, "/")))
U2F.AppID = sec.Key("APP_ID").MustString(strings.TrimRight(AppURL, "/")) U2F.AppID = sec.Key("APP_ID").MustString(strings.TrimRight(AppURL, "/"))
zip.Verbose = false
} }
func loadInternalToken(sec *ini.Section) string { func loadInternalToken(sec *ini.Section) string {

View File

@ -18,6 +18,7 @@ import (
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/cron" "code.gitea.io/gitea/modules/cron"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/process"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
) )
@ -210,7 +211,7 @@ func Config(ctx *context.Context) {
ctx.Data["DisableRouterLog"] = setting.DisableRouterLog ctx.Data["DisableRouterLog"] = setting.DisableRouterLog
ctx.Data["RunUser"] = setting.RunUser ctx.Data["RunUser"] = setting.RunUser
ctx.Data["RunMode"] = strings.Title(macaron.Env) ctx.Data["RunMode"] = strings.Title(macaron.Env)
ctx.Data["GitVersion"] = setting.Git.Version ctx.Data["GitVersion"], _ = git.BinVersion()
ctx.Data["RepoRootPath"] = setting.RepoRootPath ctx.Data["RepoRootPath"] = setting.RepoRootPath
ctx.Data["CustomRootPath"] = setting.CustomPath ctx.Data["CustomRootPath"] = setting.CustomPath
ctx.Data["StaticRootPath"] = setting.StaticRootPath ctx.Data["StaticRootPath"] = setting.StaticRootPath

View File

@ -86,7 +86,6 @@ func GlobalInit() {
log.Fatal("Failed to initialize OAuth2 support: %v", err) log.Fatal("Failed to initialize OAuth2 support: %v", err)
} }
models.LoadRepoConfig()
models.NewRepoContext() models.NewRepoContext()
// Booting long running goroutines. // Booting long running goroutines.