Skip to content

Commit

Permalink
[emrun] Use GNU command line flag names
Browse files Browse the repository at this point in the history
For example `--no-browser` vs `--no_browser`.

Continue to support the old style but don't advertise these.
  • Loading branch information
sbc100 committed Feb 26, 2024
1 parent e6be4f5 commit 805bd0b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 48 deletions.
91 changes: 50 additions & 41 deletions emrun.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@
# Stores the browser executable that was run with --browser= parameter.
browser_exe = None

# If we have routed browser output to file with --log_stdout and/or
# --log_stderr, these track the handles.
# If we have routed browser output to file with --log-stdout and/or
# --log-stderr, these track the handles.
browser_stdout_handle = sys.stdout
browser_stderr_handle = sys.stderr

Expand Down Expand Up @@ -408,7 +408,7 @@ def kill_browser_process():
# process that immediately exits.
def detect_browser_processes():
if not browser_exe:
return # Running with --no_browser, we are not binding to a spawned browser.
return # Running with --no-browser, we are not binding to a spawned browser.

global current_browser_processes
logv('First navigation occurred. Identifying currently running browser processes')
Expand Down Expand Up @@ -526,7 +526,7 @@ def serve_forever(self, timeout=0.5):
time_since_message = now - last_message_time
if emrun_options.silence_timeout != 0 and time_since_message > emrun_options.silence_timeout:
self.shutdown()
logi('No activity in ' + str(emrun_options.silence_timeout) + ' seconds. Quitting web server with return code ' + str(emrun_options.timeout_returncode) + '. (--silence_timeout option)')
logi('No activity in ' + str(emrun_options.silence_timeout) + ' seconds. Quitting web server with return code ' + str(emrun_options.timeout_returncode) + '. (--silence-timeout option)')
page_exit_code = emrun_options.timeout_returncode
emrun_options.kill_exit = True

Expand All @@ -542,7 +542,7 @@ def serve_forever(self, timeout=0.5):
if not emrun_not_enabled_nag_printed and page_last_served_time is not None:
time_since_page_serve = now - page_last_served_time
if not have_received_messages and time_since_page_serve > 10:
logv('The html page you are running is not emrun-capable. Stdout, stderr and exit(returncode) capture will not work. Recompile the application with the --emrun linker flag to enable this, or pass --no_emrun_detect to emrun to hide this check.')
logv('The html page you are running is not emrun-capable. Stdout, stderr and exit(returncode) capture will not work. Recompile the application with the --emrun linker flag to enable this, or pass --no-emrun-detect to emrun to hide this check.')
emrun_not_enabled_nag_printed = True

# Clean up at quit, print any leftover messages in queue.
Expand Down Expand Up @@ -703,7 +703,7 @@ def do_POST(self):
elif data.startswith('^exit^'):
if not emrun_options.serve_after_exit:
page_exit_code = int(data[6:])
logv('Web page has quit with a call to exit() with return code ' + str(page_exit_code) + '. Shutting down web server. Pass --serve_after_exit to keep serving even after the page terminates with exit().')
logv('Web page has quit with a call to exit() with return code ' + str(page_exit_code) + '. Shutting down web server. Pass --serve-after-exit to keep serving even after the page terminates with exit().')
self.server.shutdown()
return
else:
Expand Down Expand Up @@ -1155,7 +1155,7 @@ def win_get_default_browser():
except WindowsError:
logv("Unable to find default browser key in Windows registry. Trying fallback.")

# Fall back to 'start "" %1', which we have to treat as if user passed --serve_forever, since
# Fall back to 'start "" %1', which we have to treat as if user passed --serve-forever, since
# for some reason, we are not able to detect when the browser closes when this is passed.
#
# If the first argument to 'start' is quoted, then 'start' will create a new cmd.exe window with
Expand Down Expand Up @@ -1444,44 +1444,44 @@ def list_processes_by_name(exe_full_path):
"""


def parse_args():
def parse_args(args):
parser = argparse.ArgumentParser(usage=usage_str)

parser.add_argument('--kill_start', action='store_true',
parser.add_argument('--kill-start', action='store_true',
help='If true, any previously running instances of '
'the target browser are killed before starting.')

parser.add_argument('--kill_exit', action='store_true',
parser.add_argument('--kill-exit', action='store_true',
help='If true, the spawned browser process is forcibly '
'killed when it calls exit(). Note: Using this '
'option may require explicitly passing the option '
'--browser=/path/to/browser, to avoid emrun being '
'detached from the browser process it spawns.')

parser.add_argument('--no_server', dest='run_server', action='store_false',
parser.add_argument('--no-server', dest='run_server', action='store_false',
default=True,
help='If specified, a HTTP web server is not launched '
'to host the page to run.')

parser.add_argument('--no_browser', dest='run_browser', action='store_false',
parser.add_argument('--no-browser', dest='run_browser', action='store_false',
default=True,
help='If specified, emrun will not launch a web browser '
'to run the page.')

parser.add_argument('--no_emrun_detect', action='store_true',
parser.add_argument('--no-emrun-detect', action='store_true',
help='If specified, skips printing the warning message '
'if html page is detected to not have been built '
'with --emrun linker flag.')

parser.add_argument('--serve_after_close', action='store_true',
parser.add_argument('--serve-after-close', action='store_true',
help='If true, serves the web page even after the '
'application quits by user closing the web page.')

parser.add_argument('--serve_after_exit', action='store_true',
parser.add_argument('--serve-after-exit', action='store_true',
help='If true, serves the web page even after the '
'application quits by a call to exit().')

parser.add_argument('--serve_root',
parser.add_argument('--serve-root',
help='If set, specifies the root path that the emrun '
'web server serves. If not specified, the directory '
'where the target .html page lives in is served.')
Expand All @@ -1495,14 +1495,14 @@ def parse_args():
parser.add_argument('--port', default=default_webserver_port, type=int,
help='Specifies the port the server runs in.')

parser.add_argument('--log_stdout',
parser.add_argument('--log-stdout',
help='Specifies a log filename where the browser process '
'stdout data will be appended to.')

parser.add_argument('--log_stderr',
parser.add_argument('--log-stderr',
help='Specifies a log filename where the browser process stderr data will be appended to.')

parser.add_argument('--silence_timeout', type=int, default=0,
parser.add_argument('--silence-timeout', type=int, default=0,
help='If no activity is received in this many seconds, '
'the browser process is assumed to be hung, and the web '
'server is shut down and the target browser killed. '
Expand All @@ -1514,66 +1514,75 @@ def parse_args():
'to be hung, and the web server is shut down and the '
'target browser killed. Disabled by default.')

parser.add_argument('--timeout_returncode', type=int, default=99999,
parser.add_argument('--timeout-returncode', type=int, default=99999,
help='Sets the exit code that emrun reports back to '
'caller in the case that a page timeout occurs. '
'Default: 99999.')

parser.add_argument('--list_browsers', action='store_true',
parser.add_argument('--list-browsers', action='store_true',
help='Prints out all detected browser that emrun is able '
'to use with the --browser command and exits.')

parser.add_argument('--browser',
help='Specifies the browser executable to run the web page in.')

parser.add_argument('--browser_args', default='',
parser.add_argument('--browser-args', default='',
help='Specifies the arguments to the browser executable.')

parser.add_argument('--android', action='store_true',
help='Launches the page in a browser of an Android '
'device connected to an USB on the local system. (via adb)')

parser.add_argument('--android_tunnel', action='store_true',
parser.add_argument('--android-tunnel', action='store_true',
help='Expose the port directly to the Android device '
'and connect to it as localhost, establishing '
'cross origin isolation. Implies --android. A '
'reverse socket connection is created by adb '
'reverse, and remains after emrun terminates (it '
'can be removed by adb reverse --remove).')

parser.add_argument('--system_info', action='store_true',
parser.add_argument('--system-info', action='store_true',
help='Prints information about the current system at startup.')

parser.add_argument('--browser_info', action='store_true',
parser.add_argument('--browser-info', action='store_true',
help='Prints information about the target browser to launch at startup.')

parser.add_argument('--json', action='store_true',
help='If specified, --system_info and --browser_info are '
help='If specified, --system-info and --browser-info are '
'outputted in JSON format.')

parser.add_argument('--safe_firefox_profile', action='store_true',
parser.add_argument('--safe-firefox-profile', action='store_true',
help='If true, the browser is launched into a new clean '
'Firefox profile that is suitable for unattended '
'automated runs. (If target browser != Firefox, '
'this parameter is ignored)')

parser.add_argument('--private_browsing', action='store_true',
parser.add_argument('--private-browsing', action='store_true',
help='If specified, opens browser in private/incognito mode.')

parser.add_argument('--dump_out_directory', default='dump_out', type=str,
parser.add_argument('--dump-out-directory', default='dump_out', type=str,
help='If specified, overrides the directory for dump files using emrun_file_dump method.')

parser.add_argument('serve', nargs='?', default='')

parser.add_argument('cmdlineparams', nargs='*')

return parser.parse_args()
# Support legacy argument names with `_` in them (but don't
# advertize these in the --help message.
newargs = []
for a in args:
if a.startswith('--') and '_' in a:
newargs.append(a.replace('_', '-'))
else:
newargs.append(a)

return parser.parse_args(newargs)


def run():
def run(args):
global browser_process, browser_exe, processname_killed_atexit, emrun_options, emrun_not_enabled_nag_printed

options = emrun_options = parse_args()
options = emrun_options = parse_args(args)

if options.android_tunnel:
options.android = True
Expand Down Expand Up @@ -1603,7 +1612,7 @@ def run():
return

if not options.serve and (options.system_info or options.browser_info):
# Don't run if only --system_info or --browser_info was passed.
# Don't run if only --system-info or --browser-info was passed.
options.run_server = options.run_browser = False

if not options.serve and (options.run_server or options.run_browser):
Expand Down Expand Up @@ -1659,7 +1668,7 @@ def run():
if options.android:
if options.run_browser or options.browser_info:
if not options.browser:
loge("Running on Android requires that you explicitly specify the browser to run with --browser <id>. Run emrun --android --list_browsers to obtain a list of installed browsers you can use.")
loge("Running on Android requires that you explicitly specify the browser to run with --browser <id>. Run emrun --android --list-browsers to obtain a list of installed browsers you can use.")
return 1
elif options.browser == 'firefox':
browser_app = 'org.mozilla.firefox/org.mozilla.gecko.BrowserApp'
Expand Down Expand Up @@ -1757,7 +1766,7 @@ def run(cmd):
run(['adb', 'push', os.path.join(profile_dir, 'prefs.js'), '/mnt/sdcard/safe_firefox_profile/prefs.js'])
except Exception as e:
loge('Creating Firefox profile prefs.js file to internal storage in /mnt/sdcard failed with error ' + str(e) + '!')
loge('Try running without --safe_firefox_profile flag if unattended execution mode is not important, or')
loge('Try running without --safe-firefox-profile flag if unattended execution mode is not important, or')
loge('enable rooted debugging on the Android device to allow adb to write files to /mnt/sdcard.')
browser += ['--es', 'args', '"--profile /mnt/sdcard/safe_firefox_profile"']

Expand Down Expand Up @@ -1820,7 +1829,7 @@ def run(cmd):
premature_quit_code = browser_process.poll()
if premature_quit_code is not None:
options.serve_after_close = True
logv('Warning: emrun got immediately detached from the target browser process (the process quit with exit code ' + str(premature_quit_code) + '). Cannot detect when user closes the browser. Behaving as if --serve_after_close was passed in.')
logv('Warning: emrun got immediately detached from the target browser process (the process quit with exit code ' + str(premature_quit_code) + '). Cannot detect when user closes the browser. Behaving as if --serve-after-close was passed in.')
if not options.browser:
logv('Try passing the --browser=/path/to/browser option to avoid this from occurring. See https://github.com/emscripten-core/emscripten/issues/3234 for more discussion.')

Expand All @@ -1838,7 +1847,7 @@ def run(cmd):
kill_browser_process()
else:
if is_browser_process_alive():
logv('Not terminating browser process, pass --kill_exit to terminate the browser when it calls exit().')
logv('Not terminating browser process, pass --kill-exit to terminate the browser when it calls exit().')
# If we have created a temporary Firefox profile, we would really really
# like to wait until the browser closes, or otherwise we'll just have to
# litter temp files and keep the temporary profile alive. It is possible
Expand All @@ -1855,13 +1864,13 @@ def run(cmd):
return page_exit_code


def main():
returncode = run()
def main(args):
returncode = run(args)
logv('emrun quitting with process exit code ' + str(returncode))
if temp_firefox_profile_dir is not None:
logi('Warning: Had to leave behind a temporary Firefox profile directory ' + temp_firefox_profile_dir + ' because --safe_firefox_profile was set and the browser did not quit before emrun did.')
logi('Warning: Had to leave behind a temporary Firefox profile directory ' + temp_firefox_profile_dir + ' because --safe-firefox-profile was set and the browser did not quit before emrun did.')
return returncode


if __name__ == '__main__':
sys.exit(main())
sys.exit(main(sys.argv[1:]))
14 changes: 7 additions & 7 deletions test/test_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5844,22 +5844,22 @@ class emrun(RunnerCore):
def test_emrun_info(self):
if not has_browser():
self.skipTest('need a browser')
result = self.run_process([EMRUN, '--system_info', '--browser_info'], stdout=PIPE).stdout
result = self.run_process([EMRUN, '--system-info', '--browser_info'], stdout=PIPE).stdout
assert 'CPU' in result
assert 'Browser' in result
assert 'Traceback' not in result

result = self.run_process([EMRUN, '--list_browsers'], stdout=PIPE).stdout
result = self.run_process([EMRUN, '--list-browsers'], stdout=PIPE).stdout
assert 'Traceback' not in result

def test_no_browser(self):
# Test --no_browser mode where we have to take care of launching the browser ourselves
# Test --no-browser mode where we have to take care of launching the browser ourselves
# and then killing emrun when we are done.
if not has_browser():
self.skipTest('need a browser')

self.run_process([EMCC, test_file('test_emrun.c'), '--emrun', '-o', 'hello_world.html'])
proc = subprocess.Popen([EMRUN, '--no_browser', '.', '--port=3333'], stdout=PIPE)
proc = subprocess.Popen([EMRUN, '--no-browser', '.', '--port=3333'], stdout=PIPE)
try:
if EMTEST_BROWSER:
print('Starting browser')
Expand Down Expand Up @@ -5891,9 +5891,9 @@ def test_emrun(self):

os.chdir(path_from_root())
args_base = [EMRUN, '--timeout', '30', '--safe_firefox_profile',
'--kill_exit', '--port', '6939', '--verbose',
'--log_stdout', self.in_dir('stdout.txt'),
'--log_stderr', self.in_dir('stderr.txt')]
'--kill-exit', '--port', '6939', '--verbose',
'--log-stdout', self.in_dir('stdout.txt'),
'--log-stderr', self.in_dir('stderr.txt')]

# Verify that trying to pass argument to the page without the `--` separator will
# generate an actionable error message
Expand Down

0 comments on commit 805bd0b

Please sign in to comment.