From 6de94ccffbefcd102336a545879a4a63553c3476 Mon Sep 17 00:00:00 2001 From: Radhi Fadlillah Date: Tue, 30 Jan 2018 14:57:36 +0700 Subject: [PATCH] Add flags for custom title and excerpt --- cmd/add.go | 38 +++++++++++++++++++++++++++++++++----- database/sqlite.go | 9 +++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/cmd/add.go b/cmd/add.go index 9a88f54..33d71ba 100644 --- a/cmd/add.go +++ b/cmd/add.go @@ -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...) diff --git a/database/sqlite.go b/database/sqlite.go index 7bbc89f..a46c60a 100644 --- a/database/sqlite.go +++ b/database/sqlite.go @@ -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 {