-
Notifications
You must be signed in to change notification settings - Fork 0
/
issue.py
executable file
·419 lines (381 loc) · 16 KB
/
issue.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/usr/bin/python3
#
# Copyright (c) 2013 Lauri Hakko
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from datetime import date, datetime
from os.path import exists
from string import whitespace
import argparse
import array
import fcntl
import gzip
import json
import logging
import os
import subprocess
import tempfile
import termios
logging.basicConfig(format='%(levelname)s:%(message)s')
VERSION = '0.1.5'
def term_size():
buf = array.array('h', [0, 0])
_ = fcntl.ioctl(0, termios.TIOCGWINSZ, buf, 1)
rows, columns = buf
return rows, columns
def open_editor(content=""):
with tempfile.NamedTemporaryFile() as f:
editor = os.environ['EDITOR']
filename = f.name
f.write(bytes(content, encoding="utf-8"))
f.flush() # Make sure file has appropriate content before open
ret = subprocess.call([editor, filename])
if ret == 0:
f.seek(0)
content = str(f.read(), encoding="utf-8")
content = content.strip("\n\r")
return content
def get_status_color(status):
""" Return a unicode color string depending the status. """
status = status.lower()
if status == 'open':
return '\033[92m'
elif status == 'closed':
return '\033[91m'
elif status == 'wontfix':
return '\033[95m'
else:
return '\033[0m'
class Issues(object):
def __init__(self):
self.issues = []
self.filename = ""
if exists("ISSUES"):
self.filename = "ISSUES"
self.gzip_file = False
elif exists("ISSUES.gz"):
self.filename = "ISSUES.gz"
self.gzip_file = True
def load_issues(self):
if self.filename == "ISSUES":
generic_open = open
elif self.filename == "ISSUES.gz":
generic_open = gzip.open
else:
logging.warning("ISSUES file does not exist.")
print("You can create one with\n\n $ issue init\n")
exit(1)
try:
with generic_open(self.filename, "rt") as f:
content = f.read()
if content.strip() != "":
self.issues = json.loads(content)
except ValueError:
logging.error("Error while loading json. "
+ "Maybe ISSUES file is corrupted.")
except OSError as err:
logging.error(os.strerror(err.errno))
exit(1)
except PermissionError:
logging.error("No permissions to read ISSUES file")
exit(1)
def add_issue(self, description, tags):
if not description:
description = open_editor()
if description.strip() == "":
print("Empty issue description. Aborting.")
exit(1)
today = date.today().isoformat()
largest = 0
if len(self.issues) > 0:
largest = max([issue["number"] for issue in self.issues])
number = largest + 1
issue = {"status": "open", "number": number, "tag": tags,
"date": today, "description": description}
self.issues.append(issue)
self.print_short([issue])
logging.info("Added a new issue:\n{}".format(issue))
self.save_issues()
def search_issues(self, status="open", tags="", description=""):
issues = self.issues[:]
if status and status != "all":
issues = [issue for issue in issues if issue["status"] == status]
if tags:
for tag in tags.split(","):
issues = [issue for issue in issues
if issue["tag"].lstrip().find(tag) != -1]
if description:
description = description.lower()
issues = [issue for issue in issues
if issue["description"].find(description)]
if issues:
self.print_short(issues)
else:
print("Nothing found.")
def edit_issue(self, number, message="", tags="", status="", edit=False):
if message and edit:
logging.warning("Cannot use --message and --edit at the same time.")
exit(1)
for issue in self.issues:
if issue["number"] == number:
if tags:
if tags[0] == '+':
for tag in tags[1:].split(","):
if len(tag) > 20:
tag = tag[:20]
message = ("Tag length is over 20 characters. "
+ "Shortening it to 20 characters.")
logging.warning(message)
issue["tag"] += "," + tag
elif tags[0] == '-':
removes = tags[1:].split(",")
current_tags = issue["tag"].split(",")
issue["tag"] = ""
for tag in current_tags:
if tag not in removes:
issue["tag"] += "," + tag
elif tags[0] == '=':
for tag in tags[1:].split(","):
issue["tag"] = ""
if len(tag) > 20:
tag = tag[:20]
message = ("Tag length is over 20 characters. "
+ "Shortening it to 20 characters.")
logging.warning(message)
issue["tag"] += "," + tag
issue["tag"] = issue["tag"].lstrip(",")
if message or edit:
if issue["status"] == 'closed':
logging.warning("Editing closed issue is disallowed.")
elif message:
issue["description"] = message
elif edit:
current_desc = self.get_issue_content(number)
new_desc = open_editor(current_desc)
if new_desc.strip("\n\r" + whitespace) == "":
print("Got empty issue description. "
+ "Issue left unchanged.")
exit(0)
else:
issue["description"] = new_desc
if status:
issue["status"] = status
self.print_short((issue,))
break
self.save_issues()
def init(self, force, compress):
if self.filename:
if force:
now = datetime.today().strftime("%Y-%m-%d_%H%M%S")
newfile = self.filename + "_" + now
if exists(newfile):
logging.error("Could not rename old file. Filename "
+ "already exists.")
exit(1)
else:
try:
os.rename(filename, newfile)
logging.info("Moved old issue file to {}"
.format(newfile))
except OSError:
logging.error("Could not rename file.")
if compress:
self.gzip_file = True
self.issues = []
self.save_issues()
logging.info("Created a new issue file.")
else:
logging.error("ISSUES file already exists.")
print("Use --force to make one anyway.")
else:
self.filename = "ISSUES"
if compress:
self.gzip_file = True
else:
self.gzip_file = False
logging.info("Created a new issue file.")
self.save_issues()
def get_issue_content(self, number=-1):
content = ""
if number != -1:
for issue in self.issues:
if issue["number"] == number:
content = issue["description"]
break
return content
def print_short(self, issuelist):
rows, max_width = term_size()
print('\033[2J\033[{}A'.format(rows), end='')
padding = 3
# Use the column title length as min length
lens = {
"status": len('status'),
"number": len('number'),
"tag": len('tag'),
"date": len('date'),
"description": len('description')
}
# Use custom length if a column value is longer than the column title
# length
if len(issuelist) > 0:
for issue in issuelist:
for col in issue:
if len(str(issue[col])) > lens[col]:
lens[col] = len(str(issue[col]))
for column in lens:
lens[column] += padding
else:
logging.warning("Issue list print requested but got nothing.")
exit(1)
# All logic is done. Now we juste have to print the informations.
# Print a bold column header
print('\033[1m', end='')
print('status'.ljust(lens['status']), end='')
print('number'.ljust(lens['number']), end='')
print('tag'.ljust(lens['tag']), end='')
print('date'.ljust(lens['date']), end='')
print('description', end='')
print('\033[0m', end='')
print()
for issue in issuelist:
# Only use the first line of the description
# and strech if too long.
desc_width = (max_width - (sum(lens.values())
- lens["description"]) - 12)
d = issue['description'][:]
d = d.splitlines()[0]
if len(d) >= desc_width:
d = d[:desc_width - 3]
d += '...'
print(get_status_color(issue['status']), end='')
print(issue["status"].ljust(lens["status"]), end='')
print(get_status_color(''), end='')
print(str(issue["number"]).ljust(lens["number"]), end='')
print(issue["tag"].ljust(lens["tag"]), end='')
print(issue["date"].ljust(lens["date"]), end='')
print(d, end='')
print()
def print_long(self, number):
rows, max_width = term_size()
print('\033[2J\033[{}A'.format(rows), end='')
for issue in self.issues:
if issue["number"] == number:
print("\033[1mStatus:\033[0m\t", end='')
print(get_status_color(issue['status']), end='')
print(issue['status'], end='')
print(get_status_color(''))
print("\033[1mNumber:\033[0m\t" + str(number))
print("\033[1mTag:\033[0m\t" + issue["tag"])
print("\033[1mDate:\033[0m\t" + issue["date"])
print("\n" + issue["description"])
break
def remove_issue(self, number):
print("Warning! You are about to remove following issue. "
+ "This cannot be undone!")
self.print_long(number)
print("To confirm, please retype the issue number: ", end="")
other = input()
if other.isdigit():
other = int(other)
else:
logging.error("Not a number. Aborting.")
exit(1)
if number == int(other):
self.issues = [issue for issue in self.issues
if issue["number"] != number]
self.save_issues()
logging.info("Removed an issue.")
else:
logging.error("Wrong issue number. Aborting.")
def save_issues(self):
if not self.gzip_file:
generic_open = open
else:
generic_open = gzip.open
try:
with generic_open(self.filename, mode="wt") as f:
json.dump(self.issues, f, ensure_ascii=False, indent=4)
except PermissionError:
logging.error("No permission to write to the file. "
+ "Changes were not saved.")
logging.info("Succesfully saved issues")
def parse_arguments():
parser = argparse.ArgumentParser(description="Simple issue handler")
subparsers = parser.add_subparsers(title="subcommands", dest="subparser")
add_parser = subparsers.add_parser("add", help="Add new issue")
add_parser.add_argument("-d", "--description", metavar="TEXT",
help="Description of the issue. if omitted, "
+ "the $EDITOR will be invoked.")
add_parser.add_argument("-t", "--tags", default="bug",
help="Specify tags for issue, default: %(default)s")
edit_parser = subparsers.add_parser("edit", help="Edit individual issue")
edit_parser.add_argument("number", type=int, help="Issue number to edit")
edit_parser.add_argument("-m", "--message", default="",
help="New message to replace the old.")
edit_parser.add_argument("-t", "--tags", default="",
help="Change issue tags")
edit_parser.add_argument("-s", "--status", default="",
help="Change issue status")
edit_parser.add_argument("-e", "--edit", action="store_true",
help="Edit issue in editor."),
close_parser = subparsers.add_parser("close", help="Close an issue")
close_parser.add_argument("number", type=int, help="Issue number to close")
search_parser = subparsers.add_parser("search", aliases=["se"],
help="Search issues")
search_parser.add_argument("-s", "--status", default="open",
help="Filter issues by status. 'all' will list all issues."
+ " default: %(default)s")
search_parser.add_argument("-t", "--tags",
help="Filter issues by tags.")
search_parser.add_argument("-d", "--description", metavar="TEXT",
help="Filter issues by description.")
show_parser = subparsers.add_parser("show",
help="Show more information on individual issue")
show_parser.add_argument("number", type=int, help="Issue number to show")
init_parser = subparsers.add_parser("init", help="Initialize issue file")
init_parser.add_argument("-f", "--force", action="store_true",
help="Make issue files regardless if one exists already.")
init_parser.add_argument("-g", "--gzip", action="store_true",
help="Make gzip compressed issue file.")
remove_parser = subparsers.add_parser("remove", aliases=["rm"],
help="Remove an issue")
remove_parser.add_argument("number", type=int,
help="Number of the issue you want to remove")
return parser.parse_args()
def main():
issues = Issues()
args = parse_arguments()
# if init is called, do that and exit
if args.subparser == "init":
issues.init(args.force, args.gzip)
exit(0)
# otherwise load issues from file and continue
issues.load_issues()
if args.subparser == "add":
issues.add_issue(args.description, args.tags)
elif args.subparser == "show":
issues.print_long(args.number)
elif args.subparser == "search" or args.subparser == "se":
issues.search_issues(status=args.status, tags=args.tags,
description=args.description)
elif args.subparser == "close":
issues.edit_issue(args.number, status="closed")
elif args.subparser == "edit":
issues.edit_issue(args.number, message=args.message, tags=args.tags,
status=args.status, edit=args.edit)
elif args.subparser == "remove" or args.subparser == "rm":
issues.remove_issue(args.number)
else:
issues.search_issues()
if __name__=='__main__':
main()