-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmds.go
394 lines (333 loc) · 9.23 KB
/
cmds.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/iamhectorsosa/anchor/internal/database"
"github.com/iamhectorsosa/anchor/internal/logger"
"github.com/iamhectorsosa/anchor/internal/store"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "anchor [key] [...$1] | [key='value']",
Short: "Anchor is a CLI tool for managing your anchors.",
Long: `Anchor is a CLI tool for managing your anchors.
To get an anchor, use: anchor [key] [...$1]
To add anchors, use: anchor [key='value']`,
Args: cobra.ArbitraryArgs,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
if len(args) >= 1 {
input := args[0]
if strings.Contains(input, "=") {
inputSlice := strings.SplitN(input, "=", 2)
if len(inputSlice) != 2 {
return log.Error("invalid format. Use: key='value'")
}
key := inputSlice[0]
value := strings.TrimSpace(strings.Trim(inputSlice[1], "'"))
parsedURL, err := url.Parse(strings.ReplaceAll(value, "\\", ""))
if err != nil {
return log.Error("url.Parse, err=%v", err)
}
value = parsedURL.String()
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
if err = db.Create(key, value); err != nil {
return log.Error("db.Create, err=%v", err)
}
log.Info("Anchor successfully created, key=%q value=%q.", key, value)
return nil
}
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
key := input
anchor, err := db.Read(key)
if err != nil {
return log.Error("db.Read, err=%v", err)
}
value := anchor.Value
placeholderCount := strings.Count(value, "$")
if placeholderCount != len(args)-1 {
return log.Error("missing arguments for %s=%q", key, value)
}
for i, arg := range args[1:] {
placeholder := fmt.Sprintf("$%d", i+1)
value = strings.ReplaceAll(value, placeholder, arg)
}
cmd := exec.Command("pbcopy")
cmd.Stdin = bytes.NewReader([]byte(value))
if err := cmd.Run(); err != nil {
return log.Error("pbcopy in cmd.Run, err=%v", err)
}
log.Info("Copied to clipboard, value=%q", value)
cmd = exec.Command("open", value)
if err := cmd.Run(); err != nil {
return log.Error("open in cmd.Run, err=%v", err)
}
return nil
} else {
return cmd.Help()
}
},
}
var ls = &cobra.Command{
Use: "ls",
Short: "List all anchors",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
anchors, err := db.ReadAll()
if err != nil {
return log.Error("db.ReadAll, err=%v", err)
}
log.Info("Found %d anchors...", len(anchors))
if len(anchors) == 0 {
return nil
}
maxKeyLen, maxValueLen := 0, 0
for _, s := range anchors {
if len(s.Key) > maxKeyLen {
maxKeyLen = len(s.Key) + 6
}
if len(s.Value) > maxValueLen {
maxValueLen = len(s.Value)
}
}
anchors = append([]store.Anchor{store.Anchor{
Id: 0,
Key: "KEY",
Value: "VALUE",
}}, anchors...)
evenStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("245"))
for i, s := range anchors {
key := fmt.Sprintf("%-*s", maxKeyLen, s.Key)
value := fmt.Sprintf("%-*s", maxValueLen, s.Value)
if i%2 == 0 {
key = evenStyle.Render(key)
value = evenStyle.Render(value)
}
fmt.Println(key, value)
}
return nil
},
}
var update = &cobra.Command{
Use: "update [key='new_value']",
Short: "Update an anchor",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
input := args[0]
inputSlice := strings.SplitN(input, "=", 2)
if len(inputSlice) != 2 {
return log.Error("invalid format. Use: key='new_value'")
}
key := inputSlice[0]
newValue := strings.TrimSpace(strings.Trim(inputSlice[1], "'"))
parsedURL, err := url.Parse(strings.ReplaceAll(newValue, "\\", ""))
if err != nil {
return log.Error("url.Parse, err=%v", err)
}
newValue = parsedURL.String()
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
anchor, err := db.Read(key)
if err != nil {
return log.Error("db.Read, err=%v", err)
}
if err = db.Update(store.Anchor{
Id: anchor.Id,
Key: key,
Value: newValue,
}); err != nil {
return log.Error("db.Update, err=%v", err)
}
log.Info("Anchor successfully updated, key=%q value=%q.", key, newValue)
return nil
},
}
var delete = &cobra.Command{
Use: "delete [key]",
Short: "Delete a anchor",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
key := args[0]
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
if err = db.Delete(key); err != nil {
return log.Error("db.Delete, err=%v", err)
}
log.Info("Anchor successfully deleted, key=%q.", key)
return nil
},
}
var reset = &cobra.Command{
Use: "reset",
Short: "Reset all anchors",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
if err = db.Reset(); err != nil {
return log.Error("db.Reset, err=%v", err)
}
log.Info("Anchors have been successfully reset")
return nil
},
}
var (
exportPath string
importFilePath string
importUrlPath string
)
var export = &cobra.Command{
Use: "export",
Short: "Export all anchors",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
anchors, err := db.ReadAll()
if err != nil {
return log.Error("db.ReadAll, err=%v", err)
}
log.Info("Generating report with %d anchors...", len(anchors))
filename := filepath.Join(exportPath, fmt.Sprintf("anchor-%s.csv", time.Now().Format("2006-01-02")))
filename = filepath.Clean(filename)
file, err := os.Create(filename)
if err != nil {
return log.Error("os.Create, err=%v", err)
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
if err := writer.Write([]string{"Key", "Value"}); err != nil {
return fmt.Errorf("writer.Write, err=%v", err)
}
for _, anchor := range anchors {
if err := writer.Write([]string{anchor.Key, anchor.Value}); err != nil {
return fmt.Errorf("writer.Write, err=%v", err)
}
}
log.Info("CSV file successfully created at path=%q", filename)
return nil
},
}
var importc = &cobra.Command{
Use: "import",
Short: "Import anchors",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
log := logger.New()
if importFilePath == "" && importUrlPath == "" {
return log.Error("a valid path or url is required, path=%q, url=%q", importFilePath, importUrlPath)
}
var reader io.Reader
if importFilePath != "" {
importFilePath = filepath.Clean(importFilePath)
file, err := os.Open(importFilePath)
if err != nil {
return log.Error("os.Open, err=%v", err)
}
defer file.Close()
reader = file
} else {
req, err := http.NewRequest(http.MethodGet, importUrlPath, nil)
if err != nil {
return log.Error("http.NewRequest, err=%v", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return log.Error("http.Get, err=%v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return log.Error("resp.StatusCode, status=%v", resp.Status)
}
reader = resp.Body
}
csvReader := csv.NewReader(reader)
records, err := csvReader.ReadAll()
if err != nil {
return log.Error("csvReader.ReadAll, err=%v", err)
}
var anchors []store.Anchor
for _, record := range records[1:] {
if len(record) < 2 {
continue
}
anchor := store.Anchor{
Key: record[0],
Value: record[1],
}
anchors = append(anchors, anchor)
}
if len(anchors) == 0 {
return log.Error("no valid anchors where found")
}
db, cleanup, err := database.New()
if err != nil {
return log.Error("database.New, err=%v", err)
}
defer cleanup()
if err := db.Import(anchors); err != nil {
return log.Error("db.Import, err=%v", err)
}
source := importFilePath
if source == "" {
source = importUrlPath
}
log.Info("CSV file successfully imported from %q", source)
return nil
},
}
func init() {
rootCmd.AddCommand(ls)
rootCmd.AddCommand(update)
rootCmd.AddCommand(delete)
rootCmd.AddCommand(reset)
rootCmd.AddCommand(export)
rootCmd.AddCommand(importc)
export.Flags().StringVarP(&exportPath, "path", "p", ".", "Path to directory for CSV output")
importc.Flags().StringVarP(&importFilePath, "path", "p", "", "Path to directory of your CSV file")
importc.Flags().StringVarP(&importUrlPath, "url", "u", "", "URL of your remote CSV file")
rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.SilenceUsage = true
rootCmd.SilenceErrors = true
}