-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathcmd_add-identities.go
103 lines (87 loc) · 2.52 KB
/
cmd_add-identities.go
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
// Copyright (c) 2024 Canonical Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cli
import (
"errors"
"fmt"
"os"
"strconv"
"github.com/canonical/go-flags"
"gopkg.in/yaml.v3"
"github.com/canonical/pebble/client"
)
const cmdAddIdentitiesSummary = "Add new identities"
const cmdAddIdentitiesDescription = `
The add-identities command adds one or more new identities.
The named identities must not yet exist.
For example, to add a local admin named "bob", use YAML like this:
> identities:
> bob:
> access: admin
> local:
> user-id: 42
`
type cmdAddIdentities struct {
client *client.Client
From string `long:"from" required:"1"`
}
func init() {
AddCommand(&CmdInfo{
Name: "add-identities",
Summary: cmdAddIdentitiesSummary,
Description: cmdAddIdentitiesDescription,
ArgsHelp: map[string]string{
"--from": "Path of YAML file to read identities from (required)",
},
New: func(opts *CmdOptions) flags.Commander {
return &cmdAddIdentities{client: opts.Client}
},
})
}
func (cmd *cmdAddIdentities) Execute(args []string) error {
if len(args) > 0 {
return ErrExtraArgs
}
identities, err := readIdentities(cmd.From)
if err != nil {
return err
}
err = cmd.client.AddIdentities(identities)
if err != nil {
return err
}
fmt.Fprintf(Stdout, "Added %s.\n", numItems(len(identities), "new identity", "new identities"))
return nil
}
func readIdentities(path string) (map[string]*client.Identity, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var identities identitiesMap
err = yaml.Unmarshal(data, &identities)
if err != nil {
return nil, fmt.Errorf("cannot unmarshal identities: %w", err)
}
if len(identities.Identities) == 0 {
return nil, errors.New(`no identities to add; did you forget the top-level "identities" key?`)
}
return identities.Identities, nil
}
func numItems(n int, singular, plural string) string {
if n == 1 {
return "1 " + singular
}
return strconv.Itoa(n) + " " + plural
}