intake/cmd/itemAdd.go

69 lines
1.7 KiB
Go

package cmd
import (
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"github.com/Jaculabilis/intake/core"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/cobra"
)
var itemAddCmd = &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) {
itemAdd()
},
}
var addSource string
var addId string
var addTitle string
var addAuthor string
var addBody string
var addLink string
var addTime int
func init() {
itemCmd.AddCommand(itemAddCmd)
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")
}
func itemAdd() {
// 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 := openAndMigrateDb()
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)
}