intake/cmd/itemAdd.go

69 lines
1.7 KiB
Go
Raw Normal View History

2025-01-17 05:46:49 +00:00
package cmd
import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"github.com/Jaculabilis/intake/core"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/cobra"
)
2025-01-21 16:42:59 +00:00
var itemAddCmd = &cobra.Command{
2025-01-17 05:46:49 +00:00
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) {
2025-01-21 16:42:59 +00:00
itemAdd()
2025-01-17 05:46:49 +00:00
},
}
var addSource string
var addId string
var addTitle string
var addAuthor string
var addBody string
var addLink string
var addTime int
func init() {
2025-01-21 16:42:59 +00:00
itemCmd.AddCommand(itemAddCmd)
2025-01-17 05:46:49 +00:00
2025-01-21 16:42:59 +00:00
itemAddCmd.Flags().StringVarP(&addSource, "source", "s", "", "Source in which to create the item (default: default)")
itemAddCmd.Flags().StringVarP(&addId, "item", "i", "", "Item id (default: random hex)")
itemAddCmd.Flags().StringVarP(&addTitle, "title", "t", "", "Item title")
itemAddCmd.Flags().StringVarP(&addAuthor, "author", "a", "", "Item author")
itemAddCmd.Flags().StringVarP(&addBody, "body", "b", "", "Item body")
itemAddCmd.Flags().StringVarP(&addLink, "link", "l", "", "Item link")
itemAddCmd.Flags().IntVarP(&addTime, "time", "m", 0, "Item time as a Unix timestamp")
2025-01-17 05:46:49 +00:00
}
2025-01-21 16:42:59 +00:00
func itemAdd() {
2025-01-17 05:46:49 +00:00
// 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)
}
2025-01-23 16:36:25 +00:00
db := openAndMigrateDb()
2025-01-17 05:46:49 +00:00
2025-01-23 16:36:25 +00:00
err := core.AddItem(db, addSource, addId, addTitle, addAuthor, addBody, addLink, addTime)
2025-01-17 05:46:49 +00:00
if err != nil {
log.Fatalf("Failed to add item: %s", err)
}
fmt.Printf("Added %s/%s\n", addSource, addId)
}