2
0
mirror of https://github.com/skanehira/tson synced 2024-11-03 09:40:22 +00:00
tson/main.go

89 lines
1.5 KiB
Go
Raw Normal View History

2019-10-29 14:01:24 +00:00
package main
import (
2019-10-30 01:49:33 +00:00
"flag"
2019-10-29 14:01:24 +00:00
"fmt"
"io/ioutil"
"log"
2019-11-01 17:04:57 +00:00
"net/http"
2019-10-29 14:01:24 +00:00
"os"
2019-10-30 01:49:33 +00:00
"path/filepath"
"syscall"
2019-10-29 14:01:24 +00:00
2019-10-30 01:49:33 +00:00
"github.com/mitchellh/go-homedir"
2019-10-29 17:28:25 +00:00
"github.com/skanehira/tson/gui"
2019-10-29 14:01:24 +00:00
"golang.org/x/crypto/ssh/terminal"
)
2019-10-30 01:49:33 +00:00
var (
enableLog = flag.Bool("log", false, "enable log")
2019-11-01 17:04:57 +00:00
url = flag.String("url", "", "get json from url")
2019-10-30 01:49:33 +00:00
)
2019-11-01 17:04:57 +00:00
func printError(err error) int {
fmt.Fprintln(os.Stderr, err)
return 1
}
2019-10-30 01:49:33 +00:00
func init() {
flag.Parse()
if *enableLog {
home, err := homedir.Dir()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
logWriter, err := os.OpenFile(filepath.Join(home, "tson.log"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
2019-11-01 17:04:57 +00:00
os.Exit(printError(err))
2019-10-30 01:49:33 +00:00
}
log.SetOutput(logWriter)
log.SetFlags(log.Lshortfile)
} else {
log.SetOutput(ioutil.Discard)
}
2019-10-30 01:49:33 +00:00
}
2019-10-29 14:01:24 +00:00
func run() int {
2019-11-02 08:40:28 +00:00
var i interface{}
2019-11-01 17:04:57 +00:00
if *url != "" {
resp, err := http.Get(*url)
if err != nil {
return printError(err)
}
2019-11-03 11:43:59 +00:00
defer resp.Body.Close()
2019-11-02 08:40:28 +00:00
i, err = gui.UnMarshalJSON(resp.Body)
2019-11-01 17:04:57 +00:00
if err != nil {
return printError(err)
}
} else {
if !terminal.IsTerminal(0) {
var err error
i, err = gui.UnMarshalJSON(os.Stdin)
if err != nil {
return printError(err)
}
2019-11-01 17:04:57 +00:00
// set tview tty to stdin
os.Stdin = os.NewFile(uintptr(syscall.Stderr), "/dev/tty")
2019-10-29 14:01:24 +00:00
}
2019-11-02 08:40:28 +00:00
}
2019-10-29 14:01:24 +00:00
2019-11-03 00:54:51 +00:00
if i == nil {
return printError(gui.ErrEmptyJSON)
}
2019-11-02 08:40:28 +00:00
if err := gui.New().Run(i); err != nil {
log.Println(err)
return 1
2019-10-29 14:01:24 +00:00
}
return 0
}
func main() {
os.Exit(run())
}