Config flatlist has a new --grep parameter. Fixes #98
[mdk.git] / mdk / commands / config.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 Moodle Development Kit
6
7 Copyright (c) 2013 Frédéric Massart - FMCorz.net
8
9 This program is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 http://github.com/FMCorz/mdk
23 """
24
25 import logging
26 import re
27 from ..command import Command
28 from ..tools import launchEditor, yesOrNo
29 from ..config import ConfigObject, ConfigFileCouldNotBeLoaded
30
31
32 class ConfigCommand(Command):
33
34 _arguments = [
35 (
36 ['action'],
37 {
38 'help': 'the action to perform',
39 'metavar': 'action',
40 'sub-commands': {
41 'edit': (
42 {
43 'help': 'opens the config file in an editor'
44 },
45 []
46 ),
47 'flatlist': (
48 {
49 'help': 'flat list of the settings'
50 },
51 [
52 (
53 ['-g', '--grep'],
54 {
55 'metavar': 'string',
56 'help': 'filter results using regular expressions'
57 }
58 ),
59 ]
60 ),
61 'list': (
62 {
63 'help': 'list the settings'
64 },
65 []
66 ),
67 'show': (
68 {
69 'help': 'display one setting'
70 },
71 [
72 (
73 ['setting'],
74 {
75 'metavar': 'setting',
76 'help': 'setting to display'
77 }
78 )
79 ]
80 ),
81 'set': (
82 {
83 'help': 'set the value of a setting'
84 },
85 [
86 (
87 ['setting'],
88 {
89 'metavar': 'setting',
90 'help': 'setting to edit'
91 }
92 ),
93 (
94 ['value'],
95 {
96 'default': '',
97 'metavar': 'value',
98 'nargs': '?',
99 'help': 'value to set'
100 }
101 )
102 ]
103 )
104 }
105 }
106 )
107 ]
108 _description = 'Manage your configuration'
109
110 def dictDisplay(self, data, ident=0):
111 for name in sorted(data.keys()):
112 setting = data[name]
113 if type(setting) != dict:
114 print u'{0:<20}: {1}'.format(u' ' * ident + name, setting)
115 else:
116 print u' ' * ident + '[%s]' % name
117 self.dictDisplay(setting, ident + 2)
118
119 def flatDisplay(self, data, parent='', regex=None):
120 for name in sorted(data.keys()):
121 setting = data[name]
122 if type(setting) != dict:
123 if regex and not regex.search(parent + name):
124 continue
125 print u'%s: %s' % (parent + name, setting)
126 else:
127 self.flatDisplay(setting, parent=parent + name + u'.', regex=regex)
128
129 def run(self, args):
130 if args.action == 'list':
131 self.dictDisplay(self.C.get(), 0)
132
133 elif args.action == 'edit':
134 f = self.C.userFile
135 success = None
136
137 while True:
138 tmpfile = launchEditor(filepath=f, suffix='.json')
139 co = ConfigObject()
140 try:
141 co.loadFromFile(tmpfile)
142 except ConfigFileCouldNotBeLoaded:
143 success = False
144 logging.error('I could not load the file, you probably screwed up the JSON...')
145 if yesOrNo('Would you like to continue editing? If not the changes will be discarded.'):
146 f = tmpfile
147 continue
148 else:
149 break
150 else:
151 success = True
152 break
153
154 if success:
155 with open(tmpfile, 'r') as new:
156 with open(self.C.userFile, 'w') as current:
157 current.write(new.read())
158
159 elif args.action == 'flatlist':
160 regex = None
161 if args.grep:
162 regex = re.compile(args.grep, re.I)
163 self.flatDisplay(self.C.get(), regex=regex)
164
165 elif args.action == 'show':
166 setting = self.C.get(args.setting)
167 if setting != None:
168 if type(setting) == dict:
169 self.flatDisplay(setting, args.setting + u'.')
170 else:
171 print setting
172
173 elif args.action == 'set':
174 setting = args.setting
175 val = args.value
176 if val.startswith('b:'):
177 val = True if val[2:].lower() in ['1', 'true'] else False
178 elif val.startswith('i:'):
179 try:
180 val = int(val[2:])
181 except ValueError:
182 # Not a valid int, let's consider it a string.
183 pass
184 self.C.set(setting, val)