-
Notifications
You must be signed in to change notification settings - Fork 556
/
root.go
118 lines (99 loc) · 2.57 KB
/
root.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
package cmd
import (
"fmt"
"os"
fp "path/filepath"
"github.com/go-shiori/shiori/internal/database"
apppaths "github.com/muesli/go-app-paths"
"github.com/spf13/cobra"
)
var (
db database.DB
dataDir string
developmentMode bool
)
// ShioriCmd returns the root command for shiori
func ShioriCmd() *cobra.Command {
rootCmd := &cobra.Command{
Use: "shiori",
Short: "Simple command-line bookmark manager built with Go",
}
rootCmd.PersistentPreRun = preRunRootHandler
rootCmd.PersistentFlags().Bool("portable", false, "run shiori in portable mode")
rootCmd.AddCommand(
addCmd(),
printCmd(),
updateCmd(),
deleteCmd(),
openCmd(),
importCmd(),
exportCmd(),
pocketCmd(),
serveCmd(),
checkCmd(),
)
return rootCmd
}
func preRunRootHandler(cmd *cobra.Command, args []string) {
// Read flag
var err error
portableMode, _ := cmd.Flags().GetBool("portable")
// Get and create data dir
dataDir, err = getDataDir(portableMode)
if err != nil {
cError.Printf("Failed to get data dir: %v\n", err)
os.Exit(1)
}
err = os.MkdirAll(dataDir, os.ModePerm)
if err != nil {
cError.Printf("Failed to create data dir: %v\n", err)
os.Exit(1)
}
// Open database
db, err = openDatabase()
if err != nil {
cError.Printf("Failed to open database: %v\n", err)
os.Exit(1)
}
}
func getDataDir(portableMode bool) (string, error) {
// If in portable mode, uses directory of executable
if portableMode {
exePath, err := os.Executable()
if err != nil {
return "", err
}
exeDir := fp.Dir(exePath)
return fp.Join(exeDir, "shiori-data"), nil
}
if developmentMode {
return "dev-data", nil
}
// Try to look at environment variables
dataDir, found := os.LookupEnv("SHIORI_DIR")
if found {
return dataDir, nil
}
// Try to use platform specific app path
userScope := apppaths.NewScope(apppaths.User, "shiori", "shiori")
dataDir, err := userScope.DataDir()
if err == nil {
return dataDir, nil
}
// When all fail, use current working directory
return ".", nil
}
func openDatabase() (database.DB, error) {
// Check if it uses MySQL
if dbms, _ := os.LookupEnv("SHIORI_DBMS"); dbms == "mysql" {
user, _ := os.LookupEnv("SHIORI_MYSQL_USER")
password, _ := os.LookupEnv("SHIORI_MYSQL_PASS")
dbName, _ := os.LookupEnv("SHIORI_MYSQL_NAME")
dbAddress, _ := os.LookupEnv("SHIORI_MYSQL_ADDRESS")
connString := fmt.Sprintf("%s:%s@%s/%s", user, password, dbAddress, dbName)
return database.OpenMySQLDatabase(connString)
}
// If not, just uses SQLite
dbPath := fp.Join(dataDir, "shiori.db")
return database.OpenSQLiteDatabase(dbPath)
}