intake/cmd/itemAdd.go

76 lines
1.9 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
},
}
2025-01-29 17:07:57 +00:00
var addItemSource string
var addItemId string
var addItemTitle string
var addItemAuthor string
var addItemBody string
var addItemLink string
var addItemTime int
2025-01-17 05:46:49 +00:00
func init() {
2025-01-21 16:42:59 +00:00
itemCmd.AddCommand(itemAddCmd)
2025-01-17 05:46:49 +00:00
2025-01-29 17:07:57 +00:00
itemAddCmd.Flags().StringVarP(&addItemSource, "source", "s", "", "Source in which to create the item (default: default)")
itemAddCmd.Flags().StringVarP(&addItemId, "id", "i", "", "Item id (default: random hex)")
itemAddCmd.Flags().StringVarP(&addItemTitle, "title", "t", "", "Item title")
itemAddCmd.Flags().StringVarP(&addItemAuthor, "author", "a", "", "Item author")
itemAddCmd.Flags().StringVarP(&addItemBody, "body", "b", "", "Item body")
itemAddCmd.Flags().StringVarP(&addItemLink, "link", "l", "", "Item link")
itemAddCmd.Flags().IntVarP(&addItemTime, "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
2025-01-29 17:07:57 +00:00
if addItemSource == "" {
addItemSource = "default"
2025-01-17 05:46:49 +00:00
}
// Default id to random hex string
2025-01-29 17:07:57 +00:00
if addItemId == "" {
2025-01-17 05:46:49 +00:00
bytes := make([]byte, 16)
if _, err := rand.Read(bytes); err != nil {
log.Fatal("Failed to generate id")
}
2025-01-29 17:07:57 +00:00
addItemId = hex.EncodeToString(bytes)
2025-01-17 05:46:49 +00:00
}
2025-01-23 16:36:25 +00:00
db := openAndMigrateDb()
2025-01-17 05:46:49 +00:00
2025-01-29 15:43:06 +00:00
if err := core.AddItems(db, []core.Item{{
2025-01-29 17:07:57 +00:00
Source: addItemSource,
Id: addItemId,
Title: addItemTitle,
Author: addItemAuthor,
Body: addItemBody,
Link: addItemLink,
Time: addItemTime,
2025-01-29 15:43:06 +00:00
}}); err != nil {
2025-01-17 05:46:49 +00:00
log.Fatalf("Failed to add item: %s", err)
}
2025-01-29 17:07:57 +00:00
fmt.Printf("Added %s/%s\n", addItemSource, addItemId)
2025-01-17 05:46:49 +00:00
}