From 284206c55c7491b7cd20fc48bdb8064840cbb6d2 Mon Sep 17 00:00:00 2001 From: b4b4r07 Date: Tue, 21 Jan 2020 00:11:56 +0900 Subject: [PATCH] Ask GitHub when not found and save it to cache --- cmd/meta.go | 39 ++++++++++++++++++++++++++++++++------- pkg/gist/cache.go | 10 +++++++--- pkg/gist/gist.go | 8 ++++---- 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/cmd/meta.go b/cmd/meta.go index 2082e19..f678587 100644 --- a/cmd/meta.go +++ b/cmd/meta.go @@ -23,6 +23,9 @@ type meta struct { func (m *meta) init(args []string) error { workDir := filepath.Join(os.Getenv("HOME"), ".gist") cache := gist.NewCache(filepath.Join(workDir, "cache.json")) + // load cache + cache.Open() + m.cache = cache user := os.Getenv("GIST_USER") if user == "" { @@ -32,15 +35,13 @@ func (m *meta) init(args []string) error { if editor == "" { editor = "vim" } - token := os.Getenv("GITHUB_TOKEN") - if token == "" { - return errors.New("GITHUB_TOKEN is missing") + + token, err := m.githubToken() + if err != nil { + return err } client := gist.NewClient(token) - // load cache - cache.Open() - var pages []gist.Page switch len(cache.Pages) { case 0: @@ -73,7 +74,6 @@ func (m *meta) init(args []string) error { defer s.Stop() gist.Checkout() - m.cache = cache m.gist = gist m.files = gist.Files() return nil @@ -141,3 +141,28 @@ func (m *meta) prompt() (gist.File, error) { i, _, err := prompt.Run() return m.files[i], err } + +func (m *meta) githubToken() (string, error) { + var token string + token = os.Getenv("GITHUB_TOKEN") + if token != "" { + return token, nil + } + if m.cache == nil { + return "", errors.New("cache is nil") + } + token = m.cache.Token + if token != "" { + return token, nil + } + prompt := promptui.Prompt{ + Label: "GITHUB_TOKEN", + Mask: '*', + } + token, err := prompt.Run() + if err != nil { + return "", err + } + m.cache.Token = token + return token, nil +} diff --git a/pkg/gist/cache.go b/pkg/gist/cache.go index 8b041dc..e647514 100644 --- a/pkg/gist/cache.go +++ b/pkg/gist/cache.go @@ -6,13 +6,17 @@ import ( ) type Cache struct { + Token string `json:"token"` Pages []Page `json:"pages"` - - Path string `json:"-"` + Path string `json:"-"` } func NewCache(path string) *Cache { - return &Cache{Path: path, Pages: []Page{}} + return &Cache{ + Token: os.Getenv("GITHUB_TOKEN"), + Pages: []Page{}, + Path: path, + } } func (c *Cache) Open() error { diff --git a/pkg/gist/gist.go b/pkg/gist/gist.go index 6b14798..d1a9bfb 100644 --- a/pkg/gist/gist.go +++ b/pkg/gist/gist.go @@ -40,11 +40,11 @@ type Page struct { // File represents a single file hosted on gist type File struct { - Name string - Content string - FullPath string + Name string `json:"name"` + Content string `json:"content"` + FullPath string `json:"fullpath"` - Page + Page `json:"-"` } func (g Gist) Files() []File {