Home

git-age @main - refs - log - search -
https://git.jolheiser.com/git-age.git
git-crypt, but with age
cmd/init.go - raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
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
}