1#!python
2#
3# Copyright 2014, NICTA
4#
5# This software may be distributed and modified according to the terms of
6# the BSD 2-Clause license. Note that NO WARRANTY is provided.
7# See "LICENSE_BSD2.txt" for details.
8#
9# @TAG(NICTA_BSD)
10#
11
12import sys, re
13
14def strip_comments(s):
15  s2 = ''
16  d = 0
17  quote = False
18  i, l = 0, len(s)
19  while i < l:
20    if quote == False and s[i:i+2] == '(*':
21      d += 1
22      i += 2
23    elif quote == False and s[i:i+2] == '*)' and d > 0:
24      d -= 1
25      i += 2
26    else:
27      if d == 0:
28        s2 += s[i]
29        if quote == s[i]:
30          quote = False
31        elif s[i] in ['"', "'"]:
32          quote = s[i]
33      i += 1
34  return s2
35
36def unquote(s):
37  if s[:1] == '"' and s[-1:] == '"':
38    return s[1:-1]
39  return s
40
41def get(dir):
42  sessions = []
43  try:
44    root = strip_comments(''.join(open(dir + '/ROOT').readlines()))
45    sessions += [unquote(s) for s in re.findall('session\s+("[^"]*"|\S+)', root)]
46  except IOError:
47    pass
48  try:
49    roots = [l.strip() for l in open(dir + '/ROOTS').readlines() if l.strip()[:1] != '#']
50    for dir2 in roots:
51      sessions += get(dir + '/' + dir2)
52  except IOError:
53    pass
54  return sessions
55
56if '-h' in sys.argv or '--help' in sys.argv:
57  print('Usage: %s DIRS...' % sys.argv[0])
58  print('Print Isabelle session names defined in DIRS.')
59else:
60  sessions = []
61  for dir in sys.argv[1:]:
62    sessions += get(dir)
63  print('\n'.join(sessions))
64