forked from mop-tracker/mop
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathprofile.go
56 lines (47 loc) · 1.91 KB
/
profile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright (c) 2013-2021 by Michael Dvorkin, Brandon Lee Camilleri and contributors. All Rights Reserved. Use of this source code is governed by a MIT-style license that can be found in README.md.
package TerminalStocks
import (
"encoding/json"
"io/ioutil"
"os/user"
)
// File name in user's home directory where settings are stored.
const TSrc = `/.TSrc`
// Profile manages Terminal Stocks program settings as defined by user.
// The settings are serialized using JSON and saved in the ~/.TSrc file.
type Profile struct {
Tickers []string // List of stock tickers to display.
QuotesRefresh int // Time interval to refresh stock quotes.
selectedColumn int // Stores selected column number when the column editor is active.
}
// Creates the profile and attempts to load the settings from ~/.TSrc file.
// If the file is not there it gets created with default values.
func NewProfile() *Profile {
profile := &Profile{}
data, err := ioutil.ReadFile(profile.defaultFileName())
if err != nil { // Set default values:
profile.QuotesRefresh = 5 // Stock quotes get updated every 5 seconds (12 times per minute).
profile.Tickers = []string{`0700.HK`, `1810.HK`, `AAPL`, `ABNB`, `AMD`, `AMZN`, `ATVI`, `BABA`, `C`, `DIS`, `FB`, `GOOG`, `IBM`, `INTC`, `KO`, `MA`, `MSFT`, `NFLX`, `NVDA`, `ORCL`, `PYPL`, `SONY`, `SQ`, `TSLA`, `V`, `BTC-USD`, `ETH-USD`}
profile.Save()
} else {
json.Unmarshal(data, profile)
}
profile.selectedColumn = -1
return profile
}
// Save serializes settings using JSON and saves them in ~/.TSrc file.
func (profile *Profile) Save() error {
data, err := json.Marshal(profile)
if err != nil {
return err
}
return ioutil.WriteFile(profile.defaultFileName(), data, 0644)
}
//-----------------------------------------------------------------------------
func (profile *Profile) defaultFileName() string {
usr, err := user.Current()
if err != nil {
panic(err)
}
return usr.HomeDir + TSrc
}