Skip to content

Commit

Permalink
Merge pull request #2 from meowgorithm/master
Browse files Browse the repository at this point in the history
Add help/usage and exit gracefully on error
  • Loading branch information
Stephen Solka authored Oct 23, 2020
2 parents 8fa33b7 + 8ae693c commit edbeb66
Showing 1 changed file with 37 additions and 10 deletions.
47 changes: 37 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,30 @@ import (
"github.com/nfnt/resize"
)

const usage = `imgcat [pattern|url]
Examples:
imgcat path/to/image.jpg
imgcat *.jpg
imgcat https://example.com/image.jpg`

func main() {
if len(os.Args) == 1 {
fmt.Println(usage)
os.Exit(1)
}

if os.Args[1] == "-h" || os.Args[1] == "--help" {
fmt.Println(usage)
os.Exit(0)
}

p := tea.NewProgram(model{urls: os.Args[1:len(os.Args)]})
p.EnterAltScreen()
err := p.Start()
p.ExitAltScreen()
if err != nil {
panic(err)
defer p.ExitAltScreen()
if err := p.Start(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

Expand All @@ -32,13 +49,20 @@ type model struct {
selected int
urls []string
image string
err error
}

func (m model) Init() tea.Cmd {
return load(m.urls[m.selected])
}

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.err != nil {
if _, ok := msg.(tea.KeyMsg); ok {
return m, tea.Quit
}
}

switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
Expand All @@ -60,23 +84,23 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, load(m.urls[m.selected])
}
case errMsg:
m.image = msg.Error()
m.err = msg
return m, nil
case loadMsg:
url := m.urls[m.selected]
if msg.resp != nil {
defer msg.resp.Body.Close()
img, err := readerToImage(url, msg.resp.Body)
if err != nil {
return m, func() tea.Msg { return errMsg(err) }
return m, func() tea.Msg { return errMsg{err} }
}
m.image = img
return m, nil
}
defer msg.file.Close()
img, err := readerToImage(url, msg.file)
if err != nil {
return m, func() tea.Msg { return errMsg(err) }
return m, func() tea.Msg { return errMsg{err} }
}
m.image = img
return m, nil
Expand All @@ -85,6 +109,9 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}

func (m model) View() string {
if m.err != nil {
return fmt.Sprintf("couldn't load image(s): %v\n\npress any key to exit", m.err)
}
if m.image == "" {
return fmt.Sprintf("loading %s %s", m.urls[m.selected], sparkles)
}
Expand All @@ -96,22 +123,22 @@ type loadMsg struct {
file *os.File
}

type errMsg error
type errMsg struct{ error }

func load(url string) tea.Cmd {
if strings.HasPrefix(url, "http") {
return func() tea.Msg {
resp, err := http.Get(url)
if err != nil {
return errMsg(err)
return errMsg{err}
}
return loadMsg{resp: resp}
}
}
return func() tea.Msg {
file, err := os.Open(url)
if err != nil {
return errMsg(err)
return errMsg{err}
}
return loadMsg{file: file}
}
Expand Down

0 comments on commit edbeb66

Please sign in to comment.