Determine whether a word is a valid name for a command. Commands cannot include redirection characters, whitespace, or termination characters. They also cannot start with a shortcut. :param word: the word to check as a command :param is_subcommand: Flag whet
(self, word: str, *, is_subcommand: bool = False)
| 348 | self._command_pattern = re.compile(expr) |
| 349 | |
| 350 | def is_valid_command(self, word: str, *, is_subcommand: bool = False) -> tuple[bool, str]: |
| 351 | """Determine whether a word is a valid name for a command. |
| 352 | |
| 353 | Commands cannot include redirection characters, whitespace, |
| 354 | or termination characters. They also cannot start with a |
| 355 | shortcut. |
| 356 | |
| 357 | :param word: the word to check as a command |
| 358 | :param is_subcommand: Flag whether this command name is a subcommand name |
| 359 | :return: a tuple of a boolean and an error string |
| 360 | |
| 361 | If word is not a valid command, return ``False`` and an error string |
| 362 | suitable for inclusion in an error message of your choice:: |
| 363 | |
| 364 | checkit = '>' |
| 365 | valid, errmsg = statement_parser.is_valid_command(checkit) |
| 366 | if not valid: |
| 367 | errmsg = f"alias: {errmsg}" |
| 368 | """ |
| 369 | valid = False |
| 370 | |
| 371 | if not isinstance(word, str): |
| 372 | return False, f"must be a string. Received {type(word)!s} instead" # type: ignore[unreachable] |
| 373 | |
| 374 | if not word: |
| 375 | return False, "cannot be an empty string" |
| 376 | |
| 377 | if word.startswith(constants.COMMENT_CHAR): |
| 378 | return False, "cannot start with the comment character" |
| 379 | |
| 380 | if not is_subcommand: |
| 381 | for shortcut, _ in self.shortcuts: |
| 382 | if word.startswith(shortcut): |
| 383 | # Build an error string with all shortcuts listed |
| 384 | errmsg = "cannot start with a shortcut: " |
| 385 | errmsg += ", ".join(shortcut for (shortcut, _) in self.shortcuts) |
| 386 | return False, errmsg |
| 387 | |
| 388 | errmsg = "cannot contain: whitespace, quotes, " |
| 389 | |
| 390 | errchars = (*constants.REDIRECTION_CHARS, *self.terminators) |
| 391 | errmsg += ", ".join([shlex.quote(x) for x in errchars]) |
| 392 | |
| 393 | match = self._command_pattern.search(word) |
| 394 | if match and word == match.group(1): |
| 395 | valid = True |
| 396 | errmsg = "" |
| 397 | return valid, errmsg |
| 398 | |
| 399 | def tokenize(self, line: str) -> list[str]: |
| 400 | """Lex a string into a list of tokens. Shortcuts and aliases are expanded and comments are removed. |
no outgoing calls