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