[11] | 1 | #!/usr/bin/env python
|
---|
| 2 |
|
---|
| 3 | import json
|
---|
[17] | 4 | import sys
|
---|
[11] | 5 | from argparse import ArgumentParser
|
---|
[17] | 6 | from os.path import expanduser, isfile, isdir
|
---|
[11] | 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:
|
---|
[16] | 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('- ')
|
---|
[11] | 54 | end_time = time
|
---|
| 55 |
|
---|
| 56 | stamps.append({
|
---|
| 57 | 'start': start_time,
|
---|
| 58 | 'end': end_time,
|
---|
| 59 | 'customer': customer,
|
---|
| 60 | 'action': action,
|
---|
| 61 | })
|
---|
[17] | 62 |
|
---|
| 63 | if isfile(args.output):
|
---|
| 64 | print('[warning] %(out)s already exist'
|
---|
| 65 | % {'out': args.output})
|
---|
| 66 | confirm = raw_input('overwrite? (y/n) ')
|
---|
| 67 | while confirm not in ['y','n','Y','N']:
|
---|
| 68 | confirm = raw_input('overwrite? (y/n) ')
|
---|
| 69 | if confirm in ['n', 'N']:
|
---|
| 70 | print('[warning] exiting without converting')
|
---|
| 71 | sys.exit()
|
---|
| 72 |
|
---|
| 73 | elif isdir(args.output):
|
---|
| 74 | print('[error] %(out)s is a directory, remove it first'
|
---|
| 75 | % {'out': args.output})
|
---|
| 76 | sys.exit(1)
|
---|
| 77 |
|
---|
[11] | 78 | with open(args.output, 'w') as stamps_file:
|
---|
| 79 | json.dump(stamps, stamps_file, indent=4)
|
---|