Command-line implementation
***************************

The Python functions behind the "psynet" commands. For the commands
themselves, see Command line.

class psynet.command_line.ListOfStrings

   Bases: "ParamType"

   convert(value, param, ctx)

      Convert the value to the correct type. This is not called if the
      value is "None" (the missing value).

      This must accept string values from the command line, as well as
      values that are already the correct type. It may also convert
      other compatible types.

      The "param" and "ctx" arguments may be "None" in certain
      situations, such as when converting prompt input.

      If the value cannot be converted, call "fail()" with a
      descriptive message.

      Parameters:
         * **value** -- The value to convert.

         * **param** -- The parameter that is using this type to
           convert its value. May be "None".

         * **ctx** -- The current context that arrived at this value.
           May be "None".

   name: str = 'list_of_strings'

      the descriptive name of this type

psynet.command_line.build_remote_experiment_command(app, cmd)

   Build a remote shell command that runs "cmd" inside the app's web
   container.

   "docker compose exec -T" disables TTY allocation, which is what
   makes the command safe to run when the local process has no
   interactive terminal.

psynet.command_line.check_dockerfile()

   Check that a Dockerfile exists and uses the correct format.

   This function performs two checks:

   1. Ensures a Dockerfile exists in the experiment directory

   2. Ensures the Dockerfile uses the new format (Python base image)
      rather than the outdated PsyNet base image format

   Raises:
      **click.UsageError** -- If Dockerfile is missing or uses
      outdated format

psynet.command_line.check_psynet_requirement_includes_experiment_extra()

   Require the PsyNet pin to install the experiment runtime.

   A pin of plain "psynet" installs only the command-line tools. The
   deployment image then has no Dallinger, and the clock process fails
   to start. A missing pin is left to
   "check_psynet_requirement_is_unambiguous()", which runs first.

   Raises:
      **ValueError** -- If the PsyNet requirement omits the
      "[experiment]" extra.

psynet.command_line.check_psynet_requirement_is_unambiguous()

   Validate that "requirements.txt" pins PsyNet unambiguously.

   The check requires a deterministic PsyNet specification so
   deployments are reproducible. Accepted formats are documented on
   "psynet.experiment_scaffold.is_unambiguous_psynet_requirement()".

   Raises:
      **click.ClickException** -- If the PsyNet requirement is missing
      or ambiguous.

psynet.command_line.confirm_deploying_development_psynet()

   Ask before a live remote deployment installs a development PsyNet.

   Release pins ("14.0.0", "14.0.0rc1" or the tag "v14.0.0") pass
   silently. A commit, an alpha, or an entry accepted only because
   "SKIP_CHECK_PSYNET_VERSION_REQUIREMENT" is set is a development
   version. Setting that variable replaces the question with a
   warning.

   Raises:
      **click.exceptions.Exit** -- With exit code 1 if the user
      declines to deploy a development version.

psynet.command_line.db_connection(location, app=None, server=None)

   Get a database connection.

psynet.command_line.export_(ctx, get_exp_variables, app=None, local=False, path=None, assets='collected', n_parallel=None, no_source=False, docker_ssh=False, server=None, dns_host=None, username=None, password=None, transfer='auto', allow_project_mismatch=False, pending_jobs=None, **kwargs)

   Export data from an experiment.

   The data is exported into the specified export directory with the
   following structure:

      export_path/
      ├── database/
      │   ├── participant.csv
      │   ├── trial.csv
      │   └── …
      ├── participant_identifiers.csv
      ├── lucid_entrant_identifiers.csv   # Lucid experiments only
      ├── manifest.json
      ├── basic_data.json OR basic_data/  # optional
      ├── assets/                         # omitted when --assets none
      │   ├── manifest.csv
      │   └── <semantic export paths>
      └── logs.jsonl                      # SSH exports when available

   Table CSVs under "database/" use pseudonymous participant
   identifiers so the archive remains loadable. Original recruiter
   identifiers are written to the sidecar CSV files. This is
   identifier separation, not anonymization. Empty tables are omitted
   from "database/"; "manifest.json" still records a row count of zero
   for them. Boolean columns are written as "True" / "False" rather
   than PostgreSQL "t" / "f". "manifest.json" records the deployment
   git commit instead of bundling source code.

   "--archive" (debug/deploy) accepts "export.zip", a "database/"
   directory, or an extracted export directory containing "database/".

   "get_exp_variables" is a zero-argument callable returning the
   experiment's database variables. It is only called when the export
   actually needs them, because for remote experiments it opens an SSH
   tunnel to the experiment database. Server-built exports do not need
   them: they take the experiment's identity from an authenticated
   preflight instead.

   "pending_jobs" is a remote app's async job summary, taken before
   the export (see "_fetch_ssh_pending_async_jobs()"); local exports
   read their own. A warning about pending jobs ends the output.

psynet.command_line.export_launch_data(deployment_id, **kwargs)

   Retrieves dashboard credentials from the current config and saves
   them to disk, returning the path of the saved file.

psynet.command_line.is_chromedriver_process(process)

   Return whether "process" is a chromedriver started by this shell's
   tests.

psynet.command_line.is_psynet_chrome_process(process)

   Return whether "process" is a Chrome window this shell's local run
   opened.

   Matches debug windows pointed at this run's port and test-driver
   browsers whose profile carries this run's
   "psynet_browser_prefix()", so cleanup leaves browsers belonging to
   other local experiments alone.

psynet.command_line.launch_app_and_open_browsers(port, auth=None, **kwargs)

   Launch the development app, print the "Ready." block, then open the
   browsers.

   Stands in for Dallinger's "launch_app_and_open_browser" RQ job in
   auto-reload runs that open browsers, so that its "Ready." block has
   PsyNet's rows too. It must stay importable by module path because
   RQ workers resolve it that way. "auth" is as for
   "launch_app_without_browsers()".

psynet.command_line.launch_app_without_browsers(port, auth=None, **kwargs)

   Launch the development app without opening browsers.

   Stands in for Dallinger's "launch_app_and_open_browser" RQ job in
   auto-reload "--no-browsers" runs, printing the "Ready." block (see
   "_launch_app_and_report()"). The server log leaves the dashboard
   password out. It must stay importable by module path because RQ
   workers resolve it that way. "auth" is the "(user, password)"
   dashboard login in the job; it defaults to the login in this
   worker's config.

psynet.command_line.list_psynet_worker_processes()

   List local Dallinger web, worker and real-time processes using this
   shell's database.

psynet.command_line.log(msg, chevrons=True, verbose=True, **kw)

   Print a message to stdout, as one plain line.

   "chevrons" is ignored; messages used to start with a blank line and
   "❯❯". Nothing is printed unless "verbose".

psynet.command_line.mark_audit_artifact_present(relative_path)

   Mark the canonical artifact for "relative_path" present in the
   packet.

   Updates the artifact's declared path to "relative_path" so a custom
   manifest cannot be marked present against a different file.

   Return type:
      "Path"

psynet.command_line.mark_performance_result_present(all_results)

   Mark "performance_result" present after a successful audit run.

   Return type:
      "None"

psynet.command_line.performance_results_have_successful_bots(all_results)

   Return True when any "PerformanceTestResult" completed a bot.

   Return type:
      "bool"

psynet.command_line.prolific_listing_warnings(completion_time_s, listed_minutes, base_payment, currency)

   Compare the Prolific listing in "config.txt" with PsyNet's
   estimates.

   Prolific requires "base_payment" alone, without bonuses, to meet
   its minimum hourly rate over participants' median completion time.
   The check therefore uses the longer of the listed and estimated
   durations.

psynet.command_line.psynet_browser_prefix(kind)

   Return the temporary-file prefix for browsers started by this
   shell's tests.

   "kind" is ""chrome"" (profile directory) or ""chromedriver"" (log
   file). The prefix includes a hash of "DATABASE_URL", which
   identifies a local run in the same way as
   "list_psynet_worker_processes()".

psynet.command_line.resolve_audit_artifact_path(relative_path)

   Resolve "./audit/<relative_path>", creating parents.

   Parameters:
      **relative_path** ("Path") -- Path relative to the resolved
      audit folder.

   Return type:
      "Path"

psynet.command_line.resolve_audit_root()

   Resolve "./audit" for audit CLI commands.

   Return type:
      "Path"

psynet.command_line.run_pre_checks(mode, local_, heroku=False, docker=False, app=None, local_packages=(), check_consents=True)

   Check the experiment before a launch.

   "check_consents=False" skips the consent page check, for apps that
   only bots take part in and for "--no-consent" debug deploys.

psynet.command_line.run_pre_checks_sandbox(local_packages=())

   Check the PsyNet and Dallinger pins before a debug deploy.

   Parameters:
      **local_packages** (*tuple** of **str*) -- Packages built into
      the image from local checkouts. Their pins do not decide what
      runs, so they are not checked.

psynet.command_line.run_remote_experiment_command(executor, app, cmd, timeout_s=None)

   Run "cmd" in the app's web container, echoing its output as it
   arrives.

   Dallinger's "Executor.run_and_echo" also watches local stdin so
   that the user can quit by pressing "q"; that makes it exit
   immediately when stdin is closed or not a terminal, which silently
   truncates long-running remote tests. This helper only reads the
   remote channel, and raises "click.ClickException" if the remote
   command fails.

   Output is read to end-of-file rather than until the remote exit
   status is available. The exit status arrives before the last of the
   output, so polling on it drops whatever is still in flight --
   typically the test summary, which is the part worth reading.

   With "timeout_s", the command is stopped after that many seconds
   and "click.ClickException" says so.

psynet.command_line.sql_profiled_command(func)

   Wrap a Click command to enable aggregated SQL profiling.

   Parameters:
      **func** (*callable*) -- Command function with "sql_profile"
      keyword arguments.

   Returns:
      Wrapped command that enables profiling and prints aggregation.

   Return type:
      callable

psynet.command_line.stop_local_debug_process(process)

   Stop a local "psynet debug" pexpect process and reap leftover
   workers.

   Waits for the process to exit after Ctrl-C (escalating to
   SIGTERM/SIGKILL if needed), then terminates any orphaned
   "dallinger_heroku_*" worker processes so they cannot keep database
   connections open.

psynet.command_line.user_confirms(question, default=False)

   Like click.confirm but safe for using within our wrapped Docker
   commands.

   A piped answer isn't echoed, so the prompt line is ended here
   instead.
