cmdEdit opens a cheatsheet for editing (or creates it if it doesn't exist).
(cmd *cobra.Command, _ []string, conf config.Config)
| 17 | |
| 18 | // cmdEdit opens a cheatsheet for editing (or creates it if it doesn't exist). |
| 19 | func cmdEdit(cmd *cobra.Command, _ []string, conf config.Config) { |
| 20 | |
| 21 | cheatsheet, _ := cmd.Flags().GetString("edit") |
| 22 | |
| 23 | // validate the cheatsheet name |
| 24 | if err := sheet.Validate(cheatsheet); err != nil { |
| 25 | fmt.Fprintf(os.Stderr, "invalid cheatsheet name: %v\n", err) |
| 26 | os.Exit(1) |
| 27 | } |
| 28 | |
| 29 | // load the cheatsheets |
| 30 | cheatsheets, err := sheets.Load(conf.Cheatpaths) |
| 31 | if err != nil { |
| 32 | fmt.Fprintf(os.Stderr, "failed to list cheatsheets: %v\n", err) |
| 33 | os.Exit(1) |
| 34 | } |
| 35 | if cmd.Flags().Changed("tag") { |
| 36 | tagVal, _ := cmd.Flags().GetString("tag") |
| 37 | cheatsheets = sheets.Filter( |
| 38 | cheatsheets, |
| 39 | strings.Split(tagVal, ","), |
| 40 | ) |
| 41 | } |
| 42 | |
| 43 | // consolidate the cheatsheets found on all paths into a single map of |
| 44 | // `title` => `sheet` (ie, allow more local cheatsheets to override less |
| 45 | // local cheatsheets) |
| 46 | consolidated := sheets.Consolidate(cheatsheets) |
| 47 | |
| 48 | // the file path of the sheet to edit |
| 49 | var editpath string |
| 50 | |
| 51 | // determine if the sheet exists |
| 52 | sheet, ok := consolidated[cheatsheet] |
| 53 | |
| 54 | // if the sheet exists and is not read-only, edit it in place |
| 55 | if ok && !sheet.ReadOnly { |
| 56 | editpath = sheet.Path |
| 57 | } else { |
| 58 | // for read-only or non-existent sheets, resolve a writeable path |
| 59 | writepath, err := cheatpath.Writeable(conf.Cheatpaths) |
| 60 | if err != nil { |
| 61 | fmt.Fprintf(os.Stderr, "failed to get writeable path: %v\n", err) |
| 62 | os.Exit(1) |
| 63 | } |
| 64 | |
| 65 | // use the existing title for read-only copies, the requested name otherwise |
| 66 | title := cheatsheet |
| 67 | if ok { |
| 68 | title = sheet.Title |
| 69 | } |
| 70 | editpath = filepath.Join(writepath.Path, title) |
| 71 | |
| 72 | if ok { |
| 73 | // copy the read-only sheet to the writeable path |
| 74 | // (Copy handles MkdirAll internally) |
| 75 | if err := sheet.Copy(editpath); err != nil { |
| 76 | fmt.Fprintf(os.Stderr, "failed to copy cheatsheet: %v\n", err) |