1#!/usr/bin/env python3
2
3import os, re, subprocess
4
5
6def grep(filepath, regex):
7    regObj = re.compile(regex)
8    res = { "file": filepath, "matches": {} }
9    try:
10        with open(filepath, "rt") as f:
11            line_number = 1
12            for line in f:
13                match = regObj.match(line)
14                if match:
15                    res["matches"][line_number] = match
16                line_number = line_number + 1
17    except Exception as e:
18        print("WARNING: Can't open {}: {}".format(filepath, e))
19
20    # Return filename and line matches if there are
21    return res if res["matches"] else {}
22
23
24def recursive_find_file(path, filename_regex, action = None):
25    filename_reg_obj = re.compile(filename_regex)
26    res = []
27    for root, dirs, fnames in os.walk(path):
28        for fname in fnames:
29            if filename_reg_obj.match(fname):
30                if action is None:
31                    res.append(os.path.join(root, fname))
32                else:
33                    out = action(os.path.join(root, fname))
34                    if out:
35                        res.append(out)
36
37    return res
38
39
40def invoke_command(command, needs_output, exeption_type = Exception,
41                   exeption_msg = ""):
42    try:
43        pipe_stdout = subprocess.PIPE if (needs_output == True) else None
44        output = subprocess.run(command, shell=True, check=True,
45                                stdout=pipe_stdout, stderr=subprocess.STDOUT,
46                                encoding='utf8')
47    except (subprocess.CalledProcessError, subprocess.SubprocessError) as e:
48        if needs_output == True:
49            exeption_msg = exeption_msg.format(e.cmd, output.stdout)
50        else:
51            exeption_msg = exeption_msg.format(e.cmd)
52        excp = exeption_type(exeption_msg)
53        excp.errorcode = e.returncode if hasattr(e, 'returncode') else 1
54        raise excp
55
56    return output.stdout
57