1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 03:36:16 +00:00
mycorrhiza/history/history.go

84 lines
2.1 KiB
Go
Raw Normal View History

2021-05-11 10:14:00 +00:00
// Package history provides a git wrapper.
2020-08-08 20:10:28 +00:00
package history
import (
"bytes"
2020-08-08 20:10:28 +00:00
"fmt"
"log"
"os/exec"
"path/filepath"
"regexp"
2020-08-08 20:10:28 +00:00
2021-06-19 04:51:10 +00:00
"github.com/bouncepaw/mycorrhiza/files"
"github.com/bouncepaw/mycorrhiza/util"
2020-08-08 20:10:28 +00:00
)
2021-03-09 14:27:14 +00:00
// Path to git executable. Set at init()
var gitpath string
var renameMsgPattern = regexp.MustCompile(`^Rename (.*) to .*`)
2021-06-06 15:12:07 +00:00
var gitEnv = []string{"GIT_COMMITTER_NAME=wikimind", "GIT_COMMITTER_EMAIL=wikimind@mycorrhiza"}
2021-03-09 14:27:14 +00:00
// Start finds git and initializes git credentials.
2021-05-11 10:14:00 +00:00
func Start() {
2021-03-09 14:27:14 +00:00
path, err := exec.LookPath("git")
if err != nil {
2021-05-11 10:14:00 +00:00
log.Fatal("Could not find the git executable. Check your $PATH.")
2021-03-09 14:27:14 +00:00
}
gitpath = path
2020-08-08 20:10:28 +00:00
}
// InitGitRepo checks a Git repository and initializes it if necessary.
func InitGitRepo() {
// Detect if the Git repo directory is a Git repository
isGitRepo := true
buf, err := silentGitsh("rev-parse", "--git-dir")
if err != nil {
isGitRepo = false
}
if isGitRepo {
gitDir := buf.String()
if filepath.IsAbs(gitDir) && !filepath.HasPrefix(gitDir, files.HyphaeDir()) {
isGitRepo = false
}
}
if !isGitRepo {
log.Println("Initializing Git repo at", files.HyphaeDir())
gitsh("init")
gitsh("config", "core.quotePath", "false")
}
}
// I pronounce it as [gɪt͡ʃ].
2020-09-29 18:13:24 +00:00
// gitsh is async-safe, therefore all other git-related functions in this module are too.
func gitsh(args ...string) (out bytes.Buffer, err error) {
fmt.Printf("$ %v\n", args)
cmd := exec.Command(gitpath, args...)
2021-06-19 04:51:10 +00:00
cmd.Dir = files.HyphaeDir()
cmd.Env = append(cmd.Environ(), gitEnv...)
b, err := cmd.CombinedOutput()
if err != nil {
log.Println("gitsh:", err)
}
return *bytes.NewBuffer(b), err
}
2021-05-03 18:31:19 +00:00
// silentGitsh is like gitsh, except it writes less to the stdout.
func silentGitsh(args ...string) (out bytes.Buffer, err error) {
cmd := exec.Command(gitpath, args...)
2021-06-19 04:51:10 +00:00
cmd.Dir = files.HyphaeDir()
cmd.Env = append(cmd.Environ(), gitEnv...)
2021-05-03 18:31:19 +00:00
b, err := cmd.CombinedOutput()
return *bytes.NewBuffer(b), err
}
// Rename renames from `from` to `to` using `git mv`.
func Rename(from, to string) error {
log.Println(util.ShorterPath(from), util.ShorterPath(to))
_, err := gitsh("mv", "--force", from, to)
return err
2020-08-08 20:10:28 +00:00
}