95 lines
2.2 KiB
Go
95 lines
2.2 KiB
Go
package cmd
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"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(
|
|
stringArg(cmd, "source"),
|
|
stringArg(cmd, "id"),
|
|
stringArg(cmd, "title"),
|
|
stringArg(cmd, "author"),
|
|
stringArg(cmd, "body"),
|
|
stringArg(cmd, "link"),
|
|
intArg(cmd, "time"),
|
|
stringArg(cmd, "action"),
|
|
)
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
itemCmd.AddCommand(itemAddCmd)
|
|
|
|
itemAddCmd.Flags().StringP("source", "s", "", "Source in which to create the item (default: default)")
|
|
itemAddCmd.Flags().StringP("id", "i", "", "Item id (default: random hex)")
|
|
itemAddCmd.Flags().StringP("title", "t", "", "Item title")
|
|
itemAddCmd.Flags().StringP("author", "a", "", "Item author")
|
|
itemAddCmd.Flags().StringP("body", "b", "", "Item body")
|
|
itemAddCmd.Flags().StringP("link", "l", "", "Item link")
|
|
itemAddCmd.Flags().IntP("time", "m", 0, "Item time as a Unix timestamp")
|
|
itemAddCmd.Flags().StringP("action", "x", "", "Item action data as JSON")
|
|
}
|
|
|
|
func itemAdd(
|
|
source string,
|
|
id string,
|
|
title string,
|
|
author string,
|
|
body string,
|
|
link string,
|
|
time int,
|
|
actions string,
|
|
) {
|
|
// Default to "default" source
|
|
if source == "" {
|
|
source = "default"
|
|
}
|
|
// Default id to random hex string
|
|
if id == "" {
|
|
bytes := make([]byte, 16)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
log.Fatalf("error: failed to generate id: %v", err)
|
|
}
|
|
id = hex.EncodeToString(bytes)
|
|
}
|
|
|
|
var itemActions core.Actions
|
|
if actions != "" {
|
|
if err := json.Unmarshal([]byte(actions), &itemActions); err != nil {
|
|
log.Fatalf("error: could not parse actions: %v", err)
|
|
}
|
|
}
|
|
|
|
db := openAndMigrateDb()
|
|
|
|
if err := core.AddItems(db, []core.Item{{
|
|
Source: source,
|
|
Id: id,
|
|
Title: title,
|
|
Author: author,
|
|
Body: body,
|
|
Link: link,
|
|
Time: time,
|
|
Action: itemActions,
|
|
}}); err != nil {
|
|
log.Fatalf("error: failed to add item: %s", err)
|
|
}
|
|
|
|
log.Printf("Added %s/%s\n", source, id)
|
|
}
|