mirror of
https://github.com/thomiceli/opengist.git
synced 2024-12-22 20:42:40 +00:00
Improve Git config
This commit is contained in:
parent
5994cd6ccd
commit
8f482bce33
1 changed files with 46 additions and 6 deletions
|
@ -1,15 +1,24 @@
|
|||
package git
|
||||
|
||||
import "os/exec"
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type configEntry struct {
|
||||
value string
|
||||
fn func(string, string) error
|
||||
}
|
||||
|
||||
func InitGitConfig() error {
|
||||
configs := map[string]string{
|
||||
"receive.advertisePushOptions": "true",
|
||||
"safe.directory": "*",
|
||||
configs := map[string]configEntry{
|
||||
"receive.advertisePushOptions": {value: "true", fn: setGitConfig},
|
||||
"safe.directory": {value: "*", fn: addGitConfig},
|
||||
}
|
||||
|
||||
for key, value := range configs {
|
||||
if err := setGitConfig(key, value); err != nil {
|
||||
for key, entry := range configs {
|
||||
if err := entry.fn(key, entry.value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
@ -18,6 +27,37 @@ func InitGitConfig() error {
|
|||
}
|
||||
|
||||
func setGitConfig(key, value string) error {
|
||||
_, err := getGitConfig(key, value)
|
||||
if err != nil && !checkErrorCode(err, 1) {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd := exec.Command("git", "config", "--global", key, value)
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func addGitConfig(key, value string) error {
|
||||
_, err := getGitConfig(key, regexp.QuoteMeta(value))
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if checkErrorCode(err, 1) {
|
||||
cmd := exec.Command("git", "config", "--global", "--add", key, value)
|
||||
return cmd.Run()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func getGitConfig(key, value string) (string, error) {
|
||||
cmd := exec.Command("git", "config", "--global", "--get", key, value)
|
||||
out, err := cmd.Output()
|
||||
return string(out), err
|
||||
}
|
||||
|
||||
func checkErrorCode(err error, code int) bool {
|
||||
var exitError *exec.ExitError
|
||||
if errors.As(err, &exitError) {
|
||||
return exitError.ExitCode() == code
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue