2014-08-02 21:59:53 +02:00
|
|
|
package util
|
|
|
|
|
|
|
|
|
|
import (
|
2014-08-03 22:35:53 +02:00
|
|
|
"errors"
|
2014-08-02 21:59:53 +02:00
|
|
|
"fmt"
|
|
|
|
|
"io/ioutil"
|
|
|
|
|
"os"
|
2014-08-03 22:35:53 +02:00
|
|
|
"path"
|
|
|
|
|
"path/filepath"
|
2014-08-02 21:59:53 +02:00
|
|
|
|
|
|
|
|
"code.google.com/p/gcfg"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
2014-11-15 13:33:20 +01:00
|
|
|
DefaultAPIURL = "https://asciinema.org"
|
2014-08-02 21:59:53 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Config struct {
|
2014-11-15 13:33:20 +01:00
|
|
|
API struct {
|
2014-08-02 21:59:53 +02:00
|
|
|
Token string
|
2014-11-15 13:33:20 +01:00
|
|
|
URL string
|
2014-08-02 21:59:53 +02:00
|
|
|
}
|
|
|
|
|
Record struct {
|
|
|
|
|
Command string
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2014-11-12 20:58:14 +01:00
|
|
|
func LoadConfig() (*Config, error) {
|
2014-08-03 22:35:53 +02:00
|
|
|
homeDir := os.Getenv("HOME")
|
|
|
|
|
if homeDir == "" {
|
|
|
|
|
return nil, errors.New("Need $HOME")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
cfgPath := filepath.Join(homeDir, ".asciinema", "config")
|
2014-08-02 21:59:53 +02:00
|
|
|
|
2014-08-03 22:35:53 +02:00
|
|
|
cfg, err := loadConfigFile(cfgPath)
|
2014-08-02 21:59:53 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2014-11-15 13:33:20 +01:00
|
|
|
if cfg.API.URL == "" {
|
|
|
|
|
cfg.API.URL = DefaultAPIURL
|
2014-08-02 21:59:53 +02:00
|
|
|
}
|
|
|
|
|
|
2014-11-15 13:33:20 +01:00
|
|
|
if envAPIURL := os.Getenv("ASCIINEMA_API_URL"); envAPIURL != "" {
|
|
|
|
|
cfg.API.URL = envAPIURL
|
2014-08-02 21:59:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return cfg, nil
|
|
|
|
|
}
|
|
|
|
|
|
2014-08-03 22:37:06 +02:00
|
|
|
func loadConfigFile(cfgPath string) (*Config, error) {
|
|
|
|
|
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
|
|
|
|
|
if err = createConfigFile(cfgPath); err != nil {
|
2014-08-02 21:59:53 +02:00
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var cfg Config
|
2014-08-03 22:37:06 +02:00
|
|
|
if err := gcfg.ReadFileInto(&cfg, cfgPath); err != nil {
|
2014-08-02 21:59:53 +02:00
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &cfg, nil
|
|
|
|
|
}
|
|
|
|
|
|
2014-08-03 22:37:06 +02:00
|
|
|
func createConfigFile(cfgPath string) error {
|
2014-08-02 21:59:53 +02:00
|
|
|
apiToken := NewUUID().String()
|
|
|
|
|
contents := fmt.Sprintf("[api]\ntoken = %v\n", apiToken)
|
2014-08-03 22:37:06 +02:00
|
|
|
os.MkdirAll(path.Dir(cfgPath), 0755)
|
|
|
|
|
return ioutil.WriteFile(cfgPath, []byte(contents), 0644)
|
2014-08-02 21:59:53 +02:00
|
|
|
}
|