-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreate.go
More file actions
103 lines (83 loc) · 2.39 KB
/
create.go
File metadata and controls
103 lines (83 loc) · 2.39 KB
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
package cmd
import (
"os"
"path/filepath"
"strings"
"github.com/shikaan/keydex/pkg/cli"
"github.com/shikaan/keydex/pkg/credentials"
"github.com/shikaan/keydex/pkg/errors"
"github.com/shikaan/keydex/pkg/info"
"github.com/shikaan/keydex/pkg/kdbx"
"github.com/shikaan/keydex/tui"
"github.com/spf13/cobra"
)
var Create = &cobra.Command{
Use: "create [file] [name]",
Short: "Create an empty KeePass archive.",
Aliases: []string{"new"},
Long: `Create an empty KeePass archive.
Creates a new KeePass database at 'file' called 'name'. You will be prompted to set a passphrase for the new database.
See "Examples" for more details.`,
Example: ` # Create a new database called "vault" at vault.kdbx
` + info.NAME + ` create vault.kdbx vault
# Create a new database at a specific path
` + info.NAME + ` create ~/passwords/work.kdbx work`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
path := args[0]
name := args[1]
if _, err := os.Stat(path); err == nil {
return errors.MakeError("Database file "+path+" already exists.", "create")
}
passphrase, err := credentials.MakePassphrase(path)
if err != nil {
return err
}
keyfilepath := ""
if cli.Confirm("Do you want to create a keyfile?") {
filename := strings.Replace(filepath.Base(path), filepath.Ext(path), "-key.xml", 1)
keyfilepath = filepath.Join(filepath.Dir(path), filename)
if err = credentials.CreateXMLKeyFileV2(keyfilepath); err != nil {
return err
}
}
success := false
defer func() {
if !success {
if keyfilepath != "" {
_ = os.Remove(keyfilepath)
}
_ = os.Remove(path)
}
}()
file, err := os.Create(path)
if err != nil {
return errors.MakeError(`Cannot create file: `+err.Error(), "create")
}
defer file.Close()
db, err := kdbx.NewFromFile(file)
if err != nil {
return err
}
if err = db.SetPasswordAndKey(passphrase, keyfilepath); err != nil {
return err
}
rootGroup := db.NewGroup(name)
db.Content.Root.Groups = []kdbx.Group{*rootGroup}
db.Database.Content.Meta.DatabaseName = name
if err = db.SaveAndUnlockEntries(); err != nil {
return err
}
success = true
if cli.Confirm("Creation successful. Do you want to open the database?") {
return tui.Run(tui.State{
Entry: nil,
Group: nil,
Database: db,
Reference: "",
}, false)
}
return nil
},
DisableAutoGenTag: true,
}