Debian Codegraph @

src/tools/pgflex

raw
1 #!/usr/bin/env python3
2
3 #
4 # Wrapper around flex that:
5 # - ensures lex.backup is created in a private directory
6 # - can error out if lex.backup is created (--no-backup)
7 # - works around concurrency issues with win_flex.exe:
8 # https://github.com/lexxmark/winflexbison/issues/86
9
10 import argparse
11 import os
12 import subprocess
13 import sys
14 from os.path import abspath
15
16 parser = argparse.ArgumentParser()
17
18 parser.add_argument('--flex', type=abspath, required=True)
19 parser.add_argument('--perl', type=abspath, required=True)
20 parser.add_argument('--builddir', type=abspath, required=True)
21 parser.add_argument('--srcdir', type=abspath, required=True)
22 parser.add_argument('--privatedir', type=abspath, required=True,
23 help='private directory for target')
24
25 parser.add_argument('-o', dest='output_file', type=abspath, required=True,
26 help='output file')
27 parser.add_argument('-i', dest='input_file', type=abspath, help='input file')
28
29
30 parser.add_argument('--no-backup', action='store_true',
31 help='whether no_backup is enabled or not')
32
33 parser.add_argument('flex_flags', nargs='*', help='flags passed on to flex')
34
35 args = parser.parse_args()
36
37 # Since 'lex.backup' is always named that and ninja uses the top level build
38 # directory as current directory for all commands, change directory to
39 # temporary directory to avoid conflicts between concurrent flex
40 # invocations. Only unreleased versions of flex have an argument to change
41 # lex.filename to be named differently.
42 if not os.path.isdir(args.privatedir):
43 os.mkdir(args.privatedir)
44 os.chdir(args.privatedir)
45
46 # win_flex.exe generates names in a racy way, sometimes leading to random
47 # "error deleting file" failures and sometimes to intermingled file
48 # contents. Set FLEX_TMP_DIR to the target private directory to avoid
49 # that. That environment variable isn't consulted on other platforms, so we
50 # don't even need to make this conditional.
51 env = {'FLEX_TMP_DIR': args.privatedir}
52
53 # build flex invocation
54 command = [args.flex, '-o', args.output_file]
55 if args.no_backup:
56 command += ['-b']
57 command += args.flex_flags
58 command += [args.input_file]
59
60 # create .c file from .l file
61 sp = subprocess.run(command, env=env)
62 if sp.returncode != 0:
63 sys.exit(sp.returncode)
64
65 # check lex.backup
66 if args.no_backup:
67 with open('lex.backup') as lex:
68 if len(lex.readlines()) != 1:
69 sys.exit('Scanner requires backup; see lex.backup.')
70 os.remove('lex.backup')
71
72 sys.exit(0)