1 | #!/usr/bin/env python
|
---|
2 |
|
---|
3 | import json
|
---|
4 | import sys
|
---|
5 | from argparse import ArgumentParser
|
---|
6 | from os.path import expanduser, isfile, isdir
|
---|
7 |
|
---|
8 |
|
---|
9 | def args_cmd():
|
---|
10 | """Parse the command line arguments via argparse"""
|
---|
11 | parser = ArgumentParser(description='Convert tool from txt to json format')
|
---|
12 | parser.add_argument(
|
---|
13 | '--input', '-i', default=expanduser('~/.workstamps.txt'),
|
---|
14 | help='Input filename (default ~/.workstamps.txt')
|
---|
15 | parser.add_argument(
|
---|
16 | '--output', '-o', default=expanduser('~/.workstamps.json'),
|
---|
17 | help='Input filename (default: ~/.workstamps.json)')
|
---|
18 | return parser.parse_args()
|
---|
19 |
|
---|
20 |
|
---|
21 | def itemify(line):
|
---|
22 | """Split a line, returning date and the rest of data"""
|
---|
23 | line = line.strip()
|
---|
24 | end_time = line[:16]
|
---|
25 | info = line[17:]
|
---|
26 | return(line[:16], line[17:])
|
---|
27 |
|
---|
28 |
|
---|
29 | if __name__ == '__main__':
|
---|
30 | args = args_cmd()
|
---|
31 |
|
---|
32 | stamps = []
|
---|
33 |
|
---|
34 | with open(args.input, 'r') as infile:
|
---|
35 |
|
---|
36 | for line in infile:
|
---|
37 | time, info = itemify(line)
|
---|
38 |
|
---|
39 | if info == 'start':
|
---|
40 | customer = None
|
---|
41 | action = None
|
---|
42 | start_time = time
|
---|
43 | end_time = None
|
---|
44 |
|
---|
45 | elif time == 'restarttotals':
|
---|
46 | continue
|
---|
47 |
|
---|
48 | else:
|
---|
49 | info_items = info.split(' ', 1)
|
---|
50 | customer = info_items[0]
|
---|
51 | action = ''
|
---|
52 | if len(info_items) > 1:
|
---|
53 | action = info_items[1].lstrip('- ')
|
---|
54 | # if the previous line was not a start line, took the previous
|
---|
55 | # line end time as start time
|
---|
56 | if end_time is not None:
|
---|
57 | start_time = end_time
|
---|
58 | end_time = time
|
---|
59 |
|
---|
60 | stamps.append({
|
---|
61 | 'start': start_time,
|
---|
62 | 'end': end_time,
|
---|
63 | 'customer': customer,
|
---|
64 | 'action': action,
|
---|
65 | })
|
---|
66 |
|
---|
67 | if isfile(args.output):
|
---|
68 | print('[warning] %(out)s already exist'
|
---|
69 | % {'out': args.output})
|
---|
70 | confirm = raw_input('overwrite? (y/n) ')
|
---|
71 | while confirm not in ['y','n','Y','N']:
|
---|
72 | confirm = raw_input('overwrite? (y/n) ')
|
---|
73 | if confirm in ['n', 'N']:
|
---|
74 | print('[warning] exiting without converting')
|
---|
75 | sys.exit()
|
---|
76 |
|
---|
77 | elif isdir(args.output):
|
---|
78 | print('[error] %(out)s is a directory, remove it first'
|
---|
79 | % {'out': args.output})
|
---|
80 | sys.exit(1)
|
---|
81 |
|
---|
82 | with open(args.output, 'w') as stamps_file:
|
---|
83 | json.dump(stamps, stamps_file, indent=4)
|
---|