tools: adding error and warning calls
[treecutter.git] / treecutter / tools.py
1 #!/usr/bin/python
2 from __future__ import print_function
3 import os
4 import subprocess
5 import errno
6 import sys
7
8 def mkdir_p(path):
9     try:
10         os.makedirs(path)
11     except OSError as exc: # Python >2.5
12         if exc.errno == errno.EEXIST:
13             pass
14         else: raise
15
16 def publish(src,target):
17     cmd = ["rsync","-a","--delete",src,target]
18     retcode = subprocess.call(cmd)
19     if retcode:
20         error('%s : retruncode %s' % (' '.join(cmd),str(retcode)))
21
22 def ssh_cmd(target, command):
23     t = target.split(":")
24     c = command.split()
25     if len(t)==1:
26         cmd = [c[0],c[1],t[0]]
27     else:
28         cmd = ["ssh",t[0],c[0],c[1],t[1]]
29     retcode = subprocess.call(cmd)
30     if retcode:
31         error('%s : retruncode %s' % (' '.join(cmd),str(retcode)))
32
33 def sizeof_fmt(num, suffix='B'):
34     for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
35         if abs(num) < 1024.0:
36             return "%3.1f%s%s" % (num, unit, suffix)
37         num /= 1024.0
38     return "%.1f%s%s" % (num, 'Yi', suffix)
39
40 def get_folder_size(folder):
41     total_size = os.path.getsize(folder)
42     for item in os.listdir(folder):
43         itempath = os.path.join(folder, item)
44         if os.path.isfile(itempath):
45             total_size += os.path.getsize(itempath)
46         elif os.path.isdir(itempath):
47             total_size += get_folder_size(itempath)
48     return total_size
49
50 def warning(*objs):
51     print("WARNING: ", *objs, file=sys.stderr)
52
53 def error(*objs):
54     print("ERROR: ", *objs, file=sys.stderr)