-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathclikan.py
333 lines (274 loc) · 10.3 KB
/
clikan.py
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
from rich import print
from rich.console import Console
from rich.table import Table
import click
from click_default_group import DefaultGroup
import yaml
import os
import sys
from textwrap import wrap
import collections
import datetime
import configparser
import importlib
VERSION = importlib.metadata.version('clikan')
class Config(object):
"""The config in this example only holds aliases."""
def __init__(self):
self.path = os.getcwd()
self.aliases = {}
def read_config(self, filename):
parser = configparser.RawConfigParser()
parser.read([filename])
try:
self.aliases.update(parser.items('aliases'))
except configparser.NoSectionError:
pass
pass_config = click.make_pass_decorator(Config, ensure=True)
class AliasedGroup(DefaultGroup):
"""This subclass of a group supports looking up aliases in a config
file and with a bit of magic.
"""
def get_command(self, ctx, cmd_name):
# Step one: bulitin commands as normal
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
# Step two: find the config object and ensure it's there. This
# will create the config object is missing.
cfg = ctx.ensure_object(Config)
# Step three: lookup an explicit command aliase in the config
if cmd_name in cfg.aliases:
actual_cmd = cfg.aliases[cmd_name]
return click.Group.get_command(self, ctx, actual_cmd)
# Alternative option: if we did not find an explicit alias we
# allow automatic abbreviation of the command. "status" for
# instance will match "st". We only allow that however if
# there is only one command.
matches = [x for x in self.list_commands(ctx)
if x.lower().startswith(cmd_name.lower())]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))
def read_config(ctx, param, value):
"""Callback that is used whenever --config is passed. We use this to
always load the correct config. This means that the config is loaded
even if the group itself never executes so our aliases stay always
available.
"""
cfg = ctx.ensure_object(Config)
if value is None:
value = os.path.join(os.path.dirname(__file__), 'aliases.ini')
cfg.read_config(value)
return value
@click.version_option(VERSION)
@click.command(cls=AliasedGroup, default='show', default_if_no_args=True)
def clikan():
"""clikan: CLI personal kanban """
@clikan.command()
def configure():
"""Place default config file in CLIKAN_HOME or HOME"""
home = get_clikan_home()
data_path = os.path.join(home, ".clikan.dat")
config_path = os.path.join(home, ".clikan.yaml")
if (os.path.exists(config_path) and not
click.confirm('Config file exists. Do you want to overwrite?')):
return
with open(config_path, 'w') as outfile:
conf = {'clikan_data': data_path}
yaml.dump(conf, outfile, default_flow_style=False)
click.echo("Creating %s" % config_path)
@clikan.command()
@click.argument('tasks', nargs=-1)
def add(tasks):
"""Add a tasks in todo"""
config = read_config_yaml()
dd = read_data(config)
if ('limits' in config and 'taskname' in config['limits']):
taskname_length = config['limits']['taskname']
else:
taskname_length = 40
for task in tasks:
if len(task) > taskname_length:
click.echo('Task must be at most %s chars, Brevity counts: %s'
% (taskname_length, task))
else:
todos, inprogs, dones = split_items(config, dd)
if ('limits' in config and 'todo' in config['limits'] and
int(config['limits']['todo']) <= len(todos)):
click.echo('No new todos, limit reached already.')
else:
od = collections.OrderedDict(sorted(dd['data'].items()))
new_id = 1
if bool(od):
new_id = next(reversed(od)) + 1
entry = ['todo', task, timestamp(), timestamp()]
dd['data'].update({new_id: entry})
click.echo("Creating new task w/ id: %d -> %s"
% (new_id, task))
write_data(config, dd)
if ('repaint' in config and config['repaint']):
display()
@clikan.command()
@click.argument('ids', nargs=-1)
def delete(ids):
"""Delete task"""
config = read_config_yaml()
dd = read_data(config)
for id in ids:
try:
item = dd['data'].get(int(id))
if item is None:
click.echo('No existing task with that id: %d' % int(id))
else:
item[0] = 'deleted'
item[2] = timestamp()
dd['deleted'].update({int(id): item})
dd['data'].pop(int(id))
click.echo('Removed task %d.' % int(id))
except ValueError:
click.echo('Invalid task id')
write_data(config, dd)
if ('repaint' in config and config['repaint']):
display()
@clikan.command()
@click.argument('ids', nargs=-1)
def promote(ids):
"""Promote task"""
config = read_config_yaml()
dd = read_data(config)
todos, inprogs, dones = split_items(config, dd)
for id in ids:
try:
item = dd['data'].get(int(id))
if item is None:
click.echo('No existing task with that id: %s' % id)
elif item[0] == 'todo':
if ('limits' in config and 'wip' in config['limits'] and
int(config['limits']['wip']) <= len(inprogs)):
click.echo(
'Can not promote, in-progress limit of %s reached.'
% config['limits']['wip']
)
else:
click.echo('Promoting task %s to in-progress.' % id)
dd['data'][int(id)] = [
'inprogress',
item[1], timestamp(),
item[3]
]
elif item[0] == 'inprogress':
click.echo('Promoting task %s to done.' % id)
dd['data'][int(id)] = ['done', item[1], timestamp(), item[3]]
else:
click.echo('Can not promote %s, already done.' % id)
except ValueError:
click.echo('Invalid task id')
write_data(config, dd)
if ('repaint' in config and config['repaint']):
display()
@clikan.command()
@click.argument('id', nargs=-1)
def regress(ids):
"""Regress task"""
config = read_config_yaml()
dd = read_data(config)
for id in ids:
item = dd['data'].get(int(id))
if item is None:
click.echo('No existing task with id: %s' % id)
elif item[0] == 'done':
click.echo('Regressing task %s to in-progress.' % id)
dd['data'][int(id)] = ['inprogress', item[1], timestamp(), item[3]]
elif item[0] == 'inprogress':
click.echo('Regressing task %s to todo.' % id)
dd['data'][int(id)] = ['todo', item[1], timestamp(), item[3]]
else:
click.echo('Already in todo, can not regress %s' % id)
write_data(config, dd)
if ('repaint' in config and config['repaint']):
display()
# Use a non-Click function to allow for repaint to work.
def display():
console = Console()
"""Show tasks in clikan"""
config = read_config_yaml()
dd = read_data(config)
todos, inprogs, dones = split_items(config, dd)
if 'limits' in config and 'done' in config['limits']:
dones = dones[0:int(config['limits']['done'])]
else:
dones = dones[0:10]
todos = '\n'.join([str(x) for x in todos])
inprogs = '\n'.join([str(x) for x in inprogs])
dones = '\n'.join([str(x) for x in dones])
table = Table(show_header=True, show_footer=True)
table.add_column(
"[bold yellow]todo[/bold yellow]",
no_wrap=True,
footer="clikan"
)
table.add_column('[bold green]in-progress[/bold green]', no_wrap=True)
table.add_column(
'[bold magenta]done[/bold magenta]',
no_wrap=True,
footer="v.{}".format(VERSION)
)
table.add_row(todos, inprogs, dones)
console.print(table)
@clikan.command()
def show():
display()
def read_data(config):
"""Read the existing data from the config datasource"""
try:
with open(config["clikan_data"], 'r') as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print("Ensure %s exists, as you specified it "
"as the clikan data file." % config['clikan_data'])
print(exc)
except IOError:
click.echo("No data, initializing data file.")
write_data(config, {"data": {}, "deleted": {}})
with open(config["clikan_data"], 'r') as stream:
return yaml.safe_load(stream)
def write_data(config, data):
"""Write the data to the config datasource"""
with open(config["clikan_data"], 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
def get_clikan_home():
home = os.environ.get('CLIKAN_HOME')
if not home:
home = os.path.expanduser('~')
return home
def read_config_yaml():
"""Read the app config from ~/.clikan.yaml"""
try:
home = get_clikan_home()
with open(home + "/.clikan.yaml", 'r') as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError:
print("Ensure %s/.clikan.yaml is valid, expected YAML." % home)
sys.exit()
except IOError:
print("Ensure %s/.clikan.yaml exists and is valid." % home)
sys.exit()
def split_items(config, dd):
todos = []
inprogs = []
dones = []
for key, value in dd['data'].items():
if value[0] == 'todo':
todos.append("[%d] %s" % (key, value[1]))
elif value[0] == 'inprogress':
inprogs.append("[%d] %s" % (key, value[1]))
else:
dones.insert(0, "[%d] %s" % (key, value[1]))
return todos, inprogs, dones
def timestamp():
return '{:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now())