loading up the forgejo repo on tangled to test page performance
at forgejo 16 kB view raw
1// Copyright 2015 The Gogs Authors. All rights reserved. 2// Copyright 2017 The Gitea Authors. All rights reserved. 3// SPDX-License-Identifier: MIT 4 5package git 6 7import ( 8 "context" 9 "errors" 10 "fmt" 11 "os" 12 "os/exec" 13 "path/filepath" 14 "regexp" 15 "runtime" 16 "strings" 17 "time" 18 19 "forgejo.org/modules/log" 20 "forgejo.org/modules/setting" 21 22 "github.com/hashicorp/go-version" 23) 24 25// RequiredVersion is the minimum Git version required 26const RequiredVersion = "2.0.0" 27 28var ( 29 // GitExecutable is the command name of git 30 // Could be updated to an absolute path while initialization 31 GitExecutable = "git" 32 33 // DefaultContext is the default context to run git commands in, must be initialized by git.InitXxx 34 DefaultContext context.Context 35 36 SupportProcReceive bool // >= 2.29 37 SupportHashSha256 bool // >= 2.42, SHA-256 repositories no longer an ‘experimental curiosity’ 38 InvertedGitFlushEnv bool // 2.43.1 39 SupportCheckAttrOnBare bool // >= 2.40 40 41 HasSSHExecutable bool 42 43 gitVersion *version.Version 44) 45 46// loadGitVersion returns current Git version from shell. Internal usage only. 47func loadGitVersion() error { 48 // doesn't need RWMutex because it's executed by Init() 49 if gitVersion != nil { 50 return nil 51 } 52 stdout, _, runErr := NewCommand(DefaultContext, "version").RunStdString(nil) 53 if runErr != nil { 54 return runErr 55 } 56 57 fields := strings.Fields(stdout) 58 if len(fields) < 3 { 59 return fmt.Errorf("invalid git version output: %s", stdout) 60 } 61 62 versionString := fields[2] 63 64 var err error 65 gitVersion, err = version.NewVersion(versionString) 66 return err 67} 68 69// SetExecutablePath changes the path of git executable and checks the file permission and version. 70func SetExecutablePath(path string) error { 71 // If path is empty, we use the default value of GitExecutable "git" to search for the location of git. 72 if path != "" { 73 GitExecutable = path 74 } 75 absPath, err := exec.LookPath(GitExecutable) 76 if err != nil { 77 return fmt.Errorf("git not found: %w", err) 78 } 79 GitExecutable = absPath 80 81 err = loadGitVersion() 82 if err != nil { 83 return fmt.Errorf("unable to load git version: %w", err) 84 } 85 86 versionRequired, err := version.NewVersion(RequiredVersion) 87 if err != nil { 88 return err 89 } 90 91 if gitVersion.LessThan(versionRequired) { 92 moreHint := "get git: https://git-scm.com/downloads" 93 if runtime.GOOS == "linux" { 94 // there are a lot of CentOS/RHEL users using old git, so we add a special hint for them 95 if _, err = os.Stat("/etc/redhat-release"); err == nil { 96 // ius.io is the recommended official(git-scm.com) method to install git 97 moreHint = "get git: https://git-scm.com/downloads/linux and https://ius.io" 98 } 99 } 100 return fmt.Errorf("installed git version %q is not supported, Gitea requires git version >= %q, %s", gitVersion.Original(), RequiredVersion, moreHint) 101 } 102 103 return nil 104} 105 106// VersionInfo returns git version information 107func VersionInfo() string { 108 if gitVersion == nil { 109 return "(git not found)" 110 } 111 format := "%s" 112 args := []any{gitVersion.Original()} 113 // Since git wire protocol has been released from git v2.18 114 if setting.Git.EnableAutoGitWireProtocol && CheckGitVersionAtLeast("2.18") == nil { 115 format += ", Wire Protocol %s Enabled" 116 args = append(args, "Version 2") // for focus color 117 } 118 119 return fmt.Sprintf(format, args...) 120} 121 122func checkInit() error { 123 if setting.Git.HomePath == "" { 124 return errors.New("unable to init Git's HomeDir, incorrect initialization of the setting and git modules") 125 } 126 if DefaultContext != nil { 127 log.Warn("git module has been initialized already, duplicate init may work but it's better to fix it") 128 } 129 return nil 130} 131 132// HomeDir is the home dir for git to store the global config file used by Gitea internally 133func HomeDir() string { 134 if setting.Git.HomePath == "" { 135 // strict check, make sure the git module is initialized correctly. 136 // attention: when the git module is called in gitea sub-command (serv/hook), the log module might not obviously show messages to users/developers. 137 // for example: if there is gitea git hook code calling git.NewCommand before git.InitXxx, the integration test won't show the real failure reasons. 138 log.Fatal("Unable to init Git's HomeDir, incorrect initialization of the setting and git modules") 139 return "" 140 } 141 return setting.Git.HomePath 142} 143 144// InitSimple initializes git module with a very simple step, no config changes, no global command arguments. 145// This method doesn't change anything to filesystem. At the moment, it is only used by some Gitea sub-commands. 146func InitSimple(ctx context.Context) error { 147 if err := checkInit(); err != nil { 148 return err 149 } 150 151 DefaultContext = ctx 152 globalCommandArgs = nil 153 154 if setting.Git.Timeout.Default > 0 { 155 defaultCommandExecutionTimeout = time.Duration(setting.Git.Timeout.Default) * time.Second 156 } 157 158 return SetExecutablePath(setting.Git.Path) 159} 160 161// InitFull initializes git module with version check and change global variables, sync gitconfig. 162// It should only be called once at the beginning of the program initialization (TestMain/GlobalInitInstalled) as this code makes unsynchronized changes to variables. 163func InitFull(ctx context.Context) (err error) { 164 if err = InitSimple(ctx); err != nil { 165 return err 166 } 167 168 // when git works with gnupg (commit signing), there should be a stable home for gnupg commands 169 if _, ok := os.LookupEnv("GNUPGHOME"); !ok { 170 _ = os.Setenv("GNUPGHOME", filepath.Join(HomeDir(), ".gnupg")) 171 } 172 173 // Since git wire protocol has been released from git v2.18 174 if setting.Git.EnableAutoGitWireProtocol && CheckGitVersionAtLeast("2.18") == nil { 175 globalCommandArgs = append(globalCommandArgs, "-c", "protocol.version=2") 176 } 177 178 // Explicitly disable credential helper, otherwise Git credentials might leak 179 if CheckGitVersionAtLeast("2.9") == nil { 180 globalCommandArgs = append(globalCommandArgs, "-c", "credential.helper=") 181 } 182 SupportProcReceive = CheckGitVersionAtLeast("2.29") == nil 183 SupportHashSha256 = CheckGitVersionAtLeast("2.42") == nil 184 SupportCheckAttrOnBare = CheckGitVersionAtLeast("2.40") == nil 185 if SupportHashSha256 { 186 SupportedObjectFormats = append(SupportedObjectFormats, Sha256ObjectFormat) 187 } else { 188 log.Warn("sha256 hash support is disabled - requires Git >= 2.42") 189 } 190 191 InvertedGitFlushEnv = CheckGitVersionEqual("2.43.1") == nil 192 193 if setting.LFS.StartServer { 194 if CheckGitVersionAtLeast("2.1.2") != nil { 195 return errors.New("LFS server support requires Git >= 2.1.2") 196 } 197 globalCommandArgs = append(globalCommandArgs, "-c", "filter.lfs.required=", "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=") 198 } 199 200 // Detect the presence of the ssh executable in $PATH. 201 _, err = exec.LookPath("ssh") 202 HasSSHExecutable = err == nil 203 204 return syncGitConfig() 205} 206 207// syncGitConfig only modifies gitconfig, won't change global variables (otherwise there will be data-race problem) 208func syncGitConfig() (err error) { 209 if err = os.MkdirAll(HomeDir(), os.ModePerm); err != nil { 210 return fmt.Errorf("unable to prepare git home directory %s, err: %w", HomeDir(), err) 211 } 212 213 // first, write user's git config options to git config file 214 // user config options could be overwritten by builtin values later, because if a value is builtin, it must have some special purposes 215 for k, v := range setting.GitConfig.Options { 216 if err = configSet(strings.ToLower(k), v); err != nil { 217 return err 218 } 219 } 220 221 // Git requires setting user.name and user.email in order to commit changes - old comment: "if they're not set just add some defaults" 222 // TODO: need to confirm whether users really need to change these values manually. It seems that these values are dummy only and not really used. 223 // If these values are not really used, then they can be set (overwritten) directly without considering about existence. 224 for configKey, defaultValue := range map[string]string{ 225 "user.name": "Gitea", 226 "user.email": "gitea@fake.local", 227 } { 228 if err := configSetNonExist(configKey, defaultValue); err != nil { 229 return err 230 } 231 } 232 233 // Set git some configurations - these must be set to these values for gitea to work correctly 234 if err := configSet("core.quotePath", "false"); err != nil { 235 return err 236 } 237 238 if CheckGitVersionAtLeast("2.10") == nil { 239 if err := configSet("receive.advertisePushOptions", "true"); err != nil { 240 return err 241 } 242 } 243 244 if CheckGitVersionAtLeast("2.18") == nil { 245 if err := configSet("core.commitGraph", "true"); err != nil { 246 return err 247 } 248 if err := configSet("gc.writeCommitGraph", "true"); err != nil { 249 return err 250 } 251 if err := configSet("fetch.writeCommitGraph", "true"); err != nil { 252 return err 253 } 254 } 255 256 if SupportProcReceive { 257 // set support for AGit flow 258 if err := configAddNonExist("receive.procReceiveRefs", "refs/for"); err != nil { 259 return err 260 } 261 } else { 262 if err := configUnsetAll("receive.procReceiveRefs", "refs/for"); err != nil { 263 return err 264 } 265 } 266 267 // Due to CVE-2022-24765, git now denies access to git directories which are not owned by current user 268 // however, some docker users and samba users find it difficult to configure their systems so that Gitea's git repositories are owned by the Gitea user. (Possibly Windows Service users - but ownership in this case should really be set correctly on the filesystem.) 269 // see issue: https://github.com/go-gitea/gitea/issues/19455 270 // Fundamentally the problem lies with the uid-gid-mapping mechanism for filesystems in docker on windows (and to a lesser extent samba). 271 // Docker's configuration mechanism for local filesystems provides no way of setting this mapping and although there is a mechanism for setting this uid through using cifs mounting it is complicated and essentially undocumented 272 // Thus the owner uid/gid for files on these filesystems will be marked as root. 273 // As Gitea now always use its internal git config file, and access to the git repositories is managed through Gitea, 274 // it is now safe to set "safe.directory=*" for internal usage only. 275 // Please note: the wildcard "*" is only supported by Git 2.30.4/2.31.3/2.32.2/2.33.3/2.34.3/2.35.3/2.36 and later, 276 // but is tolerated by earlier versions 277 if err := configAddNonExist("safe.directory", "*"); err != nil { 278 return err 279 } 280 281 switch setting.Repository.Signing.Format { 282 case "ssh": 283 // First do a git version check. 284 if CheckGitVersionAtLeast("2.34.0") != nil { 285 return errors.New("ssh signing requires Git >= 2.34.0") 286 } 287 288 // Get the ssh-keygen binary that Git will use. 289 // This can be overriden in app.ini in [git.config] section, so we must 290 // query this information. 291 sshKeygenPath, err := configGet("gpg.ssh.program") 292 if err != nil { 293 return err 294 } 295 // git is very stubborn and does not give a default value, so we must do 296 // this ourselves. 297 if len(sshKeygenPath) == 0 { 298 // Default value of git, very unlikely to change. 299 // https://github.com/git/git/blob/5b97a56fa0e7d580dc8865b73107407c9b3f0eff/gpg-interface.c#L116 300 sshKeygenPath = "ssh-keygen" 301 } 302 303 // Although there's a version requirement of 8.2p1, there's no cross-version 304 // method to get the version of ssh-keygen. Therefore we do a simple binary 305 // presence check and hope for the best. 306 if _, err := exec.LookPath(sshKeygenPath); err != nil { 307 if errors.Is(err, exec.ErrNotFound) { 308 return errors.New("git signing requires a ssh-keygen binary") 309 } 310 return err 311 } 312 313 if err := configSet("gpg.format", "ssh"); err != nil { 314 return err 315 } 316 // openpgp is already the default value, so in the case of a non SSH format 317 // set the value to openpgp. 318 default: 319 if err := configSet("gpg.format", "openpgp"); err != nil { 320 return err 321 } 322 } 323 324 // By default partial clones are disabled, enable them from git v2.22 325 if !setting.Git.DisablePartialClone && CheckGitVersionAtLeast("2.22") == nil { 326 if err = configSet("uploadpack.allowfilter", "true"); err != nil { 327 return err 328 } 329 err = configSet("uploadpack.allowAnySHA1InWant", "true") 330 } else { 331 if err = configUnsetAll("uploadpack.allowfilter", "true"); err != nil { 332 return err 333 } 334 err = configUnsetAll("uploadpack.allowAnySHA1InWant", "true") 335 } 336 337 return err 338} 339 340// CheckGitVersionAtLeast check git version is at least the constraint version 341func CheckGitVersionAtLeast(atLeast string) error { 342 if err := loadGitVersion(); err != nil { 343 return err 344 } 345 atLeastVersion, err := version.NewVersion(atLeast) 346 if err != nil { 347 return err 348 } 349 if gitVersion.Compare(atLeastVersion) < 0 { 350 return fmt.Errorf("installed git binary version %s is not at least %s", gitVersion.Original(), atLeast) 351 } 352 return nil 353} 354 355// CheckGitVersionEqual checks if the git version is equal to the constraint version. 356func CheckGitVersionEqual(equal string) error { 357 if err := loadGitVersion(); err != nil { 358 return err 359 } 360 atLeastVersion, err := version.NewVersion(equal) 361 if err != nil { 362 return err 363 } 364 if !gitVersion.Equal(atLeastVersion) { 365 return fmt.Errorf("installed git binary version %s is not equal to %s", gitVersion.Original(), equal) 366 } 367 return nil 368} 369 370func configGet(key string) (string, error) { 371 stdout, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key).RunStdString(nil) 372 if err != nil && !IsErrorExitCode(err, 1) { 373 return "", fmt.Errorf("failed to get git config %s, err: %w", key, err) 374 } 375 376 return strings.TrimSpace(stdout), nil 377} 378 379func configSet(key, value string) error { 380 stdout, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key).RunStdString(nil) 381 if err != nil && !IsErrorExitCode(err, 1) { 382 return fmt.Errorf("failed to get git config %s, err: %w", key, err) 383 } 384 385 currValue := strings.TrimSpace(stdout) 386 if currValue == value { 387 return nil 388 } 389 390 _, _, err = NewCommand(DefaultContext, "config", "--global").AddDynamicArguments(key, value).RunStdString(nil) 391 if err != nil { 392 return fmt.Errorf("failed to set git global config %s, err: %w", key, err) 393 } 394 395 return nil 396} 397 398func configSetNonExist(key, value string) error { 399 _, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key).RunStdString(nil) 400 if err == nil { 401 // already exist 402 return nil 403 } 404 if IsErrorExitCode(err, 1) { 405 // not exist, set new config 406 _, _, err = NewCommand(DefaultContext, "config", "--global").AddDynamicArguments(key, value).RunStdString(nil) 407 if err != nil { 408 return fmt.Errorf("failed to set git global config %s, err: %w", key, err) 409 } 410 return nil 411 } 412 413 return fmt.Errorf("failed to get git config %s, err: %w", key, err) 414} 415 416func configAddNonExist(key, value string) error { 417 _, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(nil) 418 if err == nil { 419 // already exist 420 return nil 421 } 422 if IsErrorExitCode(err, 1) { 423 // not exist, add new config 424 _, _, err = NewCommand(DefaultContext, "config", "--global", "--add").AddDynamicArguments(key, value).RunStdString(nil) 425 if err != nil { 426 return fmt.Errorf("failed to add git global config %s, err: %w", key, err) 427 } 428 return nil 429 } 430 return fmt.Errorf("failed to get git config %s, err: %w", key, err) 431} 432 433func configUnsetAll(key, value string) error { 434 _, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key).RunStdString(nil) 435 if err == nil { 436 // exist, need to remove 437 _, _, err = NewCommand(DefaultContext, "config", "--global", "--unset-all").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(nil) 438 if err != nil { 439 return fmt.Errorf("failed to unset git global config %s, err: %w", key, err) 440 } 441 return nil 442 } 443 if IsErrorExitCode(err, 1) { 444 // not exist 445 return nil 446 } 447 return fmt.Errorf("failed to get git config %s, err: %w", key, err) 448} 449 450// Fsck verifies the connectivity and validity of the objects in the database 451func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args TrustedCmdArgs) error { 452 return NewCommand(ctx, "fsck").AddArguments(args...).Run(&RunOpts{Timeout: timeout, Dir: repoPath}) 453}