git-age/cmd/init.go

92 lines
1.8 KiB
Go

package cmd
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/urfave/cli/v2"
)
var Init = &cli.Command{
Name: "init",
Aliases: []string{"i"},
Description: "Initialize git-age",
Action: actionInit,
}
func actionInit(ctx *cli.Context) error {
exe, err := os.Executable()
if err != nil {
return fmt.Errorf("could not get path to executable: %w", err)
}
var debugFlag string
if debug {
debugFlag = " -d"
}
if _, err := cmd("git", "config", "filter.git-age.required", "true"); err != nil {
return err
}
if _, err := cmd("git", "config", "filter.git-age.smudge", exe+debugFlag+" smudge -f %f"); err != nil {
return err
}
if _, err := cmd("git", "config", "filter.git-age.clean", exe+debugFlag+" clean -f %f"); err != nil {
return err
}
if _, err := cmd("git", "config", "diff.git-age.textconv", exe+debugFlag+" textconv"); err != nil {
return err
}
cfg, err := LoadConfig()
if err != nil {
return err
}
dir, err := gitBaseDir()
if err != nil {
return err
}
for file := range cfg {
apn := filepath.Join(dir, file)
args := []string{"smudge", "-f", file}
if debug {
args = append([]string{"-d"}, args...)
}
if err := func() error {
content, err := os.ReadFile(apn)
if err != nil {
return err
}
var buf bytes.Buffer
cmd := exec.Command(exe, args...)
cmd.Stdin = bytes.NewReader(content)
cmd.Stdout = &buf
if debug {
cmd.Stderr = os.Stderr
}
if err := cmd.Run(); err != nil {
if debug {
fmt.Fprintf(os.Stderr, "could not smudge file: %v\n", err)
}
return nil
}
fi, err := os.Create(apn)
if err != nil {
return err
}
defer fi.Close()
fi.Write(buf.Bytes())
return nil
}(); err != nil {
return err
}
}
return nil
}