-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathprofile.go
119 lines (95 loc) · 2.47 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"database/sql"
"errors"
"fmt"
"os"
"os/user"
"path/filepath"
"github.com/laurent22/go-sqlkv"
_ "github.com/mattn/go-sqlite3"
)
const PROFILE_PERM = 0700
var homeDir_ string
var profileFolder_ string
var config_ *sqlkv.SqlKv
var profileDb_ *sql.DB
func profileOpen() error {
if profileDb_ != nil {
return nil
}
var err error
profileDb_, err = sql.Open("sqlite3", profileFile())
if err != nil {
return errors.New(fmt.Sprintf("Profile file could not be opened: %s: %s", err, profileFile()))
}
_, err = profileDb_.Exec("CREATE TABLE IF NOT EXISTS history (id INTEGER NOT NULL PRIMARY KEY, source TEXT, destination TEXT, timestamp INTEGER)")
if err != nil {
return errors.New(fmt.Sprintf("History table could not be created: %s", err))
}
profileDb_.Exec("CREATE INDEX id_index ON history (id)")
profileDb_.Exec("CREATE INDEX destination_index ON history (destination)")
profileDb_.Exec("CREATE INDEX timestamp_index ON history (timestamp)")
config_ = sqlkv.New(profileDb_, "config")
return nil
}
func profileClose() {
config_ = nil
if profileDb_ != nil {
profileDb_.Close()
profileDb_ = nil
}
profileFolder_ = ""
}
// Used only for debugging
func profileDelete() {
profileFolder := profileFolder_ // profileFolder_ is going to be cleared in profileClose()
profileClose()
os.RemoveAll(profileFolder)
}
func profileFolder() string {
if profileFolder_ != "" {
return profileFolder_
}
if homeDir_ == "" {
// By default, use $HOME as it seems to be different from HomeDir in some
// systems. In particular it's necessary to pass Homebrew's tests.
homeDir_ = os.Getenv("HOME")
if homeDir_ == "" {
u, err := user.Current()
if err != nil {
panic(err)
}
homeDir_ = u.HomeDir
}
}
output := filepath.Join(homeDir_, ".config", APPNAME)
err := os.MkdirAll(output, PROFILE_PERM)
if err != nil {
panic(err)
}
profileFolder_ = output
return profileFolder_
}
func profileFile() string {
return filepath.Join(profileFolder(), "profile.sqlite")
}
func handleConfigCommand(opts *CommandLineOptions, args []string) error {
if len(args) == 0 {
kvs := config_.All()
for _, kv := range kvs {
fmt.Printf("%s = \"%s\"\n", kv.Name, kv.Value)
}
return nil
}
name := args[0]
if len(args) == 1 {
config_.Del(name)
logInfo("Config has been changed: deleted key \"%s\"", name)
return nil
}
value := args[1]
config_.SetString(name, value)
logInfo("Config has been changed: %s = \"%s\"", name, value)
return nil
}