aboutsummaryrefslogtreecommitdiff
path: root/utils/query-jobs/query-jobs
blob: d0b797155c049978c1ede16d5e4f3fd2a4d7bcab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
import sys
import glob
import re
import optparse

from lxml import etree


JENKINS_HOME = "/var/lib/jenkins/"

def get_xpath(el):
    path = []
    while el is not None:
        path.insert(0, el.tag)
        el = el.getparent()
    return "/" + "/".join(path)

def match_job_name(job_name):
    "Check if job name matches filters which may be specified on command line."
    if not options.filter_jobname:
        return True
    neg = False
    r = options.filter_jobname
    if r[0] == "-":
        neg = True
        r = r[1:]
    return bool(re.search(r, job_name)) ^ neg

def process(query):
    for fname in glob.glob(options.home + "jobs/*/config.xml"):
        job_name = fname.split('/')[-2]
        if not match_job_name(job_name):
            continue

        doc = etree.parse(fname)
        results = doc.getroot().xpath(query)
        if options.filter and not results:
            continue
        if options.filter_not and results:
            continue

        if options.verbose:
            print "===== %s =====" % (fname if options.show_file else job_name)
        else:
            print fname if options.show_file else job_name
        if options.verbose:
            first = True
            for el in results:
                if not first:
                    print "-" * 20
                print "Element XPath: %s" % get_xpath(el)
                print etree.tostring(el)
                first = False

optparser = optparse.OptionParser(usage="%prog")
optparser.add_option("-v", "--verbose", action="store_true", help="Verbose")
optparser.add_option("--show-file", action="store_true", help="Show job config path (default is job name)")
optparser.add_option("--home", default=JENKINS_HOME, help="Jenkins home dir (%default)")
optparser.add_option("--filter-jobname", metavar="REGEX", help="Process only jobs matching regex pattern (prefix with '-' for not matching)")
optparser.add_option("--filter", action="store_true", help="Show jobs matching query")
optparser.add_option("--filter-not", action="store_true", help="Show jobs not matching query")
options, args = optparser.parse_args(sys.argv[1:])
if len(args) != 1:
    optparser.error("Wrong number of arguments")

process(args[0])