• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nats-io / nsc / 14765656943

30 Apr 2025 10:34PM UTC coverage: 69.949% (-4.2%) from 74.148%
14765656943

Pull #691

github

web-flow
Merge b4ee16f94 into a9c0df586
Pull Request #691: Generate docs

1 of 1 new or added line in 1 file covered. (100.0%)

3680 existing lines in 93 files now uncovered.

12325 of 17620 relevant lines covered (69.95%)

1.66 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

58.33
/cmd/generatecontext.go
1
// Copyright 2023 The NATS Authors
2
// Licensed under the Apache License, Version 2.0 (the "License");
3
// you may not use this file except in compliance with the License.
4
// You may obtain a copy of the License at
5
//
6
// http://www.apache.org/licenses/LICENSE-2.0
7
//
8
// Unless required by applicable law or agreed to in writing, software
9
// distributed under the License is distributed on an "AS IS" BASIS,
10
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
// See the License for the specific language governing permissions and
12
// limitations under the License.
13

14
package cmd
15

16
import (
17
        "encoding/json"
18
        "fmt"
19
        "os"
20
        "path/filepath"
21
        "strings"
22

23
        "github.com/nats-io/nsc/v2/cmd/store"
24
        "github.com/nats-io/nsc/v2/home"
25
        "github.com/spf13/cobra"
26
)
27

28
func init() {
29
        generateCmd.AddCommand(createGenerateContext())
30
}
2✔
31

2✔
32
type GenerateContextParams struct {
2✔
33
        AccountContextParams
34
        user        string
35
        context     string
36
        creds       string
37
        operatorURL string
38
}
39

40
func createGenerateContext() *cobra.Command {
41
        var params GenerateContextParams
42
        cmd := &cobra.Command{
2✔
43
                Use:          "context",
2✔
44
                Short:        "Generate nats cli user context",
2✔
45
                Args:         MaxArgs(0),
2✔
46
                SilenceUsage: true,
2✔
47
                Example:      `nsc generate context --account a --user u --context contextName`,
2✔
48
                RunE: func(cmd *cobra.Command, args []string) error {
2✔
49
                        return RunAction(cmd, args, &params)
2✔
50
                },
4✔
51
        }
2✔
52
        cmd.Flags().StringVarP(&params.user, "user", "u", "", "user name")
2✔
53
        cmd.Flags().StringVarP(&params.context, "context", "", "", "context name")
54
        params.AccountContextParams.BindFlags(cmd)
2✔
55

2✔
56
        return cmd
2✔
57
}
2✔
58

2✔
59
func (p *GenerateContextParams) SetDefaults(ctx ActionCtx) error {
60
        p.AccountContextParams.SetDefaults(ctx)
61
        if p.user == "" && p.AccountContextParams.Name != "" {
2✔
62
                entries, err := ctx.StoreCtx().Store.ListEntries(store.Accounts, p.AccountContextParams.Name, store.Users)
2✔
63
                if err != nil {
2✔
64
                        return err
×
65
                }
×
66
                switch len(entries) {
×
67
                case 0:
×
68
                        return fmt.Errorf("account %q has no users", p.AccountContextParams.Name)
×
69
                case 1:
×
70
                        p.user = entries[0]
×
UNCOV
71
                }
×
UNCOV
72
        }
×
73

74
        return nil
75
}
76

2✔
77
func (p *GenerateContextParams) PreInteractive(_ ActionCtx) error {
78
        return nil
79
}
×
UNCOV
80

×
UNCOV
81
func (p *GenerateContextParams) Load(ctx ActionCtx) error {
×
82
        oc, err := ctx.StoreCtx().Store.ReadOperatorClaim()
83
        if err != nil {
2✔
84
                return err
2✔
85
        }
2✔
UNCOV
86
        if len(oc.OperatorServiceURLs) > 0 {
×
87
                p.operatorURL = oc.OperatorServiceURLs[0]
×
88
        }
2✔
UNCOV
89
        return nil
×
UNCOV
90
}
×
91

2✔
92
func (p *GenerateContextParams) PostInteractive(_ ActionCtx) error {
93
        return nil
94
}
×
UNCOV
95

×
UNCOV
96
func (p *GenerateContextParams) Validate(ctx ActionCtx) error {
×
97
        if p.context == "" {
98
                return fmt.Errorf("context name is required")
2✔
99
        }
2✔
UNCOV
100
        if strings.ContainsAny(p.context, "/\\") {
×
101
                return fmt.Errorf("context name cannot contain filepath separators")
×
102
        }
2✔
UNCOV
103
        if p.AccountContextParams.Name == "" {
×
104
                return fmt.Errorf("account is required")
×
105
        }
2✔
UNCOV
106
        if p.user == "" {
×
107
                return fmt.Errorf("user is required")
×
108
        }
2✔
UNCOV
109
        if !ctx.StoreCtx().Store.Has(store.Accounts, p.AccountContextParams.Name, store.Users, store.JwtName(p.user)) {
×
110
                return fmt.Errorf("user %q not found in %q", p.user, p.AccountContextParams.Name)
×
111
        }
2✔
UNCOV
112
        p.creds = ctx.StoreCtx().KeyStore.CalcUserCredsPath(p.AccountContextParams.Name, p.user)
×
UNCOV
113
        if _, err := os.Stat(p.creds); err != nil {
×
114
                return fmt.Errorf("creds file %q - doesn't exist - nsc generate creds first", p.creds)
2✔
115
        }
2✔
UNCOV
116
        return nil
×
UNCOV
117
}
×
118

2✔
119
type cliContext struct {
120
        Nsc   string `json:"nsc,omitempty"`
121
        Url   string `json:"url,omitempty"`
122
        Creds string `json:"creds,omitempty"`
123
}
124

125
func (p *GenerateContextParams) Run(ctx ActionCtx) (store.Status, error) {
126
        var s store.Status
127
        natsCli := cliContext{}
2✔
128
        natsCli.Creds = p.creds
2✔
129
        natsCli.Nsc = fmt.Sprintf(`nsc://%s/%s/%s`, ctx.StoreCtx().Operator.Name, p.AccountContextParams.Name, p.user)
2✔
130
        natsCli.Url = p.operatorURL
2✔
131

2✔
132
        if err := os.MkdirAll(home.NatsCliContextDir(), 0755); err != nil {
2✔
133
                s = store.ErrorStatus("failed to create context dir %q: %v", home.NatsCliContextDir(), err)
2✔
134
                return s, nil
2✔
135
        }
×
UNCOV
136
        if !strings.HasSuffix(p.context, ".json") {
×
UNCOV
137
                p.context = fmt.Sprintf("%s.json", p.context)
×
138
        }
4✔
139
        fn := filepath.Join(home.NatsCliContextDir(), p.context)
2✔
140
        ctx.CurrentCmd().Println(fn)
2✔
141
        bytes, err := json.Marshal(natsCli)
2✔
142
        if err != nil {
2✔
143
                s = store.FromError(err)
2✔
144
                return s, nil
2✔
145
        }
×
UNCOV
146
        if err := Write(fn, bytes); err != nil {
×
147
                s = store.ErrorStatus("failed to write context file: %v", err)
×
148
                return s, nil
2✔
149
        }
×
UNCOV
150
        s = store.OKStatus("wrote nats cli context file to %#q", AbbrevHomePaths(fn))
×
UNCOV
151

×
152
        return s, nil
2✔
153
}
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc