|
| 1 | +import argparse |
| 2 | +from contextlib import redirect_stderr, redirect_stdout |
| 3 | +from typing import List |
| 4 | + |
| 5 | +from httpie.context import Environment |
| 6 | +from httpie.internal.update_warnings import _fetch_updates |
| 7 | +from httpie.status import ExitStatus |
| 8 | + |
| 9 | +STATUS_FILE = '.httpie-test-daemon-status' |
| 10 | + |
| 11 | + |
| 12 | +def _check_status(env): |
| 13 | + # This function is used only for the testing (test_update_warnings). |
| 14 | + # Since we don't want to trigger the fetch_updates (which would interact |
| 15 | + # with real world resources), we'll only trigger this pseudo task |
| 16 | + # and check whether the STATUS_FILE is created or not. |
| 17 | + import tempfile |
| 18 | + from pathlib import Path |
| 19 | + |
| 20 | + status_file = Path(tempfile.gettempdir()) / STATUS_FILE |
| 21 | + status_file.touch() |
| 22 | + |
| 23 | + |
| 24 | +DAEMONIZED_TASKS = { |
| 25 | + 'check_status': _check_status, |
| 26 | + 'fetch_updates': _fetch_updates, |
| 27 | +} |
| 28 | + |
| 29 | + |
| 30 | +def _parse_options(args: List[str]) -> argparse.Namespace: |
| 31 | + parser = argparse.ArgumentParser() |
| 32 | + parser.add_argument('task_id') |
| 33 | + parser.add_argument('--daemon', action='store_true') |
| 34 | + return parser.parse_known_args(args)[0] |
| 35 | + |
| 36 | + |
| 37 | +def is_daemon_mode(args: List[str]) -> bool: |
| 38 | + return '--daemon' in args |
| 39 | + |
| 40 | + |
| 41 | +def run_daemon_task(env: Environment, args: List[str]) -> ExitStatus: |
| 42 | + options = _parse_options(args) |
| 43 | + |
| 44 | + assert options.daemon |
| 45 | + assert options.task_id in DAEMONIZED_TASKS |
| 46 | + with redirect_stdout(env.devnull), redirect_stderr(env.devnull): |
| 47 | + DAEMONIZED_TASKS[options.task_id](env) |
| 48 | + |
| 49 | + return ExitStatus.SUCCESS |
0 commit comments