1from __future__ import print_function
2from __future__ import absolute_import
3
4# System modules
5import argparse
6import sys
7import multiprocessing
8import os
9import textwrap
10
11# Third-party modules
12
13# LLDB modules
14
15class ArgParseNamespace(object):
16    pass
17
18def parse_args(parser, argv):
19    """ Returns an argument object. LLDB_TEST_ARGUMENTS environment variable can
20        be used to pass additional arguments.
21    """
22    args = ArgParseNamespace()
23
24    if ('LLDB_TEST_ARGUMENTS' in os.environ):
25        print("Arguments passed through environment: '%s'" % os.environ['LLDB_TEST_ARGUMENTS'])
26        args = parser.parse_args([sys.argv[0]].__add__(os.environ['LLDB_TEST_ARGUMENTS'].split()),namespace=args)
27
28    return parser.parse_args(args=argv, namespace=args)
29
30
31def default_thread_count():
32    # Check if specified in the environment
33    num_threads_str = os.environ.get("LLDB_TEST_THREADS")
34    if num_threads_str:
35        return int(num_threads_str)
36    else:
37        return multiprocessing.cpu_count()
38
39
40def create_parser():
41    parser = argparse.ArgumentParser(description='description', prefix_chars='+-', add_help=False)
42    group = None
43
44    # Helper function for boolean options (group will point to the current group when executing X)
45    X = lambda optstr, helpstr, **kwargs: group.add_argument(optstr, help=helpstr, action='store_true', **kwargs)
46
47    group = parser.add_argument_group('Help')
48    group.add_argument('-h', '--help', dest='h', action='store_true', help="Print this help message and exit.  Add '-v' for more detailed help.")
49
50    # C and Python toolchain options
51    group = parser.add_argument_group('Toolchain options')
52    group.add_argument('-A', '--arch', metavar='arch', action='append', dest='archs', help=textwrap.dedent('''Specify the architecture(s) to test. This option can be specified more than once'''))
53    group.add_argument('-C', '--compiler', metavar='compiler', dest='compilers', action='append', help=textwrap.dedent('''Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.'''))
54    if sys.platform == 'darwin':
55        group.add_argument('--apple-sdk', metavar='apple_sdk', dest='apple_sdk', help=textwrap.dedent('''Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.'''))
56    # FIXME? This won't work for different extra flags according to each arch.
57    group.add_argument('-E', metavar='extra-flags', help=textwrap.dedent('''Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged
58                                                           suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures'''))
59
60    # Test filtering options
61    group = parser.add_argument_group('Test filtering options')
62    group.add_argument('-f', metavar='filterspec', action='append', help='Specify a filter, which consists of the test class name, a dot, followed by the test method, to only admit such test into the test suite')  # FIXME: Example?
63    X('-l', "Don't skip long running tests")
64    group.add_argument('-p', metavar='pattern', help='Specify a regexp filename pattern for inclusion in the test suite')
65    group.add_argument('-G', '--category', metavar='category', action='append', dest='categoriesList', help=textwrap.dedent('''Specify categories of test cases of interest. Can be specified more than once.'''))
66    group.add_argument('--skip-category', metavar='category', action='append', dest='skipCategories', help=textwrap.dedent('''Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.'''))
67
68    # Configuration options
69    group = parser.add_argument_group('Configuration options')
70    group.add_argument('--framework', metavar='framework-path', help='The path to LLDB.framework')
71    group.add_argument('--executable', metavar='executable-path', help='The path to the lldb executable')
72    group.add_argument('-s', metavar='name', help='Specify the name of the dir created to store the session files of tests with errored or failed status. If not specified, the test driver uses the timestamp as the session dir name')
73    group.add_argument('-y', type=int, metavar='count', help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.")
74    group.add_argument('-#', type=int, metavar='sharp', dest='sharp', help='Repeat the test suite for a specified number of times')
75    group.add_argument('--channel', metavar='channel', dest='channels', action='append', help=textwrap.dedent("Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used"))
76    group.add_argument('--log-success', dest='log_success', action='store_true', help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)")
77
78    # Configuration options
79    group = parser.add_argument_group('Remote platform options')
80    group.add_argument('--platform-name', dest='lldb_platform_name', metavar='platform-name', help='The name of a remote platform to use')
81    group.add_argument('--platform-url', dest='lldb_platform_url', metavar='platform-url', help='A LLDB platform URL to use when connecting to a remote platform to run the test suite')
82    group.add_argument('--platform-working-dir', dest='lldb_platform_working_dir', metavar='platform-working-dir', help='The directory to use on the remote platform.')
83
84    # Test-suite behaviour
85    group = parser.add_argument_group('Runtime behaviour options')
86    X('-d', 'Suspend the process after launch to wait indefinitely for a debugger to attach')
87    X('-q', "Don't print extra output from this script.")
88    X('-t', 'Turn on tracing of lldb command and other detailed test executions')
89    group.add_argument('-u', dest='unset_env_varnames', metavar='variable', action='append', help='Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble')
90    group.add_argument('--env', dest='set_env_vars', metavar='variable', action='append', help='Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES')
91    X('-v', 'Do verbose mode of unittest framework (print out each test case invocation)')
92    group.add_argument('--enable-crash-dialog', dest='disable_crash_dialog', action='store_false', help='(Windows only) When LLDB crashes, display the Windows crash dialog.')
93    group.set_defaults(disable_crash_dialog=True)
94
95    group = parser.add_argument_group('Parallel execution options')
96    group.add_argument(
97        '--inferior',
98        action='store_true',
99        help=('specify this invocation is a multiprocess inferior, '
100              'used internally'))
101    group.add_argument(
102        '--no-multiprocess',
103        action='store_true',
104        help='skip running the multiprocess test runner')
105    group.add_argument(
106        '--threads',
107        type=int,
108        dest='num_threads',
109        default=default_thread_count(),
110        help=('The number of threads/processes to use when running tests '
111              'separately, defaults to the number of CPU cores available'))
112    group.add_argument(
113        '--test-subdir',
114        action='store',
115        help='Specify a test subdirectory to use relative to the test root dir'
116    )
117    group.add_argument(
118        '--test-runner-name',
119        action='store',
120        help=('Specify a test runner strategy.  Valid values: multiprocessing,'
121              ' multiprocessing-pool, serial, threading, threading-pool')
122    )
123
124    # Test results support.
125    group = parser.add_argument_group('Test results options')
126    group.add_argument(
127        '--curses',
128        action='store_true',
129        help='Shortcut for specifying test results using the curses formatter')
130    group.add_argument(
131        '--results-file',
132        action='store',
133        help=('Specifies the file where test results will be written '
134              'according to the results-formatter class used'))
135    group.add_argument(
136        '--results-port',
137        action='store',
138        type=int,
139        help=('Specifies the localhost port to which the results '
140              'formatted output should be sent'))
141    group.add_argument(
142        '--results-formatter',
143        action='store',
144        help=('Specifies the full package/module/class name used to translate '
145              'test events into some kind of meaningful report, written to '
146              'the designated output results file-like object'))
147    group.add_argument(
148        '--results-formatter-option',
149        '-O',
150        action='append',
151        dest='results_formatter_options',
152        help=('Specify an option to pass to the formatter. '
153              'Use --results-formatter-option="--option1=val1" '
154              'syntax.  Note the "=" is critical, don\'t include whitespace.'))
155    group.add_argument(
156        '--event-add-entries',
157        action='store',
158        help=('Specify comma-separated KEY=VAL entries to add key and value '
159              'pairs to all test events generated by this test run.  VAL may '
160              'be specified as VAL:TYPE, where TYPE may be int to convert '
161              'the value to an int'))
162
163    # Re-run related arguments
164    group = parser.add_argument_group('Test Re-run Options')
165    group.add_argument(
166        '--rerun-all-issues',
167        action='store_true',
168        help=('Re-run all issues that occurred during the test run '
169              'irrespective of the test method\'s marking as flakey. '
170              'Default behavior is to apply re-runs only to flakey '
171              'tests that generate issues.'))
172    group.add_argument(
173        '--rerun-max-file-threshold',
174        action='store',
175        type=int,
176        default=50,
177        help=('Maximum number of files requiring a rerun beyond '
178              'which the rerun will not occur.  This is meant to '
179              'stop a catastrophically failing test suite from forcing '
180              'all tests to be rerun in the single-worker phase.'))
181
182    # Remove the reference to our helper function
183    del X
184
185    group = parser.add_argument_group('Test directories')
186    group.add_argument('args', metavar='test-dir', nargs='*', help='Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.')
187
188    return parser
189