source: stamper/bin/stamp2json@ 17:323bb4ed1810

Last change on this file since 17:323bb4ed1810 was 17:323bb4ed1810, checked in by Borja Lopez <borja@…>, 10 years ago

Prevent default overwrite of the destination file on conversion.
Now the script asks you for confirmation before overwriting the
destination if it is a file, exists with an error message & code
if it is a directory.

  • Property exe set to *
File size: 2.2 KB
Line 
1#!/usr/bin/env python
2
3import json
4import sys
5from argparse import ArgumentParser
6from os.path import expanduser, isfile, isdir
7
8
9def 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
21def 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
29if __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 end_time = time
55
56 stamps.append({
57 'start': start_time,
58 'end': end_time,
59 'customer': customer,
60 'action': action,
61 })
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
78 with open(args.output, 'w') as stamps_file:
79 json.dump(stamps, stamps_file, indent=4)
Note: See TracBrowser for help on using the repository browser.