-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathconfig.py
More file actions
68 lines (50 loc) · 2.03 KB
/
config.py
File metadata and controls
68 lines (50 loc) · 2.03 KB
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
from __future__ import annotations
import errno
import os
import platform
import shutil
from os.path import dirname, exists, expanduser
from configobj import ConfigObj
def config_location() -> str:
if "XDG_CONFIG_HOME" in os.environ:
return "%s/litecli/" % expanduser(os.environ["XDG_CONFIG_HOME"])
elif platform.system() == "Windows":
userprofile = os.getenv("USERPROFILE", "")
return userprofile + "\\AppData\\Local\\dbcli\\litecli\\"
else:
return expanduser("~/.config/litecli/")
def load_config(usr_cfg: str, def_cfg: str | None = None) -> ConfigObj:
cfg = ConfigObj()
if def_cfg:
cfg.merge(ConfigObj(def_cfg, interpolation=False))
cfg.merge(ConfigObj(expanduser(usr_cfg), interpolation=False, encoding="utf-8"))
cfg.filename = expanduser(usr_cfg)
return cfg
def ensure_dir_exists(path: str) -> None:
parent_dir = expanduser(dirname(path))
try:
os.makedirs(parent_dir)
except OSError as exc:
# ignore existing destination (py2 has no exist_ok arg to makedirs)
if exc.errno != errno.EEXIST:
raise
def write_default_config(source: str, destination: str, overwrite: bool = False) -> None:
destination = expanduser(destination)
if not overwrite and exists(destination):
return
ensure_dir_exists(destination)
shutil.copyfile(source, destination)
def upgrade_config(config: str, def_config: str) -> None:
cfg = load_config(config, def_config)
cfg.write()
def get_config(liteclirc_file: str | None = None) -> ConfigObj:
from litecli import __file__ as package_root
package_root = os.path.dirname(str(package_root))
liteclirc_file = liteclirc_file or f"{config_location()}config"
default_config = os.path.join(package_root, "liteclirc")
try:
write_default_config(default_config, liteclirc_file)
except OSError:
# If we can't write to the config file, just use the default config
return load_config(default_config)
return load_config(liteclirc_file, default_config)