git-age/cmd/init.go

112 lines
2.2 KiB
Go

package cmd
import (
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"github.com/bmatcuk/doublestar/v4"
"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 {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
dir, err := gitBaseDir()
if err != nil {
return err
}
for glob := range cfg {
files, err := doublestar.FilepathGlob(glob, doublestar.WithFilesOnly())
if err != nil {
return fmt.Errorf("bad glob %q: %w", glob, err)
}
for _, file := range files {
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
c := exec.Command(exe, args...)
c.Stdin = bytes.NewReader(content)
c.Stdout = &buf
if debug {
c.Stderr = os.Stderr
}
if err := c.Run(); err != nil {
if debug {
fmt.Fprintf(os.Stderr, "could not smudge file: %v\n", err)
}
return nil
}
if buf.String() == "" {
// Blank content, exit
return nil
}
fi, err := os.Create(apn)
if err != nil {
return err
}
fi.Write(buf.Bytes())
if err := fi.Close(); err != nil {
return err
}
cmd("git", "add", "--renormalize", apn)
return nil
}(); err != nil {
return err
}
}
}
return nil
}