Skip to content

Commit

Permalink
Ask GitHub when not found and save it to cache
Browse files Browse the repository at this point in the history
  • Loading branch information
babarot committed Jan 20, 2020
1 parent 62e5e5a commit 284206c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 14 deletions.
39 changes: 32 additions & 7 deletions cmd/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "" {
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
10 changes: 7 additions & 3 deletions pkg/gist/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions pkg/gist/gist.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 284206c

Please sign in to comment.