Skip to content

Commit af6618c

Browse files
committed
improve config migration
1 parent e90ffd1 commit af6618c

1 file changed

Lines changed: 34 additions & 10 deletions

File tree

pythonbits/config.py

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
CONFIG_NAME = appname.lower() + '.cfg'
1313
CONFIG_DIR = appdirs.user_config_dir(appname.lower())
1414
CONFIG_PATH = path.join(CONFIG_DIR, CONFIG_NAME)
15+
CONFIG_VERSION = 1
1516

1617
if not path.exists(CONFIG_DIR):
1718
makedirs(CONFIG_DIR, 0o700)
@@ -71,20 +72,43 @@ def get(self, section, option, default='dontguessthis'):
7172
return value
7273

7374

74-
def migrate_config(config):
75-
if config.get('Imgur', 'client_id', None) is not None:
76-
log.notice('Migrating config.')
75+
def backup(config):
76+
from datetime import datetime
77+
t = datetime.now()
7778

78-
from datetime import datetime
79-
t = datetime.now()
80-
p = config.config_path
81-
config.config_path = p + "." + t.strftime("%Y-%m-%dT%H-%M-%S") + '.bak'
82-
config._write()
83-
log.notice('Old config backed up at {}', config.config_path)
84-
config.config_path = p
79+
p = config.config_path
80+
config.config_path = (config.config_path + "." +
81+
t.strftime("%Y-%m-%dT%H-%M-%S") + '.bak')
82+
config._write()
83+
log.notice('Old config backed up at {}', config.config_path)
84+
config.config_path = p
8585

86+
87+
def imgur_api_change(config):
88+
if config.get('Imgur', 'client_id', None) is not None:
8689
config._config.remove_section('Imgur')
8790
config._write()
91+
else:
92+
log.warning('section already removed')
93+
94+
95+
def migrate_config(config):
96+
migrations = {0: (1, imgur_api_change)}
97+
version_args = lambda v: ('General', 'version', v) # noqa: E731
98+
99+
cur = int(config.get(*version_args(0)))
100+
if cur in migrations:
101+
backup(config)
102+
while True:
103+
cur = int(config.get(*version_args(0)))
104+
try:
105+
new, mig = migrations[cur]
106+
except KeyError:
107+
break
108+
else:
109+
log.notice('Migrating config from {} to {}'.format(cur, new))
110+
mig(config)
111+
config.set(*version_args(str(new)))
88112

89113

90114
config = Config()

0 commit comments

Comments
 (0)