/* Copyright © 2021 NAME HERE */ package cmd import ( "io/ioutil" "log" "os" "os/exec" "strconv" "github.com/spf13/cobra" ) // noteCmd represents the note command var noteCmd = &cobra.Command{ Use: "note", Args: cobra.ExactArgs(1), Short: "Add a note to the specified diary entry", Long: `Will open your $EDITOR (or nano, if no editor is defined) To define a default editor, set the EDITOR environment variable. Notes can be written in markdown. For example: export EDITOR="vim" `, PreRunE: func(cmd *cobra.Command, args []string) error { id, err := strconv.Atoi(args[0]) if err != nil { return err } _, err = App.GetDiaryEntry(int64(id)) if err != nil { return err } return nil }, Run: func(cmd *cobra.Command, args []string) { entry_id, err := strconv.Atoi(args[0]) if err != nil { log.Fatal(err) } temp_file, err := ioutil.TempFile(os.TempDir(), "diary_note.*.md") if err != nil { log.Fatal(err) } defer os.Remove(temp_file.Name()) var editor = os.Getenv("EDITOR") if editor == "" { editor = "nano" } editor_cmd := exec.Command(editor, temp_file.Name()) editor_cmd.Stdin = os.Stdin editor_cmd.Stdout = os.Stdout editor_cmd.Stderr = os.Stderr err = editor_cmd.Start() if err != nil { log.Fatal(err) } err = editor_cmd.Wait() if err != nil { log.Fatal(err) } content, err := ioutil.ReadFile(temp_file.Name()) if err != nil { log.Fatal(err) } App.NewDiaryEntryNote(int64(entry_id), string(content)) }, } func init() { addCmd.AddCommand(noteCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // noteCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // noteCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }