From a67b21bf41be463c8849089c0df4c1990b01da8f Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Thu, 16 Jan 2025 21:46:49 -0800 Subject: [PATCH] Add command to add items --- cmd/add.go | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 cmd/add.go diff --git a/cmd/add.go b/cmd/add.go new file mode 100644 index 0000000..2b3d401 --- /dev/null +++ b/cmd/add.go @@ -0,0 +1,75 @@ +package cmd + +import ( + "crypto/rand" + "database/sql" + "encoding/hex" + "fmt" + "log" + + "github.com/Jaculabilis/intake/core" + _ "github.com/mattn/go-sqlite3" + "github.com/spf13/cobra" +) + +var addCmd = &cobra.Command{ + Use: "add", + Short: "Add an item", + Long: `Create an ad-hoc item in a source. + +By default, the item is created in the "default" source, which is created +if it doesn't exist, with a random id.`, + Run: func(cmd *cobra.Command, args []string) { + add() + }, +} + +var addSource string +var addId string +var addTitle string +var addAuthor string +var addBody string +var addLink string +var addTime int + +func init() { + rootCmd.AddCommand(addCmd) + + addCmd.Flags().StringVarP(&addSource, "source", "s", "", "Source in which to create the item (default: default)") + addCmd.Flags().StringVarP(&addId, "item", "i", "", "Item id (default: random hex)") + addCmd.Flags().StringVarP(&addTitle, "title", "t", "", "Item title") + addCmd.Flags().StringVarP(&addAuthor, "author", "a", "", "Item author") + addCmd.Flags().StringVarP(&addBody, "body", "b", "", "Item body") + addCmd.Flags().StringVarP(&addLink, "link", "l", "", "Item link") + addCmd.Flags().IntVarP(&addTime, "time", "m", 0, "Item time as a Unix timestamp") +} + +func add() { + // Default to "default" source + if addSource == "" { + addSource = "default" + } + // Default id to random hex string + if addId == "" { + bytes := make([]byte, 16) + if _, err := rand.Read(bytes); err != nil { + log.Fatal("Failed to generate id") + } + addId = hex.EncodeToString(bytes) + } + + db, err := sql.Open("sqlite3", getDbPath()) + if err != nil { + log.Fatalf("Failed to open %s", dbPath) + } + + core.InitDatabase(db) + core.MigrateDatabase(db) + + err = core.AddItem(db, addSource, addId, addTitle, addAuthor, addBody, addLink, addTime) + if err != nil { + log.Fatalf("Failed to add item: %s", err) + } + + fmt.Printf("Added %s/%s\n", addSource, addId) +}