Home

git-age @main - refs - log - search -
https://git.jolheiser.com/git-age.git
git-crypt, but with age
cmd/add.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
package cmd

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"slices"

	"github.com/AlecAivazis/survey/v2"
	"github.com/urfave/cli/v2"
)

var Add = &cli.Command{
	Name:        "add",
	Aliases:     []string{"a"},
	Description: "Add a new file for encryption",
	Flags: []cli.Flag{
		&cli.StringSliceFlag{
			Name:    "recipient",
			Aliases: []string{"r"},
		},
	},
	Action: actionAdd,
}

func actionAdd(ctx *cli.Context) error {
	if ctx.NArg() != 1 {
		return errors.New("add requires 1 argument")
	}
	file := ctx.Args().First()

	ok, err := hasAttr(file)
	if err != nil {
		return err
	}
	if !ok {
		base, err := gitBaseDir()
		if err != nil {
			return err
		}
		attrFile := filepath.Join(base, ".gitattributes")
		fi, err := os.OpenFile(attrFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModePerm)
		if err != nil {
			return err
		}
		defer fi.Close()
		fmt.Fprintf(fi, "\n%s filter=git-age diff=git-age", file)
	}

	cfg, err := LoadConfig()
	if err != nil {
		return err
	}

	ok, err = cfg.Includes(file)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	recipients := ctx.StringSlice("recipient")
	if len(recipients) == 0 {

		var recipientOpts []string
		for _, recs := range cfg {
			for _, rec := range recs {
				if !slices.Contains(recipientOpts, rec) {
					recipientOpts = append(recipientOpts, rec)
				}
			}
		}

		if len(recipientOpts) == 0 {
			return errors.New("no identities configured; git age ident --help")
		}

		if err := survey.AskOne(&survey.MultiSelect{
			Message: "Identities",
			Options: recipientOpts,
		}, &recipients); err != nil {
			return err
		}
		if len(recipients) == 0 {
			return errors.New("no identity provided, please add manually to .git-age.yaml")
		}
	}

	cfg[file] = recipients
	return SaveConfig(cfg)
}