Add command to add items

This commit is contained in:
Tim Van Baak 2025-01-16 21:46:49 -08:00
parent 43fb2c3917
commit a67b21bf41

75
cmd/add.go Normal file
View File

@ -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)
}