| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
"""Common options for all cylc commands.""" |
| 17 |
|
| 18 |
from contextlib import suppress |
| 19 |
import logging |
| 20 |
from itertools import product |
| 21 |
from optparse import ( |
| 22 |
OptionParser, |
| 23 |
Values, |
| 24 |
Option, |
| 25 |
IndentedHelpFormatter, |
| 26 |
) |
| 27 |
import os |
| 28 |
import re |
| 29 |
import sys |
| 30 |
from textwrap import dedent |
| 31 |
from typing import Any, Dict, Iterable, Optional, List, Set, Tuple |
| 32 |
|
| 33 |
from ansimarkup import ( |
| 34 |
parse as cparse, |
| 35 |
strip as cstrip |
| 36 |
) |
| 37 |
|
| 38 |
from cylc.flow import LOG |
| 39 |
from cylc.flow.terminal import should_use_color, DIM |
| 40 |
import cylc.flow.flags |
| 41 |
from cylc.flow.loggingutil import ( |
| 42 |
CylcLogFormatter, |
| 43 |
setup_segregated_log_streams, |
| 44 |
) |
| 45 |
from cylc.flow.log_level import ( |
| 46 |
env_to_verbosity, |
| 47 |
verbosity_to_log_level |
| 48 |
) |
| 49 |
|
| 50 |
WORKFLOW_ID_ARG_DOC = ('WORKFLOW', 'Workflow ID') |
| 51 |
OPT_WORKFLOW_ID_ARG_DOC = ('[WORKFLOW]', 'Workflow ID') |
| 52 |
WORKFLOW_ID_MULTI_ARG_DOC = ('WORKFLOW ...', 'Workflow ID(s)') |
| 53 |
WORKFLOW_ID_OR_PATH_ARG_DOC = ('WORKFLOW | PATH', 'Workflow ID or path') |
| 54 |
ID_SEL_ARG_DOC = ('ID[:sel]', 'WORKFLOW-ID[[//CYCLE[/TASK]]:selector]') |
| 55 |
ID_MULTI_ARG_DOC = ('ID ...', 'Workflow/Cycle/Family/Task ID(s)') |
| 56 |
FULL_ID_MULTI_ARG_DOC = ('ID ...', 'Cycle/Family/Task ID(s)') |
| 57 |
|
| 58 |
SHORTLINK_TO_ICP_DOCS = "https://bit.ly/3MYHqVh" |
| 59 |
DOUBLEDASH = '--' |
| 60 |
|
| 61 |
|
| 62 |
class OptionSettings(): |
| 63 |
"""Container for info about a command line option |
| 64 |
|
| 65 |
Despite some similarities this is not to be confused with |
| 66 |
optparse.Option: This a container for information which may or may |
| 67 |
not be passed to optparse depending on the results of |
| 68 |
cylc.flow.option_parsers(thismodule).combine_options_pair. |
| 69 |
""" |
| 70 |
|
| 71 |
def __init__( |
| 72 |
self, |
| 73 |
argslist: List[str], |
| 74 |
sources: Optional[Set[str]] = None, |
| 75 |
useif: str = '', |
| 76 |
**kwargs |
| 77 |
): |
| 78 |
"""Init function: |
| 79 |
|
| 80 |
Args: |
| 81 |
arglist: list of arguments for optparse.Option. |
| 82 |
sources: set of CLI scripts which use this option. |
| 83 |
useif: badge for use by Cylc optionparser. |
| 84 |
**kwargs: kwargs for optparse.option. |
| 85 |
""" |
| 86 |
self.args: List[str] = argslist |
| 87 |
self.kwargs: Dict[str, Any] = kwargs |
| 88 |
self.sources: Set[str] = sources if sources is not None else set() |
| 89 |
self.useif: str = useif |
| 90 |
|
| 91 |
def __eq__(self, other): |
| 92 |
"""Args and Kwargs, but not other props equal. |
| 93 |
|
| 94 |
(Also make an exception for kwargs['help'] to allow lists of sources |
| 95 |
prepended to 'help' to be passed through.) |
| 96 |
""" |
| 97 |
return ( |
| 98 |
( |
| 99 |
{k: v for k, v in self.kwargs.items() if k != 'help'} |
| 100 |
== {k: v for k, v in other.kwargs.items() if k != 'help'} |
| 101 |
) |
| 102 |
and self.args == other.args |
| 103 |
) |
| 104 |
|
| 105 |
def __and__(self, other): |
| 106 |
"""Is there a set intersection between arguments.""" |
| 107 |
return list(set(self.args).intersection(set(other.args))) |
| 108 |
|
| 109 |
def __sub__(self, other): |
| 110 |
"""Set difference on args.""" |
| 111 |
return list(set(self.args) - set(other.args)) |
| 112 |
|
| 113 |
def _in_list(self, others): |
| 114 |
"""CLI arguments for this option found in any of a list of |
| 115 |
other options.""" |
| 116 |
return any(self & other for other in others) |
| 117 |
|
| 118 |
def _update_sources(self, other): |
| 119 |
"""Update the sources from this and 1 other OptionSettings object""" |
| 120 |
self.sources = {*self.sources, *other.sources} |
| 121 |
|
| 122 |
def __repr__(self) -> str: |
| 123 |
return f"<{type(self).__name__} {self.args}>" |
| 124 |
|
| 125 |
|
| 126 |
ICP_OPTION = OptionSettings( |
| 127 |
["--initial-cycle-point", "--icp"], |
| 128 |
help=( |
| 129 |
"Set the initial cycle point. " |
| 130 |
"Required if not defined in flow.cylc.\n" |
| 131 |
"Can be an absolute point or an offset relative to the " |
| 132 |
"current time - see " |
| 133 |
f"{SHORTLINK_TO_ICP_DOCS} (Cylc documentation link)." |
| 134 |
), |
| 135 |
metavar="CYCLE_POINT or OFFSET", |
| 136 |
action='store', |
| 137 |
dest="icp" |
| 138 |
) |
| 139 |
|
| 140 |
AGAINST_SOURCE_OPTION = OptionSettings( |
| 141 |
['--against-source'], |
| 142 |
help=( |
| 143 |
"Load the workflow configuration from the source directory it was" |
| 144 |
" installed from using any options (e.g. template variables) which" |
| 145 |
" have been set in the installation." |
| 146 |
" This is useful if you want to see how changes made to the workflow" |
| 147 |
" source would affect the installation if reinstalled." |
| 148 |
" Note if this option is used the provided workflow must have been" |
| 149 |
" installed by `cylc install`." |
| 150 |
), |
| 151 |
dest='against_source', |
| 152 |
action='store_true', |
| 153 |
default=False |
| 154 |
) |
| 155 |
|
| 156 |
|
| 157 |
icp_option = Option( |
| 158 |
*ICP_OPTION.args, **ICP_OPTION.kwargs) # type: ignore[arg-type] |
| 159 |
|
| 160 |
|
| 161 |
def format_shell_examples(string): |
| 162 |
"""Put comments in the terminal "diminished" colour.""" |
| 163 |
return cparse( |
| 164 |
re.sub( |
| 165 |
r'^(\s*(?:\$[^#]+)?)(#.*)$', |
| 166 |
rf'\1<{DIM}>\2</{DIM}>', |
| 167 |
string, |
| 168 |
flags=re.M, |
| 169 |
) |
| 170 |
) |
| 171 |
|
| 172 |
|
| 173 |
def format_help_headings(string): |
| 174 |
"""Put "headings" in bold. |
| 175 |
|
| 176 |
Where "headings" are lines with no indentation which are followed by a |
| 177 |
colon. |
| 178 |
""" |
| 179 |
return cparse( |
| 180 |
re.sub( |
| 181 |
r'^(\w.*:)$', |
| 182 |
r'<bold>\1</bold>', |
| 183 |
string, |
| 184 |
flags=re.M, |
| 185 |
) |
| 186 |
) |
| 187 |
|
| 188 |
|
| 189 |
class CylcOption(Option): |
| 190 |
"""Optparse option which adds a decrement action.""" |
| 191 |
|
| 192 |
ACTIONS = Option.ACTIONS + ('decrement',) |
| 193 |
STORE_ACTIONS = Option.STORE_ACTIONS + ('decrement',) |
| 194 |
|
| 195 |
def take_action(self, action, dest, opt, value, values, parser): |
| 196 |
if action == 'decrement': |
| 197 |
setattr(values, dest, values.ensure_value(dest, 0) - 1) |
| 198 |
else: |
| 199 |
Option.take_action(self, action, dest, opt, value, values, parser) |
| 200 |
|
| 201 |
|
| 202 |
class CylcHelpFormatter(IndentedHelpFormatter): |
| 203 |
"""This formatter handles colour in help text, and automatically |
| 204 |
colourises headings & shell examples.""" |
| 205 |
|
| 206 |
def _format(self, text: str) -> str: |
| 207 |
"""Format help (usage) text on the fly to handle coloring. |
| 208 |
|
| 209 |
Help is printed to the terminal before color initialization for general |
| 210 |
command output. |
| 211 |
|
| 212 |
If coloring is wanted: |
| 213 |
- Add color tags to shell examples |
| 214 |
Else: |
| 215 |
- Strip any hardwired color tags |
| 216 |
|
| 217 |
""" |
| 218 |
if should_use_color(self.parser.values): |
| 219 |
# Add color formatting to examples text. |
| 220 |
return format_shell_examples( |
| 221 |
format_help_headings(text) |
| 222 |
) |
| 223 |
# Else strip any hardwired formatting |
| 224 |
return cstrip(text) |
| 225 |
|
| 226 |
def format_usage(self, usage: str) -> str: |
| 227 |
return super().format_usage(self._format(usage)) |
| 228 |
|
| 229 |
# If we start using "description" as well as "usage" (also epilog): |
| 230 |
# def format_description(self, description): |
| 231 |
# return super().format_description(self._format(description)) |
| 232 |
|
| 233 |
def format_option(self, option: Option) -> str: |
| 234 |
"""Format help text for options.""" |
| 235 |
if option.help: |
| 236 |
if should_use_color(self.parser.values): |
| 237 |
option.help = cparse(option.help) |
| 238 |
else: |
| 239 |
option.help = cstrip(option.help) |
| 240 |
return super().format_option(option) |
| 241 |
|
| 242 |
|
| 243 |
class CylcOptionParser(OptionParser): |
| 244 |
|
| 245 |
"""Common options for all cylc CLI commands.""" |
| 246 |
|
| 247 |
MULTITASK_USAGE = dedent(''' |
| 248 |
This command can operate on multiple tasks: |
| 249 |
Multiple Tasks: |
| 250 |
# Operate on two tasks |
| 251 |
//cycle-1/task-1 //cycle-2/task-2 |
| 252 |
|
| 253 |
# Operate on all members of a family |
| 254 |
//cycle-1/FAMILY-NAME |
| 255 |
|
| 256 |
# Operate on all tasks in a cycle |
| 257 |
//cycle # shorthand for '//cycle/root' |
| 258 |
|
| 259 |
Globs (note: quote globs or they might expand in your shell): |
| 260 |
# Match all tasks in cycle "1" with names beginning with "foo" |
| 261 |
''//1/foo*' |
| 262 |
|
| 263 |
# Match the task "foo" in all active (i.e. n=0) cycles |
| 264 |
'//*/foo' |
| 265 |
|
| 266 |
# Match the tasks "foo-1" and "foo-2" in all active cycles. |
| 267 |
'//*/foo-[12]' |
| 268 |
|
| 269 |
Selectors (note: selectors only match active tasks): |
| 270 |
# match all failed tasks in cycle "1" |
| 271 |
//1:failed |
| 272 |
|
| 273 |
See `cylc help id` for more details. |
| 274 |
''') |
| 275 |
MULTIWORKFLOW_USAGE = dedent(''' |
| 276 |
This command can operate on multiple workflows. Globs may be used: |
| 277 |
Multiple Workflows: |
| 278 |
# Operate on two workflows |
| 279 |
workflow-1 workflow-2 |
| 280 |
|
| 281 |
Globs (note: globs should be quoted): |
| 282 |
# Match all workflows |
| 283 |
'*' |
| 284 |
|
| 285 |
# Match the workflows foo-1, foo-2 |
| 286 |
'foo-[12]' |
| 287 |
|
| 288 |
See `cylc help id` for more details. |
| 289 |
''') |
| 290 |
|
| 291 |
CAN_BE_USED_MULTIPLE = ( |
| 292 |
" This option can be used multiple times on the command line.") |
| 293 |
|
| 294 |
NOTE_PERSIST_ACROSS_RESTARTS = ( |
| 295 |
" NOTE: these settings persist across workflow restarts," |
| 296 |
" but can be set again on the \"cylc play\"" |
| 297 |
" command line if they need to be overridden." |
| 298 |
) |
| 299 |
|
| 300 |
STD_OPTIONS = [ |
| 301 |
OptionSettings( |
| 302 |
['-q', '--quiet'], help='Decrease verbosity.', |
| 303 |
action='decrement', dest='verbosity', useif='all'), |
| 304 |
OptionSettings( |
| 305 |
['-v', '--verbose'], help='Increase Verbosity', |
| 306 |
dest='verbosity', action='count', |
| 307 |
default=env_to_verbosity(os.environ), useif='all'), |
| 308 |
OptionSettings( |
| 309 |
['--debug'], help='Equivalent to -v -v', |
| 310 |
dest='verbosity', action='store_const', const=2, useif='all'), |
| 311 |
OptionSettings( |
| 312 |
['--timestamp'], |
| 313 |
help='Add a timestamp to messages logged to the terminal.', |
| 314 |
action='store_true', dest='log_timestamp', |
| 315 |
default=False, useif='all'), |
| 316 |
OptionSettings( |
| 317 |
['--no-timestamp'], help="Don't add a timestamp to messages logged" |
| 318 |
" to the terminal (this does nothing - it is now the default.", |
| 319 |
action='store_false', dest='_noop', |
| 320 |
default=False, useif='all'), |
| 321 |
OptionSettings( |
| 322 |
['--color', '--colour'], metavar='WHEN', action='store', |
| 323 |
default='auto', choices=['never', 'auto', 'always'], |
| 324 |
help=( |
| 325 |
"When to use color/bold text in terminal output." |
| 326 |
" Options are 'never', 'auto' and 'always'." |
| 327 |
), |
| 328 |
useif='color'), |
| 329 |
OptionSettings( |
| 330 |
['--comms-timeout'], metavar='SEC', |
| 331 |
help=( |
| 332 |
"Set the timeout for communication with the running workflow." |
| 333 |
" The default is determined by the setup, 5 seconds for" |
| 334 |
" TCP comms and 300 for SSH." |
| 335 |
" If connections timeout, it likely means either, a complex" |
| 336 |
" request has been issued (e.g. cylc tui); there is a network" |
| 337 |
" issue; or a problem with the scheduler. Increasing the" |
| 338 |
" timeout will help with the first case." |
| 339 |
), |
| 340 |
action='store', default=None, dest='comms_timeout', useif='comms'), |
| 341 |
OptionSettings( |
| 342 |
['-s', '--set'], metavar='NAME=VALUE', |
| 343 |
help=( |
| 344 |
"Set the value of a Jinja2 template variable in the" |
| 345 |
" workflow definition." |
| 346 |
" Values should be valid Python literals so strings" |
| 347 |
" must be quoted" |
| 348 |
" e.g. 'STR=\"string\"', INT=43, BOOL=True." |
| 349 |
+ CAN_BE_USED_MULTIPLE |
| 350 |
+ NOTE_PERSIST_ACROSS_RESTARTS |
| 351 |
), |
| 352 |
action='append', default=[], dest='templatevars', useif='jset' |
| 353 |
), |
| 354 |
OptionSettings( |
| 355 |
['-z', '--set-list', '--template-list'], |
| 356 |
metavar='NAME=VALUE1,VALUE2,...', |
| 357 |
# NOTE: deliberate non-breaking spaces in help text: |
| 358 |
help=( |
| 359 |
'A more convenient alternative to --set for defining a list' |
| 360 |
' of strings. E.G.' |
| 361 |
' "-z FOO=a,b,c" is shorthand for' |
| 362 |
' "-s FOO=[\'a\',\'b\',\'c\']".' |
| 363 |
' Commas can be present in values if quoted, e.g.' |
| 364 |
' "-z FOO=a,\'b,c\'" is shorthand for' |
| 365 |
' "-s FOO=[\'a\',\'b,c\']".' |
| 366 |
+ CAN_BE_USED_MULTIPLE |
| 367 |
+ NOTE_PERSIST_ACROSS_RESTARTS |
| 368 |
), |
| 369 |
action='append', default=[], dest='templatevars_lists', |
| 370 |
useif='jset' |
| 371 |
), |
| 372 |
OptionSettings( |
| 373 |
['--set-file'], metavar='FILE', |
| 374 |
help=( |
| 375 |
"Set the value of Jinja2 template variables in the" |
| 376 |
" workflow definition from a file containing NAME=VALUE" |
| 377 |
" pairs (one per line)." |
| 378 |
" As with --set values should be valid Python literals " |
| 379 |
" so strings must be quoted e.g. STR='string'." |
| 380 |
+ NOTE_PERSIST_ACROSS_RESTARTS |
| 381 |
), |
| 382 |
action='store', default=None, dest='templatevars_file', |
| 383 |
useif='jset' |
| 384 |
) |
| 385 |
] |
| 386 |
|
| 387 |
def __init__( |
| 388 |
self, |
| 389 |
usage: str, |
| 390 |
argdoc: Optional[List[Tuple[str, str]]] = None, |
| 391 |
comms: bool = False, |
| 392 |
jset: bool = False, |
| 393 |
multitask: bool = False, |
| 394 |
multiworkflow: bool = False, |
| 395 |
auto_add: bool = True, |
| 396 |
color: bool = True, |
| 397 |
segregated_log: bool = False |
| 398 |
) -> None: |
| 399 |
""" |
| 400 |
Args: |
| 401 |
usage: Usage instructions. Typically this will be the __doc__ of |
| 402 |
the script module. |
| 403 |
argdoc: The args for the command, to be inserted into the usage |
| 404 |
instructions. Optional list of tuples of (name, description). |
| 405 |
comms: If True, allow the --comms-timeout option. |
| 406 |
jset: If True, allow the Jinja2 --set option. |
| 407 |
multitask: If True, insert the multitask text into the |
| 408 |
usage instructions. |
| 409 |
multiworkflow: If True, insert the multiworkflow text into the |
| 410 |
usage instructions. |
| 411 |
auto_add: If True, allow the standard options. |
| 412 |
color: If True, allow the --color option. |
| 413 |
segregated_log: If False, write all logging entries to stderr. |
| 414 |
If True, write entries at level < WARNING to stdout and |
| 415 |
entries at level >= WARNING to stderr. |
| 416 |
""" |
| 417 |
self.auto_add = auto_add |
| 418 |
|
| 419 |
if multiworkflow: |
| 420 |
usage += self.MULTIWORKFLOW_USAGE |
| 421 |
|
| 422 |
if multitask: |
| 423 |
usage += self.MULTITASK_USAGE |
| 424 |
|
| 425 |
args = "" |
| 426 |
self.n_compulsory_args = 0 |
| 427 |
self.n_optional_args = 0 |
| 428 |
self.unlimited_args = False |
| 429 |
self.comms = comms |
| 430 |
self.jset = jset |
| 431 |
self.color = color |
| 432 |
# Whether to log messages that are below warning level to stdout |
| 433 |
# instead of stderr: |
| 434 |
self.segregated_log = segregated_log |
| 435 |
|
| 436 |
if argdoc: |
| 437 |
maxlen = max(len(arg) for arg, _ in argdoc) |
| 438 |
usage += "\n\nArguments:" |
| 439 |
for arg, descr in argdoc: |
| 440 |
if arg.startswith('['): |
| 441 |
self.n_optional_args += 1 |
| 442 |
else: |
| 443 |
self.n_compulsory_args += 1 |
| 444 |
if arg.rstrip(']').endswith('...'): |
| 445 |
self.unlimited_args = True |
| 446 |
|
| 447 |
args += arg + " " |
| 448 |
|
| 449 |
pad = (maxlen - len(arg)) * ' ' + ' ' |
| 450 |
usage += "\n " + arg + pad + descr |
| 451 |
usage = usage.replace('ARGS', args) |
| 452 |
|
| 453 |
OptionParser.__init__( |
| 454 |
self, |
| 455 |
usage, |
| 456 |
option_class=CylcOption, |
| 457 |
formatter=CylcHelpFormatter() |
| 458 |
) |
| 459 |
|
| 460 |
def get_std_options(self): |
| 461 |
"""Get a data-structure of standard options""" |
| 462 |
opts = [] |
| 463 |
for opt in self.STD_OPTIONS: |
| 464 |
if ( |
| 465 |
opt.useif == 'all' |
| 466 |
or hasattr(self, opt.useif) and getattr(self, opt.useif) |
| 467 |
): |
| 468 |
opts.append(opt) |
| 469 |
return opts |
| 470 |
|
| 471 |
def add_std_options(self): |
| 472 |
"""Add standard options if they have not been overridden.""" |
| 473 |
for option in self.get_std_options(): |
| 474 |
if not any(self.has_option(i) for i in option.args): |
| 475 |
self.add_option(*option.args, **option.kwargs) |
| 476 |
|
| 477 |
@staticmethod |
| 478 |
def get_cylc_rose_options(): |
| 479 |
"""Returns a list of option dictionaries if Cylc Rose exists.""" |
| 480 |
try: |
| 481 |
__import__('cylc.rose') |
| 482 |
except ImportError: |
| 483 |
return [] |
| 484 |
return [ |
| 485 |
OptionSettings( |
| 486 |
["--opt-conf-key", "-O"], |
| 487 |
help=( |
| 488 |
"Use optional Rose Config Setting" |
| 489 |
" (If Cylc-Rose is installed)"), |
| 490 |
action="append", default=[], dest="opt_conf_keys", |
| 491 |
sources={'cylc-rose'}, |
| 492 |
), |
| 493 |
OptionSettings( |
| 494 |
["--define", '-D'], |
| 495 |
help=( |
| 496 |
"Each of these overrides the `[SECTION]KEY` setting" |
| 497 |
" in a `rose-suite.conf` file." |
| 498 |
" Can be used to disable a setting using the syntax" |
| 499 |
" `--define=[SECTION]!KEY` or" |
| 500 |
" even `--define=[!SECTION]`."), |
| 501 |
action="append", default=[], dest="defines", |
| 502 |
sources={'cylc-rose'}), |
| 503 |
OptionSettings( |
| 504 |
["--rose-template-variable", '-S', '--define-suite'], |
| 505 |
help=( |
| 506 |
"As `--define`, but with an implicit `[SECTION]` for" |
| 507 |
" workflow variables."), |
| 508 |
action="append", default=[], dest="rose_template_vars", |
| 509 |
sources={'cylc-rose'}, |
| 510 |
) |
| 511 |
] |
| 512 |
|
| 513 |
def add_cylc_rose_options(self) -> None: |
| 514 |
"""Add extra options for cylc-rose plugin if it is installed. |
| 515 |
|
| 516 |
Now a vestigal interface for get_cylc_rose_options. |
| 517 |
""" |
| 518 |
for option in self.get_cylc_rose_options(): |
| 519 |
self.add_option(*option.args, **option.kwargs) |
| 520 |
|
| 521 |
def parse_args(self, api_args, remove_opts=None): |
| 522 |
"""Parse options and arguments, overrides OptionParser.parse_args. |
| 523 |
|
| 524 |
Args: |
| 525 |
api_args (list): |
| 526 |
Command line options if passed via Python as opposed to |
| 527 |
sys.argv |
| 528 |
remove_opts (list): |
| 529 |
List of standard options to remove before parsing. |
| 530 |
|
| 531 |
""" |
| 532 |
if self.auto_add: |
| 533 |
# Add common options after command-specific options. |
| 534 |
self.add_std_options() |
| 535 |
|
| 536 |
if remove_opts: |
| 537 |
for opt in remove_opts: |
| 538 |
with suppress(ValueError): |
| 539 |
self.remove_option(opt) |
| 540 |
|
| 541 |
(options, args) = OptionParser.parse_args(self, api_args) |
| 542 |
|
| 543 |
if len(args) < self.n_compulsory_args: |
| 544 |
self.error("Wrong number of arguments (too few)") |
| 545 |
|
| 546 |
elif ( |
| 547 |
not self.unlimited_args |
| 548 |
and len(args) > self.n_compulsory_args + self.n_optional_args |
| 549 |
): |
| 550 |
self.error("Wrong number of arguments (too many)") |
| 551 |
|
| 552 |
if self.jset and options.templatevars_file: |
| 553 |
options.templatevars_file = os.path.abspath(os.path.expanduser( |
| 554 |
options.templatevars_file) |
| 555 |
) |
| 556 |
|
| 557 |
cylc.flow.flags.verbosity = options.verbosity |
| 558 |
|
| 559 |
# Set up stream logging for CLI. Note: |
| 560 |
# 1. On choosing STDERR: Log messages are diagnostics, so STDERR is the |
| 561 |
# better choice for the logging stream. This allows us to use STDOUT |
| 562 |
# for verbosity agnostic outputs. |
| 563 |
# 2. Scheduler will remove this handler when it becomes a daemon. |
| 564 |
LOG.setLevel(verbosity_to_log_level(options.verbosity)) |
| 565 |
# Remove NullHandler before add the StreamHandler |
| 566 |
|
| 567 |
while LOG.handlers: |
| 568 |
LOG.handlers[0].close() |
| 569 |
LOG.removeHandler(LOG.handlers[0]) |
| 570 |
log_handler = logging.StreamHandler(sys.stderr) |
| 571 |
log_handler.setFormatter(CylcLogFormatter( |
| 572 |
timestamp=options.log_timestamp, |
| 573 |
dev_info=(options.verbosity > 2) |
| 574 |
)) |
| 575 |
LOG.addHandler(log_handler) |
| 576 |
|
| 577 |
if self.segregated_log: |
| 578 |
setup_segregated_log_streams(LOG, log_handler) |
| 579 |
|
| 580 |
return (options, args) |
| 581 |
|
| 582 |
@staticmethod |
| 583 |
def optional(arg: Tuple[str, str]) -> Tuple[str, str]: |
| 584 |
"""Make an argdoc tuple display as an optional arg with |
| 585 |
square brackets.""" |
| 586 |
name, doc = arg |
| 587 |
return (f'[{name}]', doc) |
| 588 |
|
| 589 |
|
| 590 |
class Options: |
| 591 |
"""Wrapper to allow Python API access to optparse CLI functionality. |
| 592 |
|
| 593 |
Example: |
| 594 |
Create an optparse parser as normal: |
| 595 |
>>> import optparse |
| 596 |
>>> parser = optparse.OptionParser() |
| 597 |
>>> _ = parser.add_option('-a', default=1) |
| 598 |
>>> _ = parser.add_option('-b', default=2) |
| 599 |
|
| 600 |
Create an Options object from the parser: |
| 601 |
>>> PythonOptions = Options(parser, overrides={'c': 3}) |
| 602 |
|
| 603 |
"Parse" options via Python API: |
| 604 |
>>> opts = PythonOptions(a=4) |
| 605 |
|
| 606 |
Access options as normal: |
| 607 |
>>> opts.a |
| 608 |
4 |
| 609 |
>>> opts.b |
| 610 |
2 |
| 611 |
>>> opts.c |
| 612 |
3 |
| 613 |
|
| 614 |
Optparse allows you to create new options on the fly: |
| 615 |
>>> opts.d = 5 |
| 616 |
>>> opts.d |
| 617 |
5 |
| 618 |
|
| 619 |
But you can't create new options at initiation, this gives us basic |
| 620 |
input validation: |
| 621 |
>>> PythonOptions(e=6) |
| 622 |
Traceback (most recent call last): |
| 623 |
ValueError: e |
| 624 |
|
| 625 |
You can reuse the object multiple times |
| 626 |
>>> opts2 = PythonOptions(a=2) |
| 627 |
>>> id(opts) == id(opts2) |
| 628 |
False |
| 629 |
|
| 630 |
""" |
| 631 |
|
| 632 |
def __init__( |
| 633 |
self, parser: OptionParser, overrides: Optional[Dict[str, Any]] = None |
| 634 |
) -> None: |
| 635 |
if overrides is None: |
| 636 |
overrides = {} |
| 637 |
if isinstance(parser, CylcOptionParser) and parser.auto_add: |
| 638 |
parser.add_std_options() |
| 639 |
self.defaults = {**parser.defaults, **overrides} |
| 640 |
|
| 641 |
def __call__(self, **kwargs) -> Values: |
| 642 |
opts = Values(self.defaults) |
| 643 |
for key, value in kwargs.items(): |
| 644 |
if not hasattr(opts, key): |
| 645 |
raise ValueError(key) |
| 646 |
setattr(opts, key, value) |
| 647 |
|
| 648 |
return opts |
| 649 |
|
| 650 |
|
| 651 |
def appendif(list_, item): |
| 652 |
"""Avoid duplicating items in output list""" |
| 653 |
if item not in list_: |
| 654 |
list_.append(item) |
| 655 |
return list_ |
| 656 |
|
| 657 |
|
| 658 |
def combine_options_pair(first_list, second_list): |
| 659 |
"""Combine two option lists recording where each came from. |
| 660 |
|
| 661 |
Scenarios: |
| 662 |
- Arguments are identical - return this argument. |
| 663 |
- Arguments are not identical but have some common label strings, |
| 664 |
i.e. both arguments can be invoked using `-f`. |
| 665 |
- If there are non-shared label strings strip the shared ones. |
| 666 |
- Otherwise raise an error. |
| 667 |
E.g: If `command-A` has an option `-f` or `--file` and |
| 668 |
`command-B has an option `-f` or `--fortran`` then |
| 669 |
`command-A+B` will have options `--fortran` and `--file` but _not_ |
| 670 |
`-f`, which would be confusing. |
| 671 |
- Arguments only apply to a single component of the compound CLI |
| 672 |
script. |
| 673 |
|
| 674 |
""" |
| 675 |
output = [] |
| 676 |
if not first_list: |
| 677 |
output = second_list |
| 678 |
elif not second_list: |
| 679 |
output = first_list |
| 680 |
else: |
| 681 |
for first, second in product(first_list, second_list): |
| 682 |
# Two options are identical in both args and kwargs: |
| 683 |
if first == second: |
| 684 |
first._update_sources(second) |
| 685 |
output = appendif(output, first) |
| 686 |
|
| 687 |
# If any of the argument names identical we must remove |
| 688 |
# overlapping names (if we can) |
| 689 |
# e.g. [-a, --aleph], [-a, --alpha-centuri] -> keep both options |
| 690 |
# but neither should have the `-a` short version: |
| 691 |
elif ( |
| 692 |
first != second |
| 693 |
and first & second |
| 694 |
): |
| 695 |
# if any of the args are different: |
| 696 |
|
| 697 |
if first.args == second.args: |
| 698 |
raise Exception( |
| 699 |
f'Clashing Options \n{first.args}\n{second.args}') |
| 700 |
else: |
| 701 |
first_args = first - second |
| 702 |
second.args = second - first |
| 703 |
first.args = first_args |
| 704 |
output = appendif(output, first) |
| 705 |
output = appendif(output, second) |
| 706 |
else: |
| 707 |
# Neither option appears in the other list, so it can be |
| 708 |
# appended: |
| 709 |
if not first._in_list(second_list): |
| 710 |
output = appendif(output, first) |
| 711 |
if not second._in_list(first_list): |
| 712 |
output = appendif(output, second) |
| 713 |
|
| 714 |
return output |
| 715 |
|
| 716 |
|
| 717 |
def add_sources_to_helps( |
| 718 |
options: Iterable[OptionSettings], modify: Optional[dict] = None |
| 719 |
) -> None: |
| 720 |
"""Get list of CLI commands this option applies to |
| 721 |
and prepend that list to the start of help. |
| 722 |
|
| 723 |
Arguments: |
| 724 |
options: |
| 725 |
List of OptionSettings to modify help upon. |
| 726 |
modify: |
| 727 |
Dict of items to substitute: Intended to allow one |
| 728 |
to replace cylc-rose with the names of the sub-commands |
| 729 |
cylc rose options apply to. |
| 730 |
""" |
| 731 |
modify = {} if modify is None else modify |
| 732 |
for option in options: |
| 733 |
if hasattr(option, 'sources'): |
| 734 |
sources = list(option.sources) |
| 735 |
for match, sub in modify.items(): |
| 736 |
if match in option.sources: |
| 737 |
sources.append(sub) |
| 738 |
sources.remove(match) |
| 739 |
|
| 740 |
option.kwargs['help'] = ( |
| 741 |
f'<cyan>[{", ".join(sources)}]</cyan>' |
| 742 |
f' {option.kwargs["help"]}' |
| 743 |
) |
| 744 |
|
| 745 |
|
| 746 |
def combine_options( |
| 747 |
*args: List[OptionSettings], modify: Optional[dict] = None |
| 748 |
) -> List[OptionSettings]: |
| 749 |
"""Combine lists of Cylc options. |
| 750 |
|
| 751 |
Ordering should be irrelevant because combine_options_pair should |
| 752 |
be commutative, and the overall order of args is not relevant. |
| 753 |
""" |
| 754 |
output = args[0] |
| 755 |
for arg in args[1:]: |
| 756 |
output = combine_options_pair(arg, output) |
| 757 |
|
| 758 |
add_sources_to_helps(output, modify) |
| 759 |
return output |
| 760 |
|
| 761 |
|
| 762 |
def cleanup_sysargv( |
| 763 |
script_name: str, |
| 764 |
workflow_id: str, |
| 765 |
options: 'Values', |
| 766 |
compound_script_opts: Iterable['OptionSettings'], |
| 767 |
script_opts: Iterable['OptionSettings'], |
| 768 |
source: str, |
| 769 |
) -> None: |
| 770 |
"""Remove unwanted options from sys.argv |
| 771 |
|
| 772 |
Some cylc scripts (notably Cylc Play when it is re-invoked on a scheduler |
| 773 |
server) require the correct content in sys.argv: This function |
| 774 |
subtracts the unwanted options from sys.argv. |
| 775 |
|
| 776 |
Args: |
| 777 |
script_name: |
| 778 |
Name of the target script. For example if we are |
| 779 |
using this for the play step of cylc vip then this |
| 780 |
will be "play". |
| 781 |
workflow_id: |
| 782 |
options: |
| 783 |
Actual options provided to the compound script. |
| 784 |
compound_script_options: |
| 785 |
Options available in compound script. |
| 786 |
script_options: |
| 787 |
Options available in target script. |
| 788 |
source: |
| 789 |
Source directory. |
| 790 |
""" |
| 791 |
# Organize Options by dest. |
| 792 |
script_opts_by_dest = { |
| 793 |
x.kwargs.get('dest', x.args[0].strip(DOUBLEDASH)): x |
| 794 |
for x in script_opts |
| 795 |
} |
| 796 |
compound_opts_by_dest = { |
| 797 |
x.kwargs.get('dest', x.args[0].strip(DOUBLEDASH)): x |
| 798 |
for x in compound_script_opts |
| 799 |
} |
| 800 |
|
| 801 |
# Get a list of unwanted args: |
| 802 |
unwanted_compound: List[str] = [] |
| 803 |
unwanted_simple: List[str] = [] |
| 804 |
for unwanted_dest in set(options.__dict__) - set(script_opts_by_dest): |
| 805 |
for unwanted_arg in compound_opts_by_dest[unwanted_dest].args: |
| 806 |
if ( |
| 807 |
compound_opts_by_dest[unwanted_dest].kwargs.get('action', None) |
| 808 |
in ['store_true', 'store_false'] |
| 809 |
): |
| 810 |
unwanted_simple.append(unwanted_arg) |
| 811 |
else: |
| 812 |
unwanted_compound.append(unwanted_arg) |
| 813 |
|
| 814 |
new_args = filter_sysargv(sys.argv, unwanted_simple, unwanted_compound) |
| 815 |
|
| 816 |
# replace compound script name: |
| 817 |
new_args[1] = script_name |
| 818 |
|
| 819 |
# replace source path with workflow ID. |
| 820 |
if str(source) in new_args: |
| 821 |
new_args.remove(str(source)) |
| 822 |
if workflow_id not in new_args: |
| 823 |
new_args.append(workflow_id) |
| 824 |
|
| 825 |
sys.argv = new_args |
| 826 |
|
| 827 |
|
| 828 |
def filter_sysargv( |
| 829 |
sysargs, unwanted_simple: List, unwanted_compound: List |
| 830 |
) -> List: |
| 831 |
"""Create a copy of sys.argv without unwanted arguments: |
| 832 |
|
| 833 |
Cases: |
| 834 |
>>> this = filter_sysargv |
| 835 |
>>> this(['--foo', 'expects-a-value', '--bar'], [], ['--foo']) |
| 836 |
['--bar'] |
| 837 |
>>> this(['--foo=expects-a-value', '--bar'], [], ['--foo']) |
| 838 |
['--bar'] |
| 839 |
>>> this(['--foo', '--bar'], ['--foo'], []) |
| 840 |
['--bar'] |
| 841 |
""" |
| 842 |
pop_next: bool = False |
| 843 |
new_args: List = [] |
| 844 |
for this_arg in sysargs: |
| 845 |
parts = this_arg.split('=', 1) |
| 846 |
if pop_next: |
| 847 |
pop_next = False |
| 848 |
continue |
| 849 |
elif parts[0] in unwanted_compound: |
| 850 |
# Case --foo=value or --foo value |
| 851 |
if len(parts) == 1: |
| 852 |
# --foo value |
| 853 |
pop_next = True |
| 854 |
continue |
| 855 |
elif parts[0] in unwanted_simple: |
| 856 |
# Case --foo does not expect a value: |
| 857 |
continue |
| 858 |
else: |
| 859 |
new_args.append(this_arg) |
| 860 |
return new_args |
| 861 |
|
| 862 |
|
| 863 |
def log_subcommand(*args): |
| 864 |
"""Log a command run as part of a sequence. |
| 865 |
|
| 866 |
Example: |
| 867 |
>>> log_subcommand('ruin', 'my_workflow') |
| 868 |
\x1b[1m\x1b[36m$ cylc ruin my_workflow\x1b[0m\x1b[1m\x1b[0m\n |
| 869 |
""" |
| 870 |
# Args might be posixpath or similar. |
| 871 |
args = [str(a) for a in args] |
| 872 |
print(cparse( |
| 873 |
f'<b><cyan>$ cylc {" ".join(args)}</cyan></b>' |
| 874 |
)) |