Add flags for custom title and excerpt

This commit is contained in:
Radhi Fadlillah 2018-01-30 14:57:36 +07:00
parent 25b67ee423
commit 6de94ccffb
2 changed files with 42 additions and 5 deletions

View file

@ -15,10 +15,13 @@ var (
Run: func(cmd *cobra.Command, args []string) {
// Read flag and arguments
url := args[0]
title, _ := cmd.Flags().GetString("title")
excerpt, _ := cmd.Flags().GetString("excerpt")
tags, _ := cmd.Flags().GetStringSlice("tags")
offline, _ := cmd.Flags().GetBool("offline")
// Save new bookmark
err := addBookmark(url, tags...)
err := addBookmark(url, title, excerpt, tags, offline)
if err != nil {
cError.Println(err)
os.Exit(1)
@ -28,14 +31,39 @@ var (
)
func init() {
addCmd.Flags().StringP("title", "i", "", "Custom title for this bookmark.")
addCmd.Flags().StringP("excerpt", "e", "", "Custom excerpt for this bookmark.")
addCmd.Flags().StringSliceP("tags", "t", []string{}, "Comma-separated tags for this bookmark.")
addCmd.Flags().BoolP("offline", "o", false, "Save bookmark without fetching data from internet.")
rootCmd.AddCommand(addCmd)
}
func addBookmark(url string, tags ...string) error {
article, err := readability.Parse(url, 10*time.Second)
if err != nil {
return err
func addBookmark(url, title, excerpt string, tags []string, offline bool) (err error) {
// Prepare variable
defaultArticle := readability.Article{
URL: url,
Meta: readability.Metadata{
Title: "Untitled",
},
}
article := defaultArticle
// Fetch data from internet
if !offline {
article, err = readability.Parse(url, 10*time.Second)
if err != nil {
cError.Println("Failed to fetch article from internet")
article = defaultArticle
}
}
// Set custom value
if title != "" {
article.Meta.Title = title
}
if excerpt != "" {
article.Meta.Excerpt = excerpt
}
bookmark, err := DB.SaveBookmark(article, tags...)

View file

@ -77,6 +77,15 @@ func OpenSQLiteDatabase() (*SQLiteDatabase, error) {
}
func (db *SQLiteDatabase) SaveBookmark(article readability.Article, tags ...string) (bookmark model.Bookmark, err error) {
// Check URL and title
if article.URL == "" {
return model.Bookmark{}, fmt.Errorf("URL must not empty")
}
if article.Meta.Title == "" {
return model.Bookmark{}, fmt.Errorf("Title must not empty")
}
// Prepare transaction
tx, err := db.Beginx()
if err != nil {