| 1 |
#!/usr/bin/env python3 |
| 2 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 3 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 4 |
# |
| 5 |
# This program is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License as published by |
| 7 |
# the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (at your option) any later version. |
| 9 |
# |
| 10 |
# This program is distributed in the hope that it will be useful, |
| 11 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU General Public License |
| 16 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
"""Cylc configuration linter. |
| 18 |
|
| 19 |
Checks code style, deprecated syntax and other issues. |
| 20 |
|
| 21 |
""" |
| 22 |
# NOTE: docstring needed for `cylc help all` output and docs |
| 23 |
# (if editing check this still comes out as expected) |
| 24 |
|
| 25 |
COP_DOC = """cylc lint [OPTIONS] ARGS |
| 26 |
|
| 27 |
Check .cylc and .rc files for code style, deprecated syntax and other issues. |
| 28 |
|
| 29 |
By default, suggestions are written to stdout. |
| 30 |
|
| 31 |
In-place mode ("-i, --inplace") writes suggestions into the file as comments. |
| 32 |
Commit to version control before using this, in case you want to back out. |
| 33 |
|
| 34 |
A non-zero return code will be returned if any issues are identified. |
| 35 |
This can be overridden by providing the "--exit-zero" flag. |
| 36 |
""" |
| 37 |
|
| 38 |
NOQA = """ |
| 39 |
Individual errors can be ignored using the ``# noqa`` line comment. |
| 40 |
It is good practice to specify specific errors you wish to ignore using |
| 41 |
``# noqa: S002 S007 U999`` |
| 42 |
""" |
| 43 |
|
| 44 |
TOMLDOC = """ |
| 45 |
pyproject.toml configuration: |
| 46 |
[tool.cylc.lint] |
| 47 |
ignore = ['S001', 'S002'] # List of rules to ignore |
| 48 |
exclude = ['etc/foo.cylc'] # List of files to ignore |
| 49 |
rulesets = ['style', '728'] # Sets default rulesets to check |
| 50 |
max-line-length = 130 # Max line length for linting |
| 51 |
""" |
| 52 |
from collections import Counter |
| 53 |
import functools |
| 54 |
from pathlib import Path |
| 55 |
import pkgutil |
| 56 |
import re |
| 57 |
import shutil |
| 58 |
import sys |
| 59 |
from tomllib import ( # type: ignore[no-redef] |
| 60 |
TOMLDecodeError, |
| 61 |
loads as toml_loads, |
| 62 |
) |
| 63 |
from typing import ( |
| 64 |
TYPE_CHECKING, |
| 65 |
Any, |
| 66 |
Callable, |
| 67 |
Counter as CounterType, |
| 68 |
Dict, |
| 69 |
Iterator, |
| 70 |
List, |
| 71 |
Literal, |
| 72 |
Optional, |
| 73 |
Union, |
| 74 |
) |
| 75 |
|
| 76 |
from ansimarkup import parse as cparse |
| 77 |
|
| 78 |
from cylc.flow import ( |
| 79 |
LOG, |
| 80 |
job_runner_handlers, |
| 81 |
) |
| 82 |
from cylc.flow.cfgspec.workflow import ( |
| 83 |
SPEC, |
| 84 |
upg, |
| 85 |
) |
| 86 |
from cylc.flow.exceptions import CylcError |
| 87 |
import cylc.flow.flags |
| 88 |
from cylc.flow.id_cli import parse_id |
| 89 |
from cylc.flow.job_runner_mgr import JobRunnerManager |
| 90 |
from cylc.flow.loggingutil import set_timestamps |
| 91 |
from cylc.flow.option_parsers import ( |
| 92 |
WORKFLOW_ID_OR_PATH_ARG_DOC, |
| 93 |
CylcOptionParser as COP, |
| 94 |
) |
| 95 |
from cylc.flow.parsec.config import ParsecConfig |
| 96 |
from cylc.flow.scripts.cylc import DEAD_ENDS |
| 97 |
from cylc.flow.task_outputs import ( |
| 98 |
TASK_OUTPUT_FAILED, |
| 99 |
TASK_OUTPUT_SUCCEEDED, |
| 100 |
) |
| 101 |
from cylc.flow.terminal import cli_function |
| 102 |
|
| 103 |
|
| 104 |
if TYPE_CHECKING: |
| 105 |
from optparse import Values |
| 106 |
|
| 107 |
|
| 108 |
LINT_TABLE = ['tool', 'cylc', 'lint'] |
| 109 |
LINT_SECTION = '.'.join(LINT_TABLE) |
| 110 |
|
| 111 |
# BACK COMPAT: DEPR_LINT_SECTION |
| 112 |
# url: |
| 113 |
# https://github.com/cylc/cylc-flow/issues/5811 |
| 114 |
# from: |
| 115 |
# 8.1.0 |
| 116 |
# to: |
| 117 |
# 8.3.0 |
| 118 |
# remove at: |
| 119 |
# 8.4.0 ? |
| 120 |
DEPR_LINT_SECTION = 'cylc-lint' |
| 121 |
|
| 122 |
IGNORE = 'ignore' |
| 123 |
EXCLUDE = 'exclude' |
| 124 |
RULESETS = 'rulesets' |
| 125 |
WARN = 'warn' |
| 126 |
MAX_LINE_LENGTH = 'max-line-length' |
| 127 |
|
| 128 |
DEPRECATED_ENV_VARS = { |
| 129 |
'CYLC_SUITE_HOST': 'CYLC_WORKFLOW_HOST', |
| 130 |
'CYLC_SUITE_OWNER': 'CYLC_WORKFLOW_OWNER', |
| 131 |
'CYLC_SUITE_SHARE_DIR': 'CYLC_WORKFLOW_SHARE_DIR', |
| 132 |
'CYLC_SUITE_SHARE_PATH': 'CYLC_WORKFLOW_SHARE_PATH', |
| 133 |
'CYLC_SUITE_NAME': 'CYLC_WORKFLOW_ID', |
| 134 |
'CYLC_SUITE_LOG_DIR': 'CYLC_WORKFLOW_LOG_DIR', |
| 135 |
'CYLC_SUITE_INITIAL_CYCLE_POINT': 'CYLC_WORKFLOW_INITIAL_CYCLE_POINT', |
| 136 |
'CYLC_SUITE_INITIAL_CYCLE_TIME': 'CYLC_WORKFLOW_INITIAL_CYCLE_TIME', |
| 137 |
'CYLC_SUITE_FINAL_CYCLE_POINT': 'CYLC_WORKFLOW_FINAL_CYCLE_POINT', |
| 138 |
'CYLC_SUITE_FINAL_CYCLE_TIME': 'CYLC_WORKFLOW_FINAL_CYCLE_TIME', |
| 139 |
'CYLC_SUITE_WORK_DIR': 'CYLC_WORKFLOW_WORK_DIR', |
| 140 |
'CYLC_SUITE_UUID': 'CYLC_WORKFLOW_UUID', |
| 141 |
'CYLC_SUITE_RUN_DIR': 'CYLC_WORKFLOW_RUN_DIR', |
| 142 |
} |
| 143 |
|
| 144 |
OBSOLETE_ENV_VARS = { |
| 145 |
'CYLC_SUITE_DEF_PATH', |
| 146 |
'CYLC_SUITE_DEF_PATH_ON_SUITE_HOST' |
| 147 |
} |
| 148 |
|
| 149 |
|
| 150 |
DEPRECATED_STRING_TEMPLATES = { |
| 151 |
'suite': ['workflow'], |
| 152 |
'suite_uuid': ['uuid'], |
| 153 |
'batch_sys_name': ['job_runner_name'], |
| 154 |
'batch_sys_job_id': ['job_id'], |
| 155 |
'user@host': ['platform_name'], |
| 156 |
'task_url': ['URL', '(if set in :cylc:conf:`[meta]URL`)'], |
| 157 |
'workflow_url': [ |
| 158 |
'workflow_URL', |
| 159 |
'(if set in :cylc:conf:`[runtime][<namespace>][meta]URL`)', |
| 160 |
], |
| 161 |
} |
| 162 |
|
| 163 |
|
| 164 |
LIST_ITEM = '\n * ' |
| 165 |
FUNCTION = 'function' |
| 166 |
|
| 167 |
# Don't remove deprecated check. |
| 168 |
REMOVED_CHECKS = ['U008'] |
| 169 |
|
| 170 |
|
| 171 |
deprecated_string_templates = { |
| 172 |
key: ( |
| 173 |
re.compile(r'%\(' + key + r'\)s'), |
| 174 |
value |
| 175 |
) |
| 176 |
for key, value in DEPRECATED_STRING_TEMPLATES.items() |
| 177 |
} |
| 178 |
|
| 179 |
|
| 180 |
def get_wallclock_directives(): |
| 181 |
"""Get a set of directives equivalent to execution time limit""" |
| 182 |
job_runner_manager = JobRunnerManager() |
| 183 |
directives = {} |
| 184 |
for module in pkgutil.iter_modules(job_runner_handlers.__path__): |
| 185 |
directive = getattr( |
| 186 |
job_runner_manager._get_sys(module.name), |
| 187 |
'TIME_LIMIT_DIRECTIVE', |
| 188 |
None |
| 189 |
) |
| 190 |
if directive and directive == '-W': |
| 191 |
# LSF directive -W needs to have a particular form to |
| 192 |
# avoid matching PBS directive -W: |
| 193 |
directives[module.name] = re.compile( |
| 194 |
r'^-W\s*=?\s*(\d+:)?\d+[^/]*$') |
| 195 |
elif directive: |
| 196 |
directives[module.name] = re.compile(rf'^{directive}.*') |
| 197 |
return directives |
| 198 |
|
| 199 |
|
| 200 |
WALLCLOCK_DIRECTIVES = get_wallclock_directives() |
| 201 |
|
| 202 |
|
| 203 |
def check_wallclock_directives(line: str) -> Dict[str, str]: |
| 204 |
"""Check for job runner specific directives |
| 205 |
equivalent to exection time limit. |
| 206 |
|
| 207 |
It's recommended that users prefer execution time limit |
| 208 |
because it gives the Cylc scheduler awareness should communications |
| 209 |
with a remote job runner be lost. |
| 210 |
|
| 211 |
Examples: |
| 212 |
>>> this = check_wallclock_directives |
| 213 |
>>> this(' -W 42:22') |
| 214 |
{'directive': '-W 42:22'} |
| 215 |
>>> this(' -W 42:22/hostname') # Legit LSF use case |
| 216 |
{} |
| 217 |
>>> this(' -W 422') |
| 218 |
{'directive': '-W 422'} |
| 219 |
>>> this(' -W foo=42') # Legit PBS use case. |
| 220 |
{} |
| 221 |
>>> this(' -W foo="Hello World"') # Legit PBS use case. |
| 222 |
{} |
| 223 |
>>> this(' -l walltime whatever') |
| 224 |
{'directive': '-l walltime whatever'} |
| 225 |
""" |
| 226 |
for directive in set(WALLCLOCK_DIRECTIVES.values()): |
| 227 |
if directive.findall(line.strip()): |
| 228 |
return {'directive': line.strip()} |
| 229 |
return {} |
| 230 |
|
| 231 |
|
| 232 |
def check_jinja2_no_shebang( |
| 233 |
line: str, |
| 234 |
file: Path, |
| 235 |
function: Callable, |
| 236 |
jinja_shebang: bool = False, |
| 237 |
**kwargs |
| 238 |
): |
| 239 |
"""Check ONLY top level workflow files for jinja without shebangs. |
| 240 |
|
| 241 |
Examples: |
| 242 |
>>> func = re.compile(r'{{').findall |
| 243 |
|
| 244 |
>>> check_jinja2_no_shebang( |
| 245 |
... '{{FOO}}', |
| 246 |
... function=func, jinja_shebang=True, file=Path('foo.cylc')) |
| 247 |
False |
| 248 |
|
| 249 |
>>> check_jinja2_no_shebang( |
| 250 |
... '{{FOO}}', |
| 251 |
... function=func, jinja_shebang=False, file=Path('suite.rc')) |
| 252 |
['{{'] |
| 253 |
""" |
| 254 |
if ( |
| 255 |
jinja_shebang |
| 256 |
or file.name not in {'flow.cylc', 'suite.rc'} |
| 257 |
): |
| 258 |
return False |
| 259 |
return function(line) |
| 260 |
|
| 261 |
|
| 262 |
def check_if_jinja2( |
| 263 |
line: str, |
| 264 |
jinja_shebang: bool, |
| 265 |
function: Callable, |
| 266 |
**kwargs |
| 267 |
): |
| 268 |
"""Run function if Jinja2 switched on. |
| 269 |
|
| 270 |
Examples: |
| 271 |
>>> func = re.compile('foo').findall |
| 272 |
|
| 273 |
>>> check_if_jinja2('barfoo', jinja_shebang=False, function=func) |
| 274 |
False |
| 275 |
|
| 276 |
>>> check_if_jinja2('foofoo', jinja_shebang=True, function=func) |
| 277 |
['foo', 'foo'] |
| 278 |
|
| 279 |
""" |
| 280 |
if jinja_shebang: |
| 281 |
return function(line) |
| 282 |
return False |
| 283 |
|
| 284 |
|
| 285 |
def check_dead_ends(line: str) -> bool: |
| 286 |
"""Check for dead end cylc scripts as defined in cylc.flow.scripts.cylc |
| 287 |
|
| 288 |
Examples: |
| 289 |
# Context: |
| 290 |
# [runtime] |
| 291 |
# [[task]] |
| 292 |
# script = \"\"\" |
| 293 |
|
| 294 |
>>> check_dead_ends(' cylc check-software') |
| 295 |
True |
| 296 |
|
| 297 |
>>> check_dead_ends(' cylc log') |
| 298 |
False |
| 299 |
""" |
| 300 |
return any( |
| 301 |
f'cylc {dead_end}' in line for dead_end in DEAD_ENDS |
| 302 |
) |
| 303 |
|
| 304 |
|
| 305 |
def check_for_deprecated_environment_variables( |
| 306 |
line: str |
| 307 |
) -> Union[bool, dict]: |
| 308 |
"""Warn that environment variables with SUITE in are deprecated |
| 309 |
|
| 310 |
Examples: |
| 311 |
>>> check_for_deprecated_environment_variables('CYLC_SUITE_HOST') |
| 312 |
{'vars': ['CYLC_SUITE_HOST: CYLC_WORKFLOW_HOST']} |
| 313 |
""" |
| 314 |
vars_found = [ |
| 315 |
f'{k}: {v}' for k, v in DEPRECATED_ENV_VARS.items() |
| 316 |
if k in line |
| 317 |
] |
| 318 |
|
| 319 |
if len(vars_found) == 1: |
| 320 |
return {'vars': vars_found} |
| 321 |
elif vars_found: |
| 322 |
return {'vars': '\n * ' + '\n * '.join(vars_found)} |
| 323 |
return False |
| 324 |
|
| 325 |
|
| 326 |
def check_for_obsolete_environment_variables(line: str) -> Dict[str, List]: |
| 327 |
"""Warn that environment variables are obsolete. |
| 328 |
|
| 329 |
Examples: |
| 330 |
|
| 331 |
>>> this = check_for_obsolete_environment_variables |
| 332 |
>>> this('script = echo $CYLC_SUITE_DEF_PATH') |
| 333 |
{'vars': ['CYLC_SUITE_DEF_PATH']} |
| 334 |
>>> this('script = echo "irrelevent"') |
| 335 |
{} |
| 336 |
""" |
| 337 |
vars_found = [i for i in OBSOLETE_ENV_VARS if i in line] |
| 338 |
if vars_found: |
| 339 |
return {'vars': vars_found} |
| 340 |
return {} |
| 341 |
|
| 342 |
|
| 343 |
def check_for_deprecated_task_event_template_vars( |
| 344 |
line: str |
| 345 |
) -> Optional[Dict[str, str]]: |
| 346 |
"""Look for string variables which are no longer supported |
| 347 |
|
| 348 |
Examples: |
| 349 |
>>> this = check_for_deprecated_task_event_template_vars |
| 350 |
|
| 351 |
>>> this('hello = "My name is %(suite)s"') |
| 352 |
{'suggest': '\\n * %(suite)s ⇒ %(workflow)s'} |
| 353 |
|
| 354 |
>>> this('x = %(user@host)s, %(suite)') |
| 355 |
{'suggest': '\\n * %(user@host)s ⇒ %(platform_name)s'} |
| 356 |
|
| 357 |
>>> this('x = %(task_url)s') |
| 358 |
{'suggest': '\\n * %(task_url)s ⇒ %(URL)s (if set in ...)'} |
| 359 |
""" |
| 360 |
result = [ |
| 361 |
f"%({key})s ⇒ %({replacement})s {' '.join(extra)}".rstrip() |
| 362 |
for key, ( |
| 363 |
regex, (replacement, *extra), |
| 364 |
) in deprecated_string_templates.items() |
| 365 |
if regex.findall(line) |
| 366 |
] |
| 367 |
|
| 368 |
if result: |
| 369 |
return {'suggest': LIST_ITEM + LIST_ITEM.join(result)} |
| 370 |
return None |
| 371 |
|
| 372 |
|
| 373 |
BAD_SKIP_OUTS = re.compile(r'outputs\s*=\s*(.*)') |
| 374 |
|
| 375 |
|
| 376 |
def check_skip_mode_outputs(line: str) -> Dict: |
| 377 |
"""Ensure skip mode output setting doesn't include |
| 378 |
succeeded _and_ failed, as they are mutually exclusive. |
| 379 |
|
| 380 |
n.b. |
| 381 |
|
| 382 |
This should be separable from ``[[outputs]]`` because it's a key |
| 383 |
value pair not a section heading. |
| 384 |
|
| 385 |
Examples: |
| 386 |
>>> this = check_skip_mode_outputs |
| 387 |
>>> this('outputs = succeeded, failed') |
| 388 |
{'description': 'are ... together', 'outputs': 'failed...succeeded'} |
| 389 |
""" |
| 390 |
|
| 391 |
outputs = BAD_SKIP_OUTS.findall(line) |
| 392 |
if outputs: |
| 393 |
outputs = [i.strip() for i in outputs[0].split(',')] |
| 394 |
if TASK_OUTPUT_FAILED in outputs and TASK_OUTPUT_SUCCEEDED in outputs: |
| 395 |
return { |
| 396 |
'description': |
| 397 |
'are mutually exclusive and cannot be used together', |
| 398 |
'outputs': f'{TASK_OUTPUT_FAILED} and {TASK_OUTPUT_SUCCEEDED}' |
| 399 |
} |
| 400 |
return {} |
| 401 |
|
| 402 |
|
| 403 |
INDENTATION = re.compile(r'^(\s*)(.*)') |
| 404 |
|
| 405 |
|
| 406 |
def check_indentation(line: str) -> bool: |
| 407 |
"""The key value pair is not indented 4*X spaces |
| 408 |
|
| 409 |
n.b. We test for trailing whitespace and incorrect section indenting |
| 410 |
elsewhere |
| 411 |
|
| 412 |
Examples: |
| 413 |
|
| 414 |
>>> check_indentation('') |
| 415 |
False |
| 416 |
>>> check_indentation(' ') |
| 417 |
False |
| 418 |
>>> check_indentation(' [') |
| 419 |
False |
| 420 |
>>> check_indentation('baz') |
| 421 |
False |
| 422 |
>>> check_indentation(' qux') |
| 423 |
False |
| 424 |
>>> check_indentation(' foo') |
| 425 |
True |
| 426 |
>>> check_indentation(' bar') |
| 427 |
True |
| 428 |
""" |
| 429 |
match = INDENTATION.findall(line)[0] |
| 430 |
if not match[0] or not match[1] or match[1].startswith('['): |
| 431 |
return False |
| 432 |
return bool(len(match[0]) % 4 != 0) |
| 433 |
|
| 434 |
|
| 435 |
INHERIT_REGEX = re.compile(r'\s*inherit\s*=\s*(.*)') |
| 436 |
FAM_NAME_IGNORE_REGEX = re.compile( |
| 437 |
# Stuff we want to ignore when checking for lowercase in family names |
| 438 |
r''' |
| 439 |
# comments |
| 440 |
(?<!{)\#.* |
| 441 |
# or Cylc parameters |
| 442 |
| <[^>]+> |
| 443 |
# or Jinja2 |
| 444 |
| {{.*?}} | {%.*?%} | {\#.*?\#} |
| 445 |
''', |
| 446 |
re.X |
| 447 |
) |
| 448 |
LOWERCASE_REGEX = re.compile(r'[a-z]') |
| 449 |
|
| 450 |
|
| 451 |
def check_lowercase_family_names(line: str) -> bool: |
| 452 |
"""Check for lowercase in family names. |
| 453 |
|
| 454 |
Examples: |
| 455 |
>>> check_lowercase_family_names(' inherit = FOO') |
| 456 |
False |
| 457 |
>>> check_lowercase_family_names(' inherit = foo') |
| 458 |
True |
| 459 |
""" |
| 460 |
match = INHERIT_REGEX.match(line) |
| 461 |
if not match: |
| 462 |
return False |
| 463 |
# Replace stuff we want to ignore with a neutral char (tilde will do): |
| 464 |
content = FAM_NAME_IGNORE_REGEX.sub('~', match.group(1)) |
| 465 |
return any( |
| 466 |
LOWERCASE_REGEX.search(i) |
| 467 |
for i in content.split(',') |
| 468 |
if i.strip(' \'"') not in {'None', 'none', 'root'} |
| 469 |
) |
| 470 |
|
| 471 |
|
| 472 |
CHECK_FOR_OLD_VARS = re.compile( |
| 473 |
r'CYLC_VERSION\s*=\s*\{\{\s*CYLC_VERSION\s*\}\}' |
| 474 |
r'|ROSE_VERSION\s*=\s*\{\{\s*ROSE_VERSION\s*\}\}' |
| 475 |
r'|FCM_VERSION\s*=\s*\{\{\s*FCM_VERSION\s*\}\}' |
| 476 |
) |
| 477 |
|
| 478 |
|
| 479 |
def list_wrapper(line: str, check: Callable) -> Optional[Dict[str, str]]: |
| 480 |
"""Take a line and a check function and return a Dict if there is a |
| 481 |
result, None otherwise. |
| 482 |
|
| 483 |
Returns |
| 484 |
|
| 485 |
Dict, in for {'vars': Error string} |
| 486 |
""" |
| 487 |
result = check(line) |
| 488 |
if result: |
| 489 |
return {'vars': '\n * '.join(result)} |
| 490 |
return None |
| 491 |
|
| 492 |
|
| 493 |
STYLE_GUIDE = ( |
| 494 |
'https://cylc.github.io/cylc-doc/stable/html/workflow-design-guide/' |
| 495 |
'style-guide.html#' |
| 496 |
) |
| 497 |
SECTION2 = r'\[\[\s*{}\s*\]\]' |
| 498 |
SECTION3 = r'\[\[\[\s*{}\s*\]\]\]' |
| 499 |
FILEGLOBS = ['*.rc', '*.cylc'] |
| 500 |
JINJA2_SHEBANG = '#!jinja2' |
| 501 |
DEPENDENCY_SECTION_MSG = { |
| 502 |
'text': ( |
| 503 |
'"[scheduling][dependencies][<recurrence>]graph =" -> ' |
| 504 |
'"[scheduling][graph]<recurrence> ="' |
| 505 |
), |
| 506 |
'rst': ( |
| 507 |
'``[scheduling][dependencies][<recurrence>]graph =`` -> ' |
| 508 |
'``[scheduling][graph]<recurrence> =``' |
| 509 |
) |
| 510 |
} |
| 511 |
JOBANDREMOTE_SECTION_MSG = { |
| 512 |
'text': ( |
| 513 |
'settings in "[runtime][<namespace>][{}]" have been moved to ' |
| 514 |
'"[runtime][<namespace>]" and "global.cylc[platforms]' |
| 515 |
'[<platforms name>]"' |
| 516 |
), |
| 517 |
'rst': ( |
| 518 |
'settings in ``[runtime][<namespace>][{}]`` have been moved to ' |
| 519 |
'``[runtime][<namespace>]`` and ``global.cylc[platforms]' |
| 520 |
'[<platforms name>]``' |
| 521 |
) |
| 522 |
} |
| 523 |
JINJA2_FOUND_WITHOUT_SHEBANG = 'jinja2 found: no shebang (#!jinja2)' |
| 524 |
CHECKS_DESC = { |
| 525 |
'U': '7 to 8 upgrades', |
| 526 |
'A': 'Auto Generated 7 to 8 upgrades', |
| 527 |
'S': 'Style' |
| 528 |
} |
| 529 |
LINE_LEN_NO = 'S012' |
| 530 |
# Checks Dictionary fields: |
| 531 |
# TODO: Consider making the checks an object. |
| 532 |
# Key: A unique reference number. |
| 533 |
# - short: A short description of the issue. |
| 534 |
# - url: A link to a fuller description. |
| 535 |
# - function: A function to use to run the check. |
| 536 |
# - kwargs: We want to pass a set of common kwargs to the check function. |
| 537 |
# - evaluate commented lines: Run this check on commented lines. |
| 538 |
# - rst: An rst description, for use in the Cylc docs. |
| 539 |
STYLE_CHECKS = { |
| 540 |
"S001": { |
| 541 |
'short': 'Use multiple spaces, not tabs', |
| 542 |
'url': STYLE_GUIDE + 'tab-characters', |
| 543 |
FUNCTION: re.compile(r'^\t').findall |
| 544 |
}, |
| 545 |
"S002": { |
| 546 |
'short': 'Item not indented.', |
| 547 |
# Non-indented items should be sections: |
| 548 |
'url': STYLE_GUIDE + 'indentation', |
| 549 |
FUNCTION: re.compile(r'^[^%\{\[|\s]').findall |
| 550 |
}, |
| 551 |
"S003": { |
| 552 |
'short': 'Top level sections should not be indented.', |
| 553 |
'url': STYLE_GUIDE + 'indentation', |
| 554 |
FUNCTION: re.compile(r'^\s+\[[^\[.]*\]').findall |
| 555 |
}, |
| 556 |
"S004": { |
| 557 |
'short': ( |
| 558 |
'Second level sections should be indented exactly ' |
| 559 |
'4 spaces.' |
| 560 |
), |
| 561 |
'url': STYLE_GUIDE + 'indentation', |
| 562 |
FUNCTION: re.compile(r'^(|\s|\s{2,3}|\s{5,})\[\[[^\[.]*\]\]').findall |
| 563 |
}, |
| 564 |
"S005": { |
| 565 |
'short': ( |
| 566 |
'Third level sections should be indented exactly ' |
| 567 |
'8 spaces.' |
| 568 |
), |
| 569 |
'url': STYLE_GUIDE + 'indentation', |
| 570 |
FUNCTION: re.compile(r'^(|\s{1,7}|\s{9,})\[\[\[[^\[.]*\]\]\]').findall |
| 571 |
}, |
| 572 |
"S006": { |
| 573 |
'short': 'trailing whitespace.', |
| 574 |
'url': STYLE_GUIDE + 'trailing-whitespace', |
| 575 |
FUNCTION: re.compile(r'[ \t]$').findall |
| 576 |
}, |
| 577 |
"S007": { |
| 578 |
'short': 'Family name contains lowercase characters.', |
| 579 |
'url': STYLE_GUIDE + 'task-naming-conventions', |
| 580 |
FUNCTION: check_lowercase_family_names, |
| 581 |
}, |
| 582 |
"S008": { |
| 583 |
'short': JINJA2_FOUND_WITHOUT_SHEBANG, |
| 584 |
'url': '', |
| 585 |
'kwargs': True, |
| 586 |
FUNCTION: functools.partial( |
| 587 |
check_jinja2_no_shebang, |
| 588 |
function=re.compile(r'{[{%]').findall |
| 589 |
) |
| 590 |
}, |
| 591 |
"S009": { |
| 592 |
'short': 'Host Selection Script may be redundant with platform', |
| 593 |
'url': ( |
| 594 |
'https://cylc.github.io/cylc-doc/stable/html/7-to-8/' |
| 595 |
'major-changes/platforms.html' |
| 596 |
), |
| 597 |
FUNCTION: re.compile(r'platform\s*=\s*\$\(.*?\)').findall, |
| 598 |
}, |
| 599 |
"S010": { |
| 600 |
'short': 'Using backticks to invoke subshell is deprecated', |
| 601 |
'url': 'https://github.com/cylc/cylc-flow/issues/3825', |
| 602 |
FUNCTION: re.compile(r'platform\s*=\s*(`.*?`)').findall, |
| 603 |
}, |
| 604 |
"S011": { |
| 605 |
'short': 'Cylc will process commented Jinja2!', |
| 606 |
'url': '', |
| 607 |
'kwargs': True, |
| 608 |
'evaluate commented lines': True, |
| 609 |
FUNCTION: functools.partial( |
| 610 |
check_if_jinja2, |
| 611 |
function=re.compile(r'(?<!{)#[^$].*?{[{%]').findall |
| 612 |
) |
| 613 |
}, |
| 614 |
'S012': { |
| 615 |
'short': 'This number is reserved for line length checks', |
| 616 |
}, |
| 617 |
'S013': { |
| 618 |
'short': 'Items should be indented in 4 space blocks.', |
| 619 |
FUNCTION: check_indentation |
| 620 |
}, |
| 621 |
'S014': { |
| 622 |
'short': ( |
| 623 |
'Use ``[runtime][TASK]execution time limit``' |
| 624 |
' rather than job runner directive: ``{directive}``.' |
| 625 |
), |
| 626 |
'url': ''' |
| 627 |
https://cylc.github.io/cylc-doc/stable/html/workflow-design-guide/general-principles.html#task-execution-time-limits |
| 628 |
''', |
| 629 |
'rst': ( |
| 630 |
"Use :cylc:conf:`flow.cylc[runtime][<namespace>]execution " |
| 631 |
"time limit` rather than directly specifying a timeout " |
| 632 |
"directive, otherwise Cylc has no way of knowing when the job " |
| 633 |
"should have finished. Cylc automatically translates the " |
| 634 |
"execution time limit to the correct timeout directive for the " |
| 635 |
"particular job runner.\n\n" |
| 636 |
"See :ref:`design-guide.execution-time-limit`." |
| 637 |
), |
| 638 |
FUNCTION: check_wallclock_directives, |
| 639 |
}, |
| 640 |
'S015': { |
| 641 |
'short': ( |
| 642 |
'``=>`` implies line continuation without ``\\``.' |
| 643 |
), |
| 644 |
FUNCTION: re.compile(r'=>\s*\\').findall |
| 645 |
}, |
| 646 |
'S016': { |
| 647 |
'short': 'Task outputs {outputs}: {description}.', |
| 648 |
FUNCTION: check_skip_mode_outputs |
| 649 |
}, |
| 650 |
'S017': { |
| 651 |
'short': 'Run mode is not live: This task will only appear to run.', |
| 652 |
FUNCTION: re.compile(r'run mode\s*=\s*[^l][^i][^v][^e]$').findall |
| 653 |
}, |
| 654 |
} |
| 655 |
# Subset of deprecations which are tricky (impossible?) to scrape from the |
| 656 |
# upgrader. |
| 657 |
MANUAL_DEPRECATIONS = { |
| 658 |
"U001": { |
| 659 |
'short': ( |
| 660 |
DEPENDENCY_SECTION_MSG['text'] + ' (``[dependencies]`` detected)' |
| 661 |
), |
| 662 |
'url': '', |
| 663 |
'rst': ( |
| 664 |
DEPENDENCY_SECTION_MSG['rst'] + ' (``[dependencies]`` detected)' |
| 665 |
), |
| 666 |
FUNCTION: re.compile(SECTION2.format('dependencies')).findall, |
| 667 |
}, |
| 668 |
"U002": { |
| 669 |
'short': DEPENDENCY_SECTION_MSG['text'] + ' (``graph =`` detected)', |
| 670 |
'url': '', |
| 671 |
'rst': DEPENDENCY_SECTION_MSG['rst'] + ' (``graph =`` detected)', |
| 672 |
FUNCTION: re.compile(r'graph\s*=\s*').findall, |
| 673 |
}, |
| 674 |
"U003": { |
| 675 |
'short': JOBANDREMOTE_SECTION_MSG['text'].format('remote'), |
| 676 |
'url': '', |
| 677 |
'rst': JOBANDREMOTE_SECTION_MSG['rst'].format('remote'), |
| 678 |
FUNCTION: re.compile(SECTION3.format('remote')).findall |
| 679 |
}, |
| 680 |
"U004": { |
| 681 |
'short': JOBANDREMOTE_SECTION_MSG['text'].format('job'), |
| 682 |
'url': '', |
| 683 |
'rst': JOBANDREMOTE_SECTION_MSG['rst'].format('job'), |
| 684 |
FUNCTION: re.compile(SECTION3.format('job')).findall, |
| 685 |
}, |
| 686 |
"U005": { |
| 687 |
'short': ( |
| 688 |
'flow.cylc[runtime][<namespace>][job]batch system -> ' |
| 689 |
'global.cylc[platforms][<platform name>]job runner' |
| 690 |
), |
| 691 |
'url': '', |
| 692 |
'rst': ( |
| 693 |
'``flow.cylc[runtime][<namespace>][job]batch system`` -> ' |
| 694 |
'``global.cylc[platforms][<platform name>]job runner``' |
| 695 |
), |
| 696 |
FUNCTION: re.compile(r'batch system\s*=\s*').findall, |
| 697 |
}, |
| 698 |
"U006": { |
| 699 |
'short': 'Using backticks to invoke subshell will fail at Cylc 8.', |
| 700 |
'url': 'https://github.com/cylc/cylc-flow/issues/3825', |
| 701 |
FUNCTION: re.compile(r'host\s*=\s*(`.*?`)').findall, |
| 702 |
}, |
| 703 |
'U007': { |
| 704 |
'short': ( |
| 705 |
'Use built in platform selection instead of rose host-select.'), |
| 706 |
'url': ''' |
| 707 |
https://cylc.github.io/cylc-doc/stable/html/7-to-8/major-changes/platforms.html |
| 708 |
''', |
| 709 |
FUNCTION: re.compile(r'platform\s*=\s*\$\(\s*rose host-select').findall |
| 710 |
}, |
| 711 |
'U009': { |
| 712 |
'short': 'This line contains an obsolete Cylc CLI command.', |
| 713 |
'url': '', |
| 714 |
FUNCTION: check_dead_ends |
| 715 |
}, |
| 716 |
'U010': { |
| 717 |
'short': 'rose suite-hook is deprecated at Rose 2,', |
| 718 |
'url': '', |
| 719 |
FUNCTION: lambda line: 'rose suite-hook' in line, |
| 720 |
}, |
| 721 |
'U011': { |
| 722 |
'short': 'Leading zeros are no longer valid for Jinja2 integers.', |
| 723 |
'url': ''' |
| 724 |
https://cylc.github.io/cylc-doc/stable/html/7-to-8/major-changes/python-2-3.html#jinja2-integers-with-leading-zeros |
| 725 |
''', |
| 726 |
'kwargs': True, |
| 727 |
FUNCTION: functools.partial( |
| 728 |
check_if_jinja2, |
| 729 |
function=re.compile(r'\{%\s*set\s*.+?\s*=\s*0\d+\s*%\}').findall |
| 730 |
) |
| 731 |
}, |
| 732 |
'U012': { |
| 733 |
'short': ( |
| 734 |
'Deprecated environment variables: {vars}'), |
| 735 |
'rst': ( |
| 736 |
'The following environment variables are deprecated:\n\n' |
| 737 |
'.. list-table::' |
| 738 |
'\n :header-rows: 1' |
| 739 |
'\n\n * - Deprecated Variable' |
| 740 |
'\n - New Variable' |
| 741 |
) + ''.join( |
| 742 |
[ |
| 743 |
f'\n * - ``{old}``\n - ``{new}``' |
| 744 |
for old, new in DEPRECATED_ENV_VARS.items() |
| 745 |
] |
| 746 |
), |
| 747 |
'url': ''' |
| 748 |
https://cylc.github.io/cylc-doc/stable/html/reference/job-script-vars/index.html |
| 749 |
''', |
| 750 |
FUNCTION: check_for_deprecated_environment_variables, |
| 751 |
}, |
| 752 |
'U013': { |
| 753 |
'short': ( |
| 754 |
'Obsolete environment variables: {vars}'), |
| 755 |
'rst': ( |
| 756 |
'The following environment variables are obsolete:\n\n' |
| 757 |
+ ''.join([f'\n * ``{old}``' for old in OBSOLETE_ENV_VARS]) |
| 758 |
), |
| 759 |
'url': ''' |
| 760 |
https://cylc.github.io/cylc-doc/stable/html/reference/job-script-vars/index.html |
| 761 |
''', |
| 762 |
FUNCTION: check_for_obsolete_environment_variables, |
| 763 |
}, |
| 764 |
'U014': { |
| 765 |
'short': 'Use "isodatetime [ref]" instead of "rose date [-c]"', |
| 766 |
'rst': ( |
| 767 |
'For datetime operations in task scripts:\n\n' |
| 768 |
' * Use ``isodatetime`` instead of ``rose date``\n' |
| 769 |
' * Use ``isodatetime ref`` instead of ``rose date -c`` for ' |
| 770 |
'the current cycle point\n' |
| 771 |
), |
| 772 |
'url': ''' |
| 773 |
https://cylc.github.io/cylc-doc/stable/html/7-to-8/cheat-sheet.html#datetime-operations |
| 774 |
''', |
| 775 |
FUNCTION: re.compile(r'rose +date').findall, |
| 776 |
}, |
| 777 |
'U015': { |
| 778 |
'short': ( |
| 779 |
'Deprecated template variables: {suggest}'), |
| 780 |
'rst': ( |
| 781 |
"The following deprecated template variables, mostly used in " |
| 782 |
"event handlers, should be replaced:\n" |
| 783 |
+ ''.join( |
| 784 |
f"\n * ``{old}`` ⇒ ``{new}`` {' '.join(extra)}".rstrip() |
| 785 |
for old, (new, *extra) in DEPRECATED_STRING_TEMPLATES.items() |
| 786 |
) |
| 787 |
), |
| 788 |
'url': ''' |
| 789 |
https://cylc.github.io/cylc-doc/stable/html/user-guide/writing-workflows/runtime.html#task-event-template-variables |
| 790 |
''', |
| 791 |
FUNCTION: check_for_deprecated_task_event_template_vars, |
| 792 |
}, |
| 793 |
'U016': { |
| 794 |
'short': 'Deprecated template vars: {vars}', |
| 795 |
'rst': ( |
| 796 |
'It is no longer necessary to configure the environment variables ' |
| 797 |
'``CYLC_VERSION``, ``ROSE_VERSION`` or ``FCM_VERSION``.' |
| 798 |
), |
| 799 |
'url': ''' |
| 800 |
https://cylc.github.io/cylc-doc/stable/html/plugins/cylc-rose.html#special-variables |
| 801 |
''', |
| 802 |
FUNCTION: functools.partial( |
| 803 |
list_wrapper, check=CHECK_FOR_OLD_VARS.findall), |
| 804 |
}, |
| 805 |
'U017': { |
| 806 |
'short': ( |
| 807 |
'``&`` and ``|`` imply line continuation without ``\\``' |
| 808 |
), |
| 809 |
FUNCTION: re.compile(r'[&|]\s*\\').findall |
| 810 |
}, |
| 811 |
} |
| 812 |
ALL_RULESETS = ['728', 'style', 'all'] |
| 813 |
EXTRA_TOML_VALIDATION = { |
| 814 |
IGNORE: { |
| 815 |
lambda x: re.match(r'[A-Z]\d\d\d', x): |
| 816 |
'{item} not valid: Ignore codes should be in the form X001', |
| 817 |
lambda x: x in parse_checks(['728', 'style']) or x in REMOVED_CHECKS: |
| 818 |
'{item} is a not a known linter code.', |
| 819 |
lambda x: WARN if x in REMOVED_CHECKS else True: |
| 820 |
'{item} is a deprecated linter code', |
| 821 |
}, |
| 822 |
RULESETS: { |
| 823 |
lambda item: item in ALL_RULESETS: |
| 824 |
'{item} not valid: Rulesets can be ' |
| 825 |
'\'728\', \'style\' or \'all\'.' |
| 826 |
}, |
| 827 |
MAX_LINE_LENGTH: { |
| 828 |
lambda x: isinstance(x, int): |
| 829 |
'max-line-length must be an integer.' |
| 830 |
}, |
| 831 |
# consider checking that item is file? |
| 832 |
EXCLUDE: {} |
| 833 |
} |
| 834 |
|
| 835 |
|
| 836 |
def parse_ruleset_option(ruleset: str) -> List[str]: |
| 837 |
if ruleset in {'all', ''}: |
| 838 |
return ['728', 'style'] |
| 839 |
return [ruleset] |
| 840 |
|
| 841 |
|
| 842 |
def get_url(check_meta: Dict) -> str: |
| 843 |
"""Get URL from check data. |
| 844 |
|
| 845 |
If the URL doesn't start with http then prepend with address |
| 846 |
of the 7-to-8 upgrade guide. |
| 847 |
|
| 848 |
Examples: |
| 849 |
>>> get_url({'no': 'url key'}) |
| 850 |
'' |
| 851 |
>>> get_url({'url': ''}) |
| 852 |
'' |
| 853 |
>>> get_url({'url': 'https://www.h2g2.com/'}) |
| 854 |
'https://www.h2g2.com/' |
| 855 |
>>> get_url({'url': 'cheat-sheet.html'}) |
| 856 |
'https://cylc.github.io/cylc-doc/stable/html/7-to-8/cheat-sheet.html' |
| 857 |
""" |
| 858 |
url = check_meta.get('url', '').strip() |
| 859 |
if url and not url.startswith('http'): |
| 860 |
url = ( |
| 861 |
"https://cylc.github.io/cylc-doc/stable/html/7-to-8/" |
| 862 |
+ check_meta['url'] |
| 863 |
) |
| 864 |
return url |
| 865 |
|
| 866 |
|
| 867 |
def validate_toml_items(tomldata): |
| 868 |
"""Check that all tomldata items are lists of strings |
| 869 |
|
| 870 |
Explicitly checks and raises if tomldata not: |
| 871 |
- str in EXTRA_TOML_VALIDATION.keys() |
| 872 |
- item is not a list of strings. |
| 873 |
|
| 874 |
Plus additional validation for each set of values. |
| 875 |
""" |
| 876 |
for key, items in tomldata.items(): |
| 877 |
# Key should only be one of the allowed keys: |
| 878 |
if key not in EXTRA_TOML_VALIDATION.keys(): |
| 879 |
raise CylcError( |
| 880 |
f'Only {[*EXTRA_TOML_VALIDATION.keys()]} ' |
| 881 |
f'allowed as toml sections but you used "{key}"' |
| 882 |
) |
| 883 |
if key != MAX_LINE_LENGTH: |
| 884 |
# Item should be a list... |
| 885 |
if not isinstance(items, list): |
| 886 |
raise CylcError( |
| 887 |
f'{key} should be a list, but was: {items}') |
| 888 |
# ... of strings |
| 889 |
for item in items: |
| 890 |
if not isinstance(item, str): |
| 891 |
raise CylcError( |
| 892 |
f'Config {item} should be a string but ' |
| 893 |
f'is {str(type(item))}' |
| 894 |
) |
| 895 |
for check, message in EXTRA_TOML_VALIDATION[key].items(): |
| 896 |
if not check(item): |
| 897 |
raise CylcError( |
| 898 |
message.format(item=item) |
| 899 |
) |
| 900 |
elif check(item) == WARN: |
| 901 |
LOG.warning(message.format(item=item)) |
| 902 |
return True |
| 903 |
|
| 904 |
|
| 905 |
def get_pyproject_toml(dir_: Path) -> Dict[str, Any]: |
| 906 |
"""if a pyproject.toml file is present open it and return settings. |
| 907 |
""" |
| 908 |
tomlfile = dir_ / 'pyproject.toml' |
| 909 |
tomldata: Dict[str, Union[List[str], int, None]] = { |
| 910 |
RULESETS: [], |
| 911 |
IGNORE: [], |
| 912 |
EXCLUDE: [], |
| 913 |
MAX_LINE_LENGTH: None, |
| 914 |
} |
| 915 |
if tomlfile.is_file(): |
| 916 |
try: |
| 917 |
loadeddata = toml_loads(tomlfile.read_text()) |
| 918 |
except TOMLDecodeError as exc: |
| 919 |
raise CylcError(f'pyproject.toml did not load: {exc}') from None |
| 920 |
|
| 921 |
_tool, _cylc, _lint = LINT_TABLE |
| 922 |
try: |
| 923 |
data = loadeddata[_tool][_cylc][_lint] |
| 924 |
except KeyError: |
| 925 |
if DEPR_LINT_SECTION in loadeddata: |
| 926 |
LOG.warning( |
| 927 |
f"The [{DEPR_LINT_SECTION}] section in pyproject.toml is " |
| 928 |
f"deprecated. Use [{LINT_SECTION}] instead." |
| 929 |
) |
| 930 |
data = loadeddata.get(DEPR_LINT_SECTION, {}) |
| 931 |
tomldata.update(data) |
| 932 |
validate_toml_items(tomldata) |
| 933 |
|
| 934 |
return tomldata |
| 935 |
|
| 936 |
|
| 937 |
def merge_cli_with_tomldata(target: Path, options: 'Values') -> Dict[str, Any]: |
| 938 |
"""Get a list of checks based on the checking options |
| 939 |
|
| 940 |
Args: |
| 941 |
target: Location being linted, in which we might find a |
| 942 |
pyproject.toml file. |
| 943 |
options: Cli Options |
| 944 |
|
| 945 |
This has not been merged with merged with the logic in |
| 946 |
_merge_cli_with_tomldata to keep the testing of file-system touching |
| 947 |
and pure logic separate. |
| 948 |
""" |
| 949 |
ruleset_default = (options.ruleset == '') |
| 950 |
options.ruleset = parse_ruleset_option(options.ruleset) |
| 951 |
tomlopts = get_pyproject_toml(target) |
| 952 |
return _merge_cli_with_tomldata( |
| 953 |
{ |
| 954 |
EXCLUDE: [], |
| 955 |
IGNORE: options.ignores, |
| 956 |
RULESETS: options.ruleset |
| 957 |
}, |
| 958 |
tomlopts, |
| 959 |
ruleset_default |
| 960 |
) |
| 961 |
|
| 962 |
|
| 963 |
def _merge_cli_with_tomldata( |
| 964 |
clidata: Dict[str, Any], |
| 965 |
tomldata: Dict[str, Any], |
| 966 |
override_cli_default_rules: bool = False |
| 967 |
) -> Dict[str, Any]: |
| 968 |
"""Merge options set by pyproject.toml with CLI options. |
| 969 |
|
| 970 |
rulesets: CLI should override toml. |
| 971 |
ignore: CLI and toml should be combined with no duplicates. |
| 972 |
exclude: No CLI equivalent, return toml if any. |
| 973 |
|
| 974 |
Args: |
| 975 |
override_cli_default_rules: If user doesn't specifiy a ruleset use the |
| 976 |
rules from the tomlfile - i.e: if we've set 'rulesets': 'style' |
| 977 |
we probably don't want to get warnings about 728 upgrades by |
| 978 |
default, but only if we ask for it on the CLI. |
| 979 |
|
| 980 |
Examples: |
| 981 |
>>> result = _merge_cli_with_tomldata( |
| 982 |
... {'rulesets': ['foo'], 'ignore': ['R101'], 'exclude': []}, |
| 983 |
... {'rulesets': ['bar'], 'ignore': ['R100'], 'exclude': ['*.bk']}) |
| 984 |
>>> result['ignore'] |
| 985 |
['R100', 'R101'] |
| 986 |
>>> result['rulesets'] |
| 987 |
['foo'] |
| 988 |
>>> result['exclude'] |
| 989 |
['*.bk'] |
| 990 |
""" |
| 991 |
if isinstance(clidata[RULESETS][0], list): |
| 992 |
clidata[RULESETS] = clidata[RULESETS][0] |
| 993 |
|
| 994 |
output: dict[str, Any] = {} |
| 995 |
|
| 996 |
# Combine 'ignore' sections: |
| 997 |
output[IGNORE] = sorted(set(clidata[IGNORE] + tomldata[IGNORE])) |
| 998 |
|
| 999 |
# Replace 'rulesets' from toml with those from CLI if they exist: |
| 1000 |
|
| 1001 |
if override_cli_default_rules: |
| 1002 |
output[RULESETS] = tomldata[RULESETS] or clidata[RULESETS] |
| 1003 |
else: |
| 1004 |
output[RULESETS] = clidata[RULESETS] or tomldata[RULESETS] |
| 1005 |
|
| 1006 |
# Return 'exclude' and 'max-line-length' for the tomldata: |
| 1007 |
output[EXCLUDE] = tomldata[EXCLUDE] |
| 1008 |
output[MAX_LINE_LENGTH] = tomldata.get(MAX_LINE_LENGTH, None) |
| 1009 |
|
| 1010 |
return output |
| 1011 |
|
| 1012 |
|
| 1013 |
def list_to_config(path_, is_section=False): |
| 1014 |
"""Prettify a config list |
| 1015 |
|
| 1016 |
Args: |
| 1017 |
path_: list forming address in the config. |
| 1018 |
is_section: Is this item a section? |
| 1019 |
|
| 1020 |
Examples: |
| 1021 |
>>> list_to_config(['foo', 'bar'], False) |
| 1022 |
'[foo]bar' |
| 1023 |
|
| 1024 |
>>> list_to_config(['foo', 'bar'], True) |
| 1025 |
'[foo][bar]' |
| 1026 |
""" |
| 1027 |
output = '' |
| 1028 |
for item in path_[:-1]: |
| 1029 |
# All but the last item must be sections: |
| 1030 |
output += f'[{item}]' |
| 1031 |
if is_section: |
| 1032 |
# Last item is section: |
| 1033 |
output += f'[{path_[-1]}]' |
| 1034 |
else: |
| 1035 |
# Last item not a section: |
| 1036 |
output += path_[-1] |
| 1037 |
return output |
| 1038 |
|
| 1039 |
|
| 1040 |
def get_upgrader_info(): |
| 1041 |
"""Extract info about obseletions and deprecations from Parsec Objects.""" |
| 1042 |
conf = ParsecConfig(SPEC, upg) |
| 1043 |
upgrades = conf.upgrader(conf.dense, '').upgrades |
| 1044 |
deprecations = {} |
| 1045 |
|
| 1046 |
for upgrades_for_version in upgrades.values(): |
| 1047 |
for index, upgrade in enumerate(upgrades_for_version): |
| 1048 |
# Set a flag indicating that a variable has been moved. |
| 1049 |
is_dep, is_obs = False, False |
| 1050 |
if upgrade['new'] is None: |
| 1051 |
section_name = list_to_config( |
| 1052 |
upgrade["old"], upgrade["is_section"]) |
| 1053 |
short = f'{section_name} - not available at Cylc 8' |
| 1054 |
rst = f'``{section_name}`` is not available at Cylc 8' |
| 1055 |
is_obs = True |
| 1056 |
elif upgrade["old"][-1] == upgrade['new'][-1]: |
| 1057 |
# Where an item with the same name has been moved |
| 1058 |
# a 1 line regex isn't going to work. |
| 1059 |
continue |
| 1060 |
else: |
| 1061 |
old = list_to_config( |
| 1062 |
upgrade["old"], upgrade["is_section"]) |
| 1063 |
new = list_to_config( |
| 1064 |
upgrade["new"], upgrade["is_section"]) |
| 1065 |
short = f'{old} -> {new}' |
| 1066 |
rst = f'``{old}`` is now ``{new}``' |
| 1067 |
is_dep = True |
| 1068 |
|
| 1069 |
# Check whether upgrade is section: |
| 1070 |
if upgrade['is_section'] is True: |
| 1071 |
section_depth = len(upgrade['old']) |
| 1072 |
start = r'\[' * section_depth |
| 1073 |
end = r'\]' * section_depth |
| 1074 |
name = upgrade["old"][-1] |
| 1075 |
expr = fr'{start}\s*{name}\s*{end}\s*$' |
| 1076 |
else: |
| 1077 |
name = upgrade["old"][-1] |
| 1078 |
expr = rf'^\s*{name}\s*=\s*.*' |
| 1079 |
|
| 1080 |
deprecations[f'A{index:03d}'] = { |
| 1081 |
'short': short, |
| 1082 |
'url': '', |
| 1083 |
'rst': rst, |
| 1084 |
FUNCTION: re.compile(expr).findall, |
| 1085 |
'is_obs': is_obs, |
| 1086 |
'is_dep': is_dep, |
| 1087 |
} |
| 1088 |
|
| 1089 |
return deprecations |
| 1090 |
|
| 1091 |
|
| 1092 |
PURPOSE_FILTER_MAP = { |
| 1093 |
'style': 'S', |
| 1094 |
'728': 'UA', |
| 1095 |
} |
| 1096 |
|
| 1097 |
|
| 1098 |
def parse_checks(check_args, ignores=None, max_line_len=None, reference=False): |
| 1099 |
"""Prepare dictionary of checks. |
| 1100 |
|
| 1101 |
Args: |
| 1102 |
check_arg: list of types of checks to run, |
| 1103 |
currently expecting '728' and/or 'style' |
| 1104 |
ignores: list of codes to ignore. |
| 1105 |
max_line_len: Adds a specific style warning for lines longer than |
| 1106 |
this. (If None, rule not enforced) |
| 1107 |
reference: Function is being used to get a reference. If true |
| 1108 |
max-line-length will have a generic message, rather than |
| 1109 |
using any specific value. |
| 1110 |
""" |
| 1111 |
ignores = ignores or [] |
| 1112 |
parsedchecks = {} |
| 1113 |
purpose_filters = [ |
| 1114 |
purpose |
| 1115 |
for arg in check_args |
| 1116 |
for purpose in PURPOSE_FILTER_MAP[arg] |
| 1117 |
] |
| 1118 |
|
| 1119 |
checks = { |
| 1120 |
'S': STYLE_CHECKS, |
| 1121 |
'U': MANUAL_DEPRECATIONS, |
| 1122 |
'A': get_upgrader_info(), |
| 1123 |
} |
| 1124 |
for purpose, ruleset in checks.items(): |
| 1125 |
if purpose in purpose_filters: |
| 1126 |
# Run through the rest of the config items. |
| 1127 |
for index, meta in ruleset.items(): |
| 1128 |
meta.update({'purpose': purpose}) |
| 1129 |
if f'{index}' not in ignores: |
| 1130 |
parsedchecks.update({index: meta}) |
| 1131 |
if 'S' in purpose and LINE_LEN_NO not in ignores: |
| 1132 |
# Special handling for max line length: |
| 1133 |
if not max_line_len: |
| 1134 |
max_line_len = 130 |
| 1135 |
regex = r"^.{" + str(max_line_len) + r"}" |
| 1136 |
if reference: |
| 1137 |
msg = ( |
| 1138 |
'line > ``<max_line_len>`` characters. Max line ' |
| 1139 |
' length set in pyproject.toml (default 130)' |
| 1140 |
) |
| 1141 |
else: |
| 1142 |
msg = f'line > {max_line_len} characters.' |
| 1143 |
parsedchecks[LINE_LEN_NO] = { |
| 1144 |
'short': msg, |
| 1145 |
'url': STYLE_GUIDE + 'line-length-and-continuation', |
| 1146 |
FUNCTION: re.compile(regex).findall, |
| 1147 |
'purpose': 'S' |
| 1148 |
} |
| 1149 |
return parsedchecks |
| 1150 |
|
| 1151 |
|
| 1152 |
def get_index_str(meta: dict, index: str) -> str: |
| 1153 |
"""Printable purpose string - mask useless numbers for auto-generated |
| 1154 |
upgrades.""" |
| 1155 |
if meta.get('is_dep', None): |
| 1156 |
return 'U998' |
| 1157 |
elif meta.get('is_obs', None): |
| 1158 |
return 'U999' |
| 1159 |
else: |
| 1160 |
return f'{index}' |
| 1161 |
|
| 1162 |
|
| 1163 |
def check_cylc_file( |
| 1164 |
file: Path, |
| 1165 |
file_rel: Path, |
| 1166 |
checks: Dict[str, dict], |
| 1167 |
counter: CounterType[str], |
| 1168 |
modify: bool = False, |
| 1169 |
): |
| 1170 |
"""Check A Cylc File for Cylc 7 Config""" |
| 1171 |
with open(file, 'r') as cylc_file: |
| 1172 |
# generator which reads and lints one line at a time |
| 1173 |
linter = lint( |
| 1174 |
file_rel, |
| 1175 |
cylc_file, |
| 1176 |
checks, |
| 1177 |
counter, |
| 1178 |
modify, |
| 1179 |
) |
| 1180 |
|
| 1181 |
if modify: |
| 1182 |
# write modifications into a ".temp" file |
| 1183 |
modify_file_path = file.parent / f'{file.name}.temp' |
| 1184 |
with open(modify_file_path, 'w+') as modify_file: |
| 1185 |
for line in linter: |
| 1186 |
modify_file.write(line) |
| 1187 |
# replace the original with the ".temp" file |
| 1188 |
shutil.move(str(modify_file_path), file) |
| 1189 |
else: |
| 1190 |
for _line in linter: |
| 1191 |
pass |
| 1192 |
|
| 1193 |
|
| 1194 |
def no_qa(line: str, index: str): |
| 1195 |
"""This line has a no-qa comment. |
| 1196 |
|
| 1197 |
Examples: |
| 1198 |
# No comment, no exception: |
| 1199 |
>>> no_qa('foo = bar', 'S001') |
| 1200 |
False |
| 1201 |
|
| 1202 |
# Comment, no error codes, no checking: |
| 1203 |
>>> no_qa('foo = bar # noqa', 'S001') |
| 1204 |
True |
| 1205 |
|
| 1206 |
# Comment, no relevent error codes, no checking: |
| 1207 |
>>> no_qa('foo = bar # noqa: S999, 997', 'S001') |
| 1208 |
False |
| 1209 |
|
| 1210 |
# Comment, relevent error codes, checking: |
| 1211 |
>>> no_qa('foo = bar # noqa: S001 S003', 'S001') |
| 1212 |
True |
| 1213 |
""" |
| 1214 |
NOQA = re.compile(r'.*#\s*[Nn][Oo][Qq][Aa]:?(.*)') |
| 1215 |
noqa = NOQA.findall(line) |
| 1216 |
if noqa and (noqa[0] == '' or index in noqa[0]): |
| 1217 |
return True |
| 1218 |
return False |
| 1219 |
|
| 1220 |
|
| 1221 |
def lint( |
| 1222 |
file_rel: Path, |
| 1223 |
lines: Iterator[str], |
| 1224 |
checks: Dict[str, dict], |
| 1225 |
counter: CounterType[str], |
| 1226 |
modify: bool = False, |
| 1227 |
write: Callable = print |
| 1228 |
) -> Iterator[str]: |
| 1229 |
"""Lint text, one line at a time. |
| 1230 |
|
| 1231 |
Arguments: |
| 1232 |
file_rel: |
| 1233 |
The filepath relative to the workflow configuration directory |
| 1234 |
(used in messages). |
| 1235 |
lines: |
| 1236 |
Iterator which produces one line of text at a time |
| 1237 |
e.g. open(file) or iter(['foo\n', 'bar\n', 'baz\n']. |
| 1238 |
counter: |
| 1239 |
Counter for counting lint hits per category. |
| 1240 |
modify: |
| 1241 |
If True, this generator will yield the file one line at a time |
| 1242 |
with comments inserted to help users fix their lint. |
| 1243 |
write: |
| 1244 |
A function for reporting lint messages. |
| 1245 |
|
| 1246 |
Yields: |
| 1247 |
The original file with added comments when `modify is True`. |
| 1248 |
|
| 1249 |
""" |
| 1250 |
# get the first line |
| 1251 |
line_no = 1 |
| 1252 |
line = next(lines) |
| 1253 |
# check if it is a jinja2 shebang |
| 1254 |
jinja_shebang = line.strip().lower() == JINJA2_SHEBANG |
| 1255 |
|
| 1256 |
while True: |
| 1257 |
# run lint checks against the current line |
| 1258 |
for index, check_meta in checks.items(): |
| 1259 |
# Skip commented line unless check says not to. |
| 1260 |
index_str = get_index_str(check_meta, index) |
| 1261 |
if ( |
| 1262 |
( |
| 1263 |
line.strip().startswith('#') |
| 1264 |
and not check_meta.get('evaluate commented lines', False) |
| 1265 |
) |
| 1266 |
or no_qa(line, index_str) |
| 1267 |
): |
| 1268 |
continue |
| 1269 |
|
| 1270 |
if check_meta.get('kwargs', False): |
| 1271 |
# Use a more complex function with keywords: |
| 1272 |
check_function = functools.partial( |
| 1273 |
check_meta['function'], |
| 1274 |
check_meta=check_meta, |
| 1275 |
file=file_rel, |
| 1276 |
jinja_shebang=jinja_shebang, |
| 1277 |
) |
| 1278 |
else: |
| 1279 |
# Just going to pass the line to the check function: |
| 1280 |
check_function = check_meta['function'] |
| 1281 |
|
| 1282 |
# Run the check: |
| 1283 |
check = check_function(line) |
| 1284 |
|
| 1285 |
if check: |
| 1286 |
# we have lint! |
| 1287 |
if isinstance(check, dict): |
| 1288 |
msg = check_meta['short'].format(**check) |
| 1289 |
else: |
| 1290 |
msg = check_meta['short'] |
| 1291 |
counter[check_meta['purpose']] += 1 |
| 1292 |
if modify: |
| 1293 |
# insert a command to help the user |
| 1294 |
url = get_url(check_meta) |
| 1295 |
|
| 1296 |
yield ( |
| 1297 |
f'# [{index_str}]: ' |
| 1298 |
f'{msg}\n' |
| 1299 |
f'# - see {url}\n' |
| 1300 |
) |
| 1301 |
else: |
| 1302 |
# write a message to inform the user |
| 1303 |
write(cparse( |
| 1304 |
'<yellow>' |
| 1305 |
f'[{index_str}] {file_rel}:{line_no}: {msg}' |
| 1306 |
'</yellow>' |
| 1307 |
)) |
| 1308 |
if modify: |
| 1309 |
yield line |
| 1310 |
|
| 1311 |
try: |
| 1312 |
# get the next line |
| 1313 |
line = next(lines) |
| 1314 |
except StopIteration: |
| 1315 |
# end of interator |
| 1316 |
return |
| 1317 |
line_no += 1 |
| 1318 |
|
| 1319 |
|
| 1320 |
def get_cylc_files( |
| 1321 |
base: Path, exclusions: Union[list, None] = None |
| 1322 |
) -> Iterator[Path]: |
| 1323 |
"""Given a directory yield paths to check.""" |
| 1324 |
exclusions = [] if exclusions is None else exclusions |
| 1325 |
except_these_files = [ |
| 1326 |
file for exclusion in exclusions for file in base.rglob(exclusion)] |
| 1327 |
for rglob in FILEGLOBS: |
| 1328 |
for path in base.rglob(rglob): |
| 1329 |
# Exclude log directory: |
| 1330 |
if ( |
| 1331 |
path.relative_to(base).parts[0] != 'log' |
| 1332 |
and path not in except_these_files |
| 1333 |
): |
| 1334 |
yield path |
| 1335 |
|
| 1336 |
|
| 1337 |
def get_reference(ruleset: str, output_type: 'Literal["text", "rst"]') -> str: |
| 1338 |
"""Fill out a template with all the issues Cylc Lint looks for. |
| 1339 |
""" |
| 1340 |
checks = parse_checks( |
| 1341 |
parse_ruleset_option(ruleset), |
| 1342 |
reference=True |
| 1343 |
) |
| 1344 |
|
| 1345 |
issue_heading_template = ( |
| 1346 |
'\n{url}_\n{underline}\n{summary}\n\n' if output_type == 'rst' else |
| 1347 |
'\n{check}:\n {summary}\n {url}\n\n' |
| 1348 |
) |
| 1349 |
output = '' |
| 1350 |
current_checkset = '' |
| 1351 |
for index, meta in checks.items(): |
| 1352 |
# Check if the purpose has changed - if so create a new |
| 1353 |
# section heading: |
| 1354 |
if meta['purpose'] != current_checkset: |
| 1355 |
current_checkset = meta['purpose'] |
| 1356 |
title = CHECKS_DESC[meta["purpose"]] |
| 1357 |
output += '\n{title}\n{underline}\n'.format( |
| 1358 |
title=title, underline="-" * len(title) |
| 1359 |
) |
| 1360 |
|
| 1361 |
if current_checkset == 'A': |
| 1362 |
output += ( |
| 1363 |
'U998 and U999 represent automatically generated' |
| 1364 |
' sets of deprecations and upgrades.' |
| 1365 |
) |
| 1366 |
|
| 1367 |
# Fill a template with info about the issue. |
| 1368 |
if output_type == 'rst': |
| 1369 |
summary = meta.get("rst", meta['short']) |
| 1370 |
elif output_type == 'text': |
| 1371 |
summary = meta.get("short").replace('``', '') |
| 1372 |
|
| 1373 |
if current_checkset == 'A': |
| 1374 |
# Condensed check summary for auto-generated lint items. |
| 1375 |
if output_type == 'rst': |
| 1376 |
output += '\n' |
| 1377 |
output += '\n* ' + summary |
| 1378 |
else: |
| 1379 |
check = get_index_str(meta, index) |
| 1380 |
template = issue_heading_template |
| 1381 |
url = get_url(meta) |
| 1382 |
if output_type == 'rst': |
| 1383 |
url = f'`{check} <{url}>`' if url else f'{check}' |
| 1384 |
msg = template.format( |
| 1385 |
title=index, |
| 1386 |
check=check, |
| 1387 |
summary=summary, |
| 1388 |
url=url, |
| 1389 |
underline=(len(url) + 1) * '^' |
| 1390 |
) |
| 1391 |
output += msg |
| 1392 |
output += '\n' |
| 1393 |
return output |
| 1394 |
|
| 1395 |
|
| 1396 |
def target_version_check( |
| 1397 |
target: Path, |
| 1398 |
quiet: 'Values', |
| 1399 |
mergedopts: Dict[str, Any] |
| 1400 |
) -> List: |
| 1401 |
""" |
| 1402 |
Check whether target is an upgraded Cylc 8 workflow. |
| 1403 |
|
| 1404 |
If it isn't then we shouldn't run the 7-to-8 checks upon |
| 1405 |
it. |
| 1406 |
|
| 1407 |
If it isn't and the only ruleset requested by the user is '728' |
| 1408 |
we should exit with an error code unless the user has specifically |
| 1409 |
disabled thatr with --exit-zero. |
| 1410 |
""" |
| 1411 |
cylc8 = (target / 'flow.cylc').exists() |
| 1412 |
if not cylc8 and mergedopts[RULESETS] == ['728']: |
| 1413 |
LOG.error( |
| 1414 |
f'{target} not a Cylc 8 workflow: ' |
| 1415 |
'Lint after renaming ' |
| 1416 |
'"suite.rc" to "flow.cylc"' |
| 1417 |
) |
| 1418 |
sys.exit(not quiet) |
| 1419 |
elif not cylc8 and '728' in mergedopts[RULESETS]: |
| 1420 |
check_names = mergedopts[RULESETS] |
| 1421 |
check_names.remove('728') |
| 1422 |
else: |
| 1423 |
check_names = mergedopts[RULESETS] |
| 1424 |
return check_names |
| 1425 |
|
| 1426 |
|
| 1427 |
def get_option_parser() -> COP: |
| 1428 |
parser = COP( |
| 1429 |
( |
| 1430 |
COP_DOC |
| 1431 |
+ NOQA.replace('``', '"') |
| 1432 |
+ TOMLDOC |
| 1433 |
), |
| 1434 |
argdoc=[ |
| 1435 |
COP.optional(WORKFLOW_ID_OR_PATH_ARG_DOC) |
| 1436 |
], |
| 1437 |
) |
| 1438 |
parser.add_option( |
| 1439 |
'--inplace', '-i', |
| 1440 |
help=( |
| 1441 |
'Modify files in place, adding comments to files. ' |
| 1442 |
'If not set, the script will work as a linter' |
| 1443 |
), |
| 1444 |
action='store_true', |
| 1445 |
default=False, |
| 1446 |
) |
| 1447 |
parser.add_option( |
| 1448 |
'--ruleset', '-r', |
| 1449 |
help=( |
| 1450 |
'Set of rules to use: ' |
| 1451 |
'("728", "style", "all")' |
| 1452 |
), |
| 1453 |
default='', |
| 1454 |
choices=["728", "style", "all", ''], |
| 1455 |
dest='ruleset' |
| 1456 |
) |
| 1457 |
parser.add_option( |
| 1458 |
'--list-codes', |
| 1459 |
help=( |
| 1460 |
'List all linter codes.' |
| 1461 |
), |
| 1462 |
action='store_true', |
| 1463 |
default=False, |
| 1464 |
dest='ref_mode' |
| 1465 |
) |
| 1466 |
parser.add_option( |
| 1467 |
'--ignore', '-n', |
| 1468 |
help=( |
| 1469 |
'Ignore this check number.' |
| 1470 |
), |
| 1471 |
action='append', |
| 1472 |
default=[], |
| 1473 |
dest='ignores', |
| 1474 |
metavar="CODE", |
| 1475 |
choices=list(STYLE_CHECKS.keys()) + [LINE_LEN_NO] |
| 1476 |
) |
| 1477 |
parser.add_option( |
| 1478 |
'--exit-zero', |
| 1479 |
help='Exit with status code "0" even if there are issues.', |
| 1480 |
action='store_true', |
| 1481 |
default=False, |
| 1482 |
dest='exit_zero' |
| 1483 |
) |
| 1484 |
|
| 1485 |
return parser |
| 1486 |
|
| 1487 |
|
| 1488 |
@cli_function(get_option_parser) |
| 1489 |
def main(parser: COP, options: 'Values', target=None) -> None: |
| 1490 |
if cylc.flow.flags.verbosity < 2: |
| 1491 |
set_timestamps(LOG, False) |
| 1492 |
|
| 1493 |
if options.ref_mode: |
| 1494 |
print(get_reference(options.ruleset, 'text')) |
| 1495 |
sys.exit(0) |
| 1496 |
|
| 1497 |
# If target not given assume we are looking at PWD: |
| 1498 |
if target is None: |
| 1499 |
target = str(Path.cwd()) |
| 1500 |
|
| 1501 |
# make sure the target is a src/run directory: |
| 1502 |
_, _, target = parse_id( |
| 1503 |
target, |
| 1504 |
src=True, |
| 1505 |
constraint='workflows', |
| 1506 |
) |
| 1507 |
|
| 1508 |
# We want target to be the containing folder, not the flow.cylc |
| 1509 |
# file identified by parse_id: |
| 1510 |
target = target.parent |
| 1511 |
|
| 1512 |
mergedopts = merge_cli_with_tomldata(target, options) |
| 1513 |
|
| 1514 |
check_names = target_version_check( |
| 1515 |
target=target, quiet=options.exit_zero, mergedopts=mergedopts) |
| 1516 |
|
| 1517 |
# Get the checks object. |
| 1518 |
checks = parse_checks( |
| 1519 |
check_names, |
| 1520 |
ignores=mergedopts[IGNORE], |
| 1521 |
max_line_len=mergedopts[MAX_LINE_LENGTH] |
| 1522 |
) |
| 1523 |
|
| 1524 |
# Check each file matching a pattern: |
| 1525 |
counter: CounterType[str] = Counter() |
| 1526 |
for file in get_cylc_files(target, mergedopts[EXCLUDE]): |
| 1527 |
LOG.debug(f'Checking {file}') |
| 1528 |
check_cylc_file( |
| 1529 |
file, |
| 1530 |
file.relative_to(target), |
| 1531 |
checks, |
| 1532 |
counter, |
| 1533 |
options.inplace, |
| 1534 |
) |
| 1535 |
|
| 1536 |
if counter: |
| 1537 |
total_lint_hits = sum(counter.values()) |
| 1538 |
msg = cparse( |
| 1539 |
'\n<yellow>' |
| 1540 |
f'Checked {target} against {check_names} ' |
| 1541 |
f'rules and found {total_lint_hits} issue' |
| 1542 |
f'{"s" if total_lint_hits > 1 else ""}.' |
| 1543 |
'</yellow>' |
| 1544 |
) |
| 1545 |
else: |
| 1546 |
msg = cparse( |
| 1547 |
'<green>' |
| 1548 |
f'Checked {target} against {check_names} rules and ' |
| 1549 |
'found no issues.' |
| 1550 |
'</green>' |
| 1551 |
) |
| 1552 |
|
| 1553 |
print(msg) |
| 1554 |
|
| 1555 |
# Exit with an error code if there were warnings and |
| 1556 |
# if --exit-zero was not set. |
| 1557 |
# Return codes: sys.exit(True) == 1, sys.exit(False) == 0 |
| 1558 |
sys.exit(bool(counter) and not options.exit_zero) |
| 1559 |
|
| 1560 |
|
| 1561 |
# NOTE: use += so that this works with __import__ |
| 1562 |
# (docstring needed for `cylc help all` output) |
| 1563 |
__doc__ += NOQA |
| 1564 |
__doc__ += get_reference('all', 'rst') |