b7fd8ef08a5463b9c0ea3b92947981eb2aea0225
[tests.git] / system / utils.py
1 # Thierry Parmentelat <thierry.parmentelat@inria.fr>
2 # Copyright (C) 2010 INRIA 
3 #
4 import time, os, re, glob, sys
5 from pprint import PrettyPrinter
6
7 options={}
8
9 def init_options(options_arg):
10     global options
11     options = options_arg
12
13 # how could this accept a list again ?
14 def header(message):
15     now = time.strftime("%H:%M:%S", time.localtime())
16     print("*", now, '--', message)
17
18 def pprint(message, spec, depth=2):
19     now = time.strftime("%H:%M:%S", time.localtime())
20     print(">", now, "--", message)
21     PrettyPrinter(indent=8, depth=depth).pprint(spec)
22
23
24
25 def system(command, background=False, silent=False, dry_run=None):
26     dry_run = dry_run if dry_run is not None else getattr(options, 'dry_run', False)
27     if dry_run:
28         print('dry_run:', command)
29         return 0
30     
31     if silent :    
32         if command.find(';') >= 0:
33             command = "({}) 2> /dev/null".format(command)
34         else: command += " 2> /dev/null"
35     if background:
36         command += " &"
37     if silent:
38         print('.', end=' ')
39         sys.stdout.flush()
40     else:
41         now = time.strftime("%H:%M:%S", time.localtime())
42         # don't show in summary
43         print("->", now, '--', end=' ')
44         sys.stdout.flush()
45     if not silent:
46         command = "set -x; " + command
47     return os.system(command)
48
49 ### WARNING : this ALWAYS does its job, even in dry_run mode
50 def output_of (command):
51     import subprocess
52     (code, string) = subprocess.getstatusoutput(command)
53     return (code, string)
54
55
56 # convenience: translating shell-like pattern into regexp
57 def match (string, pattern):
58     # tmp - there's probably much simpler
59     # rewrite * into .*, ? into .
60     pattern = pattern.replace("*",".*")
61     pattern = pattern.replace("?",".")
62     return re.compile(pattern).match(string)
63     
64 def locate_hooks_scripts (message, path, extensions):
65     print(message, 'searching', path, 'for extensions', extensions)
66     scripts = []
67     for ext in extensions:
68         # skip helper programs
69         scripts += glob.glob (path+'/[a-zA-Z]*.' + ext)
70     return scripts
71     
72 # quick & dirty - should probably use the parseroption object instead
73 # and move to TestMain as well
74 exclude_options_keys = [ 'ensure_value' , 'read_file', 'read_module' ]
75 def show_options (message, options):
76     now = time.strftime("%H:%M:%S", time.localtime())
77     print(">", now, "--", message)
78     for k in dir(options):
79         if k.find("_") == 0:
80             continue
81         if k in exclude_options_keys:
82             continue
83         print("    ", k, ":", getattr(options, k))
84
85
86