pax_global_header00006660000000000000000000000064145601454020014513gustar00rootroot0000000000000052 comment=3d05abbbcbee9c9b4fc8ceff4778127c342389f8 salt-pylint-2024.2.5/000077500000000000000000000000001456014540200142275ustar00rootroot00000000000000salt-pylint-2024.2.5/.gitignore000066400000000000000000000014041456014540200162160ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .cache nosetests.xml coverage.xml # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ # Auto generated version saltpylint/version.py # nvim backup files *~ # pyenv .python-version salt-pylint-2024.2.5/.pre-commit-config.yaml000066400000000000000000000042131456014540200205100ustar00rootroot00000000000000--- default_language_version: python: python3 exclude: ^(doc/_static/.*|doc/_themes/.*)$ repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-merge-conflict # Check for files that contain merge conflict strings. - id: trailing-whitespace # Trims trailing whitespace. args: - --markdown-linebreak-ext=md - id: mixed-line-ending # Replaces or checks mixed line ending. args: - --fix=lf - id: end-of-file-fixer # Makes sure files end in a newline and only a newline. - id: check-ast # Simply check whether files parse as valid python. - id: check-case-conflict # Check for files with names that would conflict on a # case-insensitive filesystem like MacOS HFS+ or Windows FAT. - id: check-json # Attempts to load all json files to verify syntax. - id: check-symlinks # Checks for symlinks which do not point to anything. - id: debug-statements # Check for debugger imports and py37+ breakpoint() calls in python source. - id: fix-byte-order-marker # removes UTF-8 byte order marker - id: forbid-submodules # forbids any submodules in the repository. - id: fix-encoding-pragma # Remove `# -*- coding: utf-8 -*-` from the top of python files. args: - --remove # ----- Code Formatting and Analysis ----------------------------------------------------------> - repo: https://github.com/charliermarsh/ruff-pre-commit rev: "v0.2.0" hooks: - id: ruff args: - --fix exclude: (.pre-commit-hooks/.*|docs/.*)\.py - repo: https://github.com/psf/black rev: 24.1.1 hooks: - id: black args: [-l 100] exclude: src/saf/version.py - repo: https://github.com/asottile/blacken-docs rev: 1.16.0 hooks: - id: blacken-docs args: [--skip-errors] files: ^(docs/.*\.rst|.*\.py)$ additional_dependencies: - black==24.1.1 # <---- Code Formatting and Analysis ----------------------------------------------------------- salt-pylint-2024.2.5/.pylintrc000066400000000000000000000311501456014540200160740ustar00rootroot00000000000000[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Pickle collected data for later comparisons. persistent=yes # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins=saltpylint.pep8, saltpylint.pep263, saltpylint.strings, saltpylint.fileperms, saltpylint.py3modernize, saltpylint.smartup, saltpylint.minpyver # Use multiple processes to speed up Pylint. jobs=1 # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code extension-pkg-whitelist= # Allow optimization of some AST trees. This will activate a peephole AST # optimizer, which will apply various small optimizations. For instance, it can # be used to obtain the result of joining multiple strings with the addition # operator. Joining a lot of strings can lead to a maximum recursion error in # Pylint and this flag can prevent that. It has one side effect, the resulting # AST will be different than the one from reality. optimize-ast=no # Fileperms Lint Plugin Settings fileperms-default = 0644 fileperms-ignore-paths = setup.py # Py3 Modernize PyLint Plugin Settings modernize-nofix = libmodernize.fixes.fix_dict_six # Minimum Python Version To Enforce minimum-python-version = 3.4 [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=yes # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details #msg-template= [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED confidence= # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" #disable= disable=W0142, C0330, I0011, I0012, W1202, E8402, E8731 # E8121, # E8122, # E8123, # E8124, # E8125, # E8126, # E8127, # E8128 # Disabled Checks # # W0142 (star-args) # W1202 (logging-format-interpolation) Use % formatting in logging functions but pass the % parameters as arguments # E812* All PEP8 E12* # E8402 module level import not at top of file # E8501 PEP8 line too long # E8731 do not assign a lambda expression, use a def # C0330 (bad-continuation) # I0011 (locally-disabling) # I0012 (locally-enabling) # W1202 (logging-format-interpolation) [FORMAT] # Maximum number of characters on a single line. max-line-length=120 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no # List of optional constructs for which whitespace checking is disabled no-space-check=trailing-comma,dict-separator # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format=LF [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format logging-modules=logging [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis ignored-modules= # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members=REQUEST,acl_users,aq_parent [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the name of dummy variables (i.e. expectedly # not used). dummy-variables-rgx=_$|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins=__opts__ # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_,_cb [SPELLING] # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [BASIC] # Required attributes for module, separated by a comma # DEPRECATED in PyLint 2.0 #required-attributes= # List of builtins function names that should not be used, separated by a comma bad-functions=map,filter # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_,log,db # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Include a hint for the correct naming format with invalid-name include-naming-hint=no # Regular expression matching correct attribute names attr-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for attribute names attr-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct variable names variable-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for variable names variable-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct function names function-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for function names function-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct constant names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Naming hint for constant names const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression matching correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Naming hint for module names module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression matching correct argument names argument-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for argument names argument-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct inline iteration names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Naming hint for inline iteration names inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ # Regular expression matching correct class attribute names class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Naming hint for class attribute names class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Regular expression matching correct method names method-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for method names method-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Naming hint for class names class-name-hint=[A-Z_][a-zA-Z0-9]+$ # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=__.*__ # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. # DEPRECATED in PyLint 2.0 #ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict,_fields,_replace,_source,_make [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=stringprep,optparse # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branches=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception salt-pylint-2024.2.5/.testing.pylintrc000066400000000000000000000100671456014540200175540ustar00rootroot00000000000000[MASTER] # Specify a configuration file. rcfile=.pylintrc # Pickle collected data for later comparisons. persistent=no # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins=saltpylint.pep8, saltpylint.pep263, saltpylint.strings, saltpylint.fileperms, saltpylint.py3modernize, saltpylint.smartup, saltpylint.minpyver # Fileperms Lint Plugin Settings fileperms-default = 0644 fileperms-ignore-paths = setup.py # Py3 Modernize PyLint Plugin Settings modernize-nofix = libmodernize.fixes.fix_dict_six # Minimum Python Version To Enforce minimum-python-version = 3.4 [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED confidence= # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" #disable= disable=R, I0011, I0012, I0013, E1101, E1103, C0102, C0103, C0111, C0203, C0204, C0301, C0302, C0330, W0110, W0122, W0142, W0201, W0212, W0404, W0511, W0603, W0612, W0613, W0621, W0622, W0631, W0704, W1202, W1307, F0220, F0401, E8501, E8116, E8121, E8122, E8123, E8124, E8125, E8126, E8127, E8128, E8129, E8131, E8265, E8266, E8402, E8731 # Disabled: # R* [refactoring suggestions & reports] # I0011 (locally-disabling) # I0012 (locally-enabling) # I0013 (file-ignored) # E1101 (no-member) [pylint isn't smart enough] # E1103 (maybe-no-member) # C0102 (blacklisted-name) [because it activates C0103 too] # C0103 (invalid-name) # C0111 (missing-docstring) # C0203 (bad-mcs-method-argument) # C0204 (bad-mcs-classmethod-argument) # C0301 (line-too-long) # C0302 (too-many-lines) # C0330 (bad-continuation) # W0110 (deprecated-lambda) # W0122 (exec-statement) # W0142 (star-args) # W0201 (attribute-defined-outside-init) [done in several places in the codebase] # W0212 (protected-access) # W0404 (reimported) [done intentionally for legit reasons] # W0511 (fixme) [several outstanding instances currently in the codebase] # W0603 (global-statement) # W0612 (unused-variable) [unused return values] # W0613 (unused-argument) # W0621 (redefined-outer-name) # W0622 (redefined-builtin) [many parameter names shadow builtins] # W0631 (undefined-loop-variable) [~3 instances, seem to be okay] # W0704 (pointless-except) [misnomer; "ignores the exception" rather than "pointless"] # F0220 (unresolved-interface) # F0401 (import-error) # W1202 (logging-format-interpolation) Use % formatting in logging functions but pass the % parameters as arguments # W1307 (invalid-format-index) Using invalid lookup key '%s' in format specifier "0['%s']" # # E8116 PEP8 E116: unexpected indentation (comment) # E812* All PEP8 E12* # E8265 PEP8 E265 - block comment should start with "# " # E8266 PEP8 E266 - too many leading '#' for block comment # E8501 PEP8 line too long # E8402 module level import not at top of file # E8731 do not assign a lambda expression, use a def [REPORTS] # Tells whether to display a full report or only the messages reports=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details msg-template='{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}' salt-pylint-2024.2.5/LICENSE000066400000000000000000000260741456014540200152450ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. salt-pylint-2024.2.5/README.md000066400000000000000000000000161456014540200155030ustar00rootroot00000000000000# salt-pylint salt-pylint-2024.2.5/pyproject.toml000066400000000000000000000077201456014540200171510ustar00rootroot00000000000000[build-system] requires = ["setuptools>=50.3.2", "setuptools_scm[toml]>=3.4"] build-backend = "setuptools.build_meta" [tool.setuptools_scm] write_to = "saltpylint/version.py" write_to_template = "# pylint: skip-file\n\n__version__ = \"{version}\"\n" [tool.ruff] line-length = 120 show-fixes = true output-format = "grouped" target-version = "py38" respect-gitignore = true src = [ "saltpylint", "tests", "tools", "examples", ] extend-exclude = [ ".nox/**", ] extend-include = [ "setup.py", "noxfile.py", ] builtins = [ "__opts__", "__salt__", # "__context__", # "__grains__", # "__pillar__", "__salt_system_encoding__", ] [tool.ruff.lint] select = ["ALL"] ignore = [ # D* pydocstyle "D200", # Reformat to one line "D212", # Remove whitespace after opening quotes "COM", # flake8-commas - Black takes care of this "ERA", # eradicate "SIM108", # Use ternary operator `A = X if Y else Z` instead of `if`-`else`-block "PERF203", # `try`-`except` within a loop incurs performance overhead" "PERF401", # Use a list comprehension to create a transformed list "PERF402", # Use `list` or `list.copy` to create a copy of a list "ANN", # Type annotations ] ignore-init-module-imports = true [tool.ruff.lint.per-file-ignores] "**/*.py" = [ "D100", # Missing docstring in public module "D101", # Missing docstring in public class "D102", # Missing docstring in public method "D103", # Missing docstring in public function "D104", # Missing docstring in public package "D107", # Missing docstring in `__init__` "D205", # 1 blank line required between summary line and description "D415", # First line should end with a period, question mark, or exclamation point "PTH", # use pathlib.Path "ARG001", # Unused function argument: * "ARG002", # Unused method argument: * ] "setup.py" = [ "D", ] "noxfile.py" = [ "D", "ANN", "SLF001", "C901", "PLR0912", "DTZ005", "FBT002", "PLR0913", # Too many arguments to function call" "PLR0915", # Too many statements ] "saltpylint/blacklist.py" = [ "BLE001", # Do not catch blind exception: `Exception` ] "saltpylint/thirdparty.py" = [ "BLE001", # Do not catch blind exception: `Exception` ] "tools/**/*.py" = [ "ANN201", # Missing return type annotation for public function" "D104", # Missing docstring in public package "FBT001", # Boolean positional arg in function definition "FBT002", # Boolean default value in function definition ] "tests/**/*.py" = [ "ANN", # Ignore missing type annotations in tests "ARG001", # Unused function argument "DTZ003", # The use of `datetime.datetime.utcnow()` is not allowed, use `datetime.datetime.now(tz=)` instead "PLR2004", # Magic value used in comparison, consider replacing 3 with a constant variable "PT001", # use @pytest.fixture() over @pytest.fixture "PT023", # use @pytest.mark.() over @pytest.mark. "RET504", # Unnecessary variable assignment before `return` statement" "S101", # Ignore the use of 'assert ...' in tests "S603", # `subprocess` call: check for execution of untrusted input "SIM117", # Use a single `with` statement with multiple contexts instead of nested `with` statements "TCH002", # Move third-party import into a type-checking block "TCH003", # Move standard library import `pathlib` into a type-checking block ] [tool.ruff.lint.flake8-quotes] docstring-quotes = "double" [tool.ruff.lint.pydocstyle] # Use Google-style docstrings. convention = "google" [tool.ruff.lint.isort] combine-as-imports = false force-single-line = true known-first-party = ["src"] forced-separate = ["tests"] [tool.ruff.lint.pep8-naming] ignore-names = [ "__virtual__", ] [tool.ruff.lint.pyupgrade] # Preserve types, even if a file imports `from __future__ import annotations`. keep-runtime-typing = true [tool.ruff.lint.mccabe] max-complexity = 45 [tool.ruff.lint.pylint] max-branches = 45 max-returns = 10 max-statements = 100 salt-pylint-2024.2.5/saltpylint/000077500000000000000000000000001456014540200164325ustar00rootroot00000000000000salt-pylint-2024.2.5/saltpylint/__init__.py000066400000000000000000000000001456014540200205310ustar00rootroot00000000000000salt-pylint-2024.2.5/saltpylint/blacklist.py000066400000000000000000000631451456014540200207650ustar00rootroot00000000000000""" saltpylint.blacklist ~~~~~~~~~~~~~~~~~~~~ Checks blacklisted imports and code usage on salt """ import contextlib import fnmatch import os import astroid from pylint.checkers import BaseChecker from pylint.checkers import utils BLACKLISTED_IMPORTS_MSGS = { "E9402": ( "Uses of a blacklisted module %r: %s", "blacklisted-module", "Used a module marked as blacklisted is imported.", ), "E9403": ( "Uses of a blacklisted external module %r: %s", "blacklisted-external-module", "Used a module marked as blacklisted is imported.", ), "E9404": ( "Uses of a blacklisted import %r: %s", "blacklisted-import", "Used an import marked as blacklisted.", ), "E9405": ( "Uses of an external blacklisted import %r: %s", "blacklisted-external-import", "Used an external import marked as blacklisted.", ), "E9406": ( "Uses of blacklisted test module execution code: %s", "blacklisted-test-module-execution", "Uses of blacklisted test module execution code.", ), "E9407": ( "Uses of blacklisted sys.path updating through 'ensure_in_syspath'. " "Please remove the import and any calls to 'ensure_in_syspath()'.", "blacklisted-syspath-update", "Uses of blacklisted sys.path updating through ensure_in_syspath.", ), } class BlacklistedImportsChecker(BaseChecker): name = "blacklisted-imports" msgs = BLACKLISTED_IMPORTS_MSGS priority = -2 def open(self): self.blacklisted_modules = ( "salttesting", "integration", "unit", "mock", "six", "distutils.version", "unittest", "unittest2", ) def visit_import(self, node): """Triggered when an import statement is seen.""" module_filename = node.root().file if fnmatch.fnmatch(module_filename, "__init__.py*") and not fnmatch.fnmatch( module_filename, "test_*.py*", ): return node.root() names = [name for name, _ in node.names] for name in names: self._check_blacklisted_module(node, name) def visit_importfrom(self, node): """Triggered when a from statement is seen.""" module_filename = node.root().file if fnmatch.fnmatch(module_filename, "__init__.py*") and not fnmatch.fnmatch( module_filename, "test_*.py*", ): return basename = node.modname self._check_blacklisted_module(node, basename) def _check_blacklisted_module(self, node, mod_path): """Check if the module is blacklisted.""" for mod_name in self.blacklisted_modules: if mod_path == mod_name or mod_path.startswith(mod_name + "."): names = [] for name, name_as in node.names: if name_as: names.append(f"{name} as {name_as}") else: names.append(name) try: import_from_module = node.modname if import_from_module == "salttesting.helpers": for name in names: if name == "ensure_in_syspath": self.add_message("blacklisted-syspath-update", node=node) continue msg = f"Please use 'from tests.support.helpers import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if import_from_module in ( "salttesting.mock", "mock", "unittest.mock", "unittest2.mock", ): for name in names: msg = f"Please use 'from tests.support.mock import {name}'" if import_from_module in ( "salttesting.mock", "unittest.mock", "unittest2.mock", ): message_id = "blacklisted-module" else: message_id = "blacklisted-external-module" self.add_message(message_id, node=node, args=(mod_path, msg)) continue if import_from_module == "salttesting.parser": for name in names: msg = f"Please use 'from tests.support.parser import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if import_from_module == "salttesting.case": for name in names: msg = f"Please use 'from tests.support.case import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if import_from_module == "salttesting.unit": for name in names: msg = f"Please use 'from tests.support.unit import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if import_from_module.startswith(("unittest", "unittest2")): for name in names: msg = f"Please use 'from tests.support.unit import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if import_from_module == "salttesting.mixins": for name in names: msg = f"Please use 'from tests.support.mixins import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if import_from_module == "six": for name in names: msg = f"Please use 'from salt.ext.six import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if import_from_module == "distutils.version": for name in names: msg = f"Please use 'from salt.utils.versions import {name}'" self.add_message("blacklisted-module", node=node, args=(mod_path, msg)) continue if names: for name in names: if name in ( "TestLoader", "TextTestRunner", "TestCase", "expectedFailure", "TestSuite", "skipIf", "TestResult", ): msg = f"Please use 'from tests.support.unit import {name}'" self.add_message( "blacklisted-module", node=node, args=(mod_path, msg), ) continue if name in ("SaltReturnAssertsMixin", "SaltMinionEventAssertsMixin"): msg = f"Please use 'from tests.support.mixins import {name}'" self.add_message( "blacklisted-module", node=node, args=(mod_path, msg), ) continue if name in ("ModuleCase", "SyndicCase", "ShellCase", "SSHCase"): msg = f"Please use 'from tests.support.case import {name}'" self.add_message( "blacklisted-module", node=node, args=(mod_path, msg), ) continue if name == "run_tests": self.add_message( "blacklisted-test-module-execution", node=node, args=( "Please remove the 'if __name__ == \"__main__\":' section from the " "end of the module" ), ) continue if mod_name in ("integration", "unit"): if name in ( "SYS_TMP_DIR", "TMP", "FILES", "PYEXEC", "MOCKBIN", "SCRIPT_DIR", "TMP_STATE_TREE", "TMP_PRODENV_STATE_TREE", "TMP_CONF_DIR", "TMP_SUB_MINION_CONF_DIR", "TMP_SYNDIC_MINION_CONF_DIR", "TMP_SYNDIC_MASTER_CONF_DIR", "CODE_DIR", "TESTS_DIR", "CONF_DIR", "PILLAR_DIR", "TMP_SCRIPT_DIR", "ENGINES_DIR", "LOG_HANDLERS_DIR", "INTEGRATION_TEST_DIR", ): msg = f"Please use 'from tests.support.paths import {name}'" self.add_message( "blacklisted-import", node=node, args=(mod_path, msg), ) continue self.add_message( "blacklisted-import", node=node, args=( mod_path, f"Please use 'from tests.{mod_path} import {name}'", ), ) continue self.add_message( "blacklisted-module", node=node, args=( mod_path, "Please report this error to SaltStack so we can fix it: " f"Trying to import {name} from {mod_path}", ), ) except AttributeError: if mod_name in ( "integration", "unit", "mock", "six", "distutils.version", "unittest", "unittest2", ): if mod_name in ("integration", "unit"): msg = f"Please use 'import tests.{mod_name} as {mod_name}'" message_id = "blacklisted-import" elif mod_name == "mock": msg = f"Please use 'import tests.support.{mod_name} as {mod_name}'" message_id = "blacklisted-external-import" elif mod_name == "six": msg = f"Please use 'import salt.ext.{name} as {name}'" message_id = "blacklisted-external-import" elif mod_name == "distutils.version": msg = "Please use 'import salt.utils.versions' instead" message_id = "blacklisted-import" elif mod_name.startswith(("unittest", "unittest2")): msg = f"Please use 'import tests.support.unit as {mod_name}' instead" message_id = "blacklisted-import" self.add_message(message_id, node=node, args=(mod_path, msg)) continue msg = f"Please report this error to SaltStack so we can fix it: Trying to import {mod_path}" self.add_message("blacklisted-import", node=node, args=(mod_path, msg)) BLACKLISTED_LOADER_USAGE_MSGS = { "E9501": ( "Blacklisted salt loader dunder usage. Setting dunder attribute %r to module %r. " "Use 'salt.support.mock' and 'patch.dict()' instead.", "unmocked-patch-dunder", "Uses a blacklisted salt loader dunder usage in tests.", ), "E9502": ( "Blacklisted salt loader dunder usage. Setting attribute %r to module %r. " "Use 'salt.support.mock' and 'patch()' instead.", "unmocked-patch", "Uses a blacklisted salt loader dunder usage in tests.", ), "E9503": ( "Blacklisted salt loader dunder usage. Updating dunder attribute %r on module %r. " "Use 'salt.support.mock' and 'patch.dict()' instead.", "unmocked-patch-dunder-update", "Uses a blacklisted salt loader dunder usage in tests.", ), } class BlacklistedLoaderModulesUsageChecker(BaseChecker): name = "blacklisted-unmocked-patching" msgs = BLACKLISTED_LOADER_USAGE_MSGS priority = -2 def open(self): self.process_module = False self.salt_dunders = ( "__opts__", "__salt__", "__runner__", "__context__", "__utils__", "__ext_pillar__", "__thorium__", "__states__", "__serializers__", "__ret__", "__grains__", "__pillar__", "__sdb__", "__proxy__", "__low__", "__orchestration_jid__", "__running__", "__intance_id__", "__lowstate__", "__env__", ) self.imported_salt_modules = {} def close(self): self.process_module = False self.imported_salt_modules = {} def visit_module(self, node): module_filename = node.root().file if not fnmatch.fnmatch(os.path.basename(module_filename), "test_*.py*"): return self.process_module = True def leave_module(self, node): if self.process_module: # Reset self.process_module = False self.imported_salt_modules = {} def visit_import(self, node): """Triggered when an import statement is seen.""" if self.process_module: # Store salt imported modules for module, import_as in node.names: if not module.startswith("salt"): continue if import_as and import_as not in self.imported_salt_modules: self.imported_salt_modules[import_as] = module continue if module not in self.imported_salt_modules: self.imported_salt_modules[module] = module def visit_importfrom(self, node): """Triggered when a from statement is seen.""" if self.process_module: if not node.modname.startswith("salt"): return # Store salt imported modules for module, import_as in node.names: if import_as and import_as not in self.imported_salt_modules: self.imported_salt_modules[import_as] = import_as continue if module not in self.imported_salt_modules: self.imported_salt_modules[module] = module def visit_assign(self, node, *args): if not self.process_module: return node_left = node.targets[0] if isinstance(node_left, astroid.Subscript): # Were're changing an existing attribute if not isinstance(node_left.value, astroid.Attribute): return if node_left.value.attrname in self.salt_dunders: if node_left.value.expr.name in self.imported_salt_modules: self.add_message( "unmocked-patch-dunder-update", node=node, args=( node_left.value.attrname, self.imported_salt_modules[node_left.value.expr.name], ), ) return if not isinstance(node_left, astroid.AssignAttr): return try: if node_left.expr.name not in self.imported_salt_modules: # If attributes are not being set on salt's modules, # leave it alone, for now! return except AttributeError: # This might not be what we're looking for return # we're assigning to an imported salt module! if node_left.attrname in self.salt_dunders: # We're changing salt dunders self.add_message( "unmocked-patch-dunder", node=node, args=(node_left.attrname, self.imported_salt_modules[node_left.expr.name]), ) return # Changing random attributes self.add_message( "unmocked-patch", node=node, args=(node_left.attrname, self.imported_salt_modules[node_left.expr.name]), ) RESOURCE_LEAKAGE_MSGS = { "W8470": ("Resource leakage detected. %s ", "resource-leakage", "Resource leakage detected."), } class ResourceLeakageChecker(BaseChecker): name = "resource-leakage" msgs = RESOURCE_LEAKAGE_MSGS priority = -2 def open(self): self.inside_with_ctx = False def close(self): self.inside_with_ctx = False def visit_with(self, node): self.inside_with_ctx = True def leave_with(self, node): self.inside_with_ctx = False def visit_call(self, node): if isinstance(node.func, astroid.Attribute): if node.func.attrname == "fopen" and self.inside_with_ctx is False: msg = ( "Please call 'salt.utils.files.fopen' using the 'with' context " "manager, otherwise the file handle won't be closed and " "resource leakage will occur." ) self.add_message("resource-leakage", node=node, args=(msg,)) elif ( isinstance(node.func, astroid.Name) and utils.is_builtin(node.func.name) and node.func.name == "open" ): if self.inside_with_ctx: msg = ( "Please use 'with salt.utils.files.fopen()' instead of " "'with open()'. It assures salt does not leak " "file handles." ) else: msg = ( "Please use 'salt.utils.files.fopen()' instead of 'open()' " "using the 'with' context manager, otherwise the file " "handle won't be closed and resource leakage will occur." ) self.add_message("resource-leakage", node=node, args=(msg,)) MOVED_TEST_CASE_CLASSES_MSGS = { "E9490": ( "Moved test case base class detected. %s", "moved-test-case-class", "Moved test case base class detected.", ), "E9491": ( "Moved test case mixin class detected. %s", "moved-test-case-mixin", "Moved test case mixin class detected.", ), } class MovedTestCaseClassChecker(BaseChecker): name = "moved-test-case-class" msgs = MOVED_TEST_CASE_CLASSES_MSGS priority = -2 def open(self): self.process_module = False def close(self): self.process_module = False def visit_module(self, node): module_filename = node.root().file if not fnmatch.fnmatch(os.path.basename(module_filename), "test_*.py*"): return self.process_module = True def leave_module(self, node): if self.process_module: # Reset self.process_module = False def visit_importfrom(self, node): """Triggered when a from statement is seen.""" if self.process_module: if not node.modname.startswith("tests.integration"): return # Store salt imported modules for module, import_as in node.names: if import_as: self._check_moved_imports(node, module, import_as) continue self._check_moved_imports(node, module) def visit_classdef(self, node): for base in node.bases: if not hasattr(base, "attrname"): continue if base.attrname in ("TestCase",): msg = f"Please use 'from tests.support.unit import {base.attrname}'" self.add_message("moved-test-case-class", node=node, args=(msg,)) if base.attrname in ("ModuleCase", "SyndicCase", "ShellCase", "SSHCase"): msg = f"Please use 'from tests.support.case import {base.attrname}'" self.add_message("moved-test-case-class", node=node, args=(msg,)) if base.attrname in ( "AdaptedConfigurationTestCaseMixin", "ShellCaseCommonTestsMixin", "SaltMinionEventAssertsMixin", ): msg = f"Please use 'from tests.support.mixins import {base.attrname}'" self.add_message("moved-test-case-mixin", node=node, args=(msg,)) def _check_moved_imports(self, node, module, import_as=None): for name, name_as in node.names: if name not in ("ModuleCase", "SyndicCase", "ShellCase", "SSHCase"): continue if name_as: msg = f"Please use 'from tests.support.case import {name} as {name_as}'" else: msg = f"Please use 'from tests.support.case import {name}'" self.add_message("moved-test-case-class", node=node, args=(msg,)) BLACKLISTED_FUNCTIONS_MSGS = { "E9601": ( "Use of blacklisted function %s (use %s instead)", "blacklisted-function", "Used a function marked as blacklisted", ), } class BlacklistedFunctionsChecker(BaseChecker): name = "blacklisted-functions" msgs = BLACKLISTED_FUNCTIONS_MSGS priority = -2 max_depth = 20 options = ( ( "blacklisted-functions", { "default": "", "type": "string", "metavar": "bad1=good1,bad2=good2", "help": "List of blacklisted functions and their recommended replacements", }, ), ) def open(self): self.blacklisted_functions = {} blacklist = [x.strip() for x in self.linter.config.blacklisted_functions.split(",")] for item in blacklist: try: key, val = (x.strip() for x in item.split("=")) except ValueError: pass else: self.blacklisted_functions[key] = val def _get_full_name(self, node): try: func = utils.safe_infer(node.func) if func.name.__str__() == "Uninferable": return None except Exception: func = None if func is None: return None ret = [] depth = 0 while func is not None: depth += 1 if depth > self.max_depth: # Prevent endless loop return None try: ret.append(func.name) except AttributeError: return None func = func.parent # ret will contain the levels of the function from last to first (e.g. # ['walk', 'os']. Reverse it and join with dots to get the correct # full name for the function. return ".".join(ret[::-1]) def visit_call(self, node): if self.blacklisted_functions: full_name = self._get_full_name(node) if full_name is not None: with contextlib.suppress(KeyError): self.add_message( "blacklisted-function", node=node, args=(full_name, self.blacklisted_functions[full_name]), ) def register(linter): """Required method to auto register this checker.""" linter.register_checker(ResourceLeakageChecker(linter)) linter.register_checker(BlacklistedImportsChecker(linter)) linter.register_checker(MovedTestCaseClassChecker(linter)) linter.register_checker(BlacklistedLoaderModulesUsageChecker(linter)) linter.register_checker(BlacklistedFunctionsChecker(linter)) salt-pylint-2024.2.5/saltpylint/dunder_del.py000066400000000000000000000015731456014540200211170ustar00rootroot00000000000000from typing import ClassVar from pylint.checkers import BaseChecker WARNING_CODE = "W1701" class DunderDelChecker(BaseChecker): """info: This class is used by pylint that checks if "__del__" is not used if "__del__" is used then a warning will be raised. """ name = "dunder-del" priority = -1 msgs: ClassVar = { WARNING_CODE: ( '"__del__" is not allowed!', "no-dunder-del", '"__del__" is not allowed! A "with" block could be a good solution', ), } def visit_functiondef(self, node): """:param node: info about a function or method :return: None """ if node.name == "__del__": self.add_message(WARNING_CODE, node=node) def register(linter): """Required method to auto register this checker.""" linter.register_checker(DunderDelChecker(linter)) salt-pylint-2024.2.5/saltpylint/fileperms.py000066400000000000000000000106441456014540200207770ustar00rootroot00000000000000""" PyLint File Permissions Check Plugin ==================================== PyLint plugin which checks for specific file permissions """ import glob import os import stat import sys from typing import ClassVar from pylint.checkers import BaseChecker class FilePermsChecker(BaseChecker): """Check for files with undesirable permissions.""" name = "fileperms" msgs: ClassVar = { "E0599": ( "Module file has the wrong file permissions(expected %s): %s", "file-perms", ("Wrong file permissions"), ), } priority = -1 options = ( ( "fileperms-default", { "default": "0644", "type": "string", "metavar": "ZERO_PADDED_PERM", "help": "Desired file permissons. Default: 0644", }, ), ( "fileperms-ignore-paths", { "default": (), "type": "csv", "metavar": "", "help": "File paths to ignore file permission. Glob patterns allowed.", }, ), ) def process_module(self, node): """Process a module.""" for listing in self.config.fileperms_ignore_paths: if node.file.split(f"{os.getcwd()}/")[-1] in glob.glob(listing): # File is ignored, no checking should be done return desired_perm = self.config.fileperms_default if "-" in desired_perm: desired_perm = desired_perm.split("-") else: desired_perm = [desired_perm] if len(desired_perm) > 2: # noqa: PLR2004 msg = "Permission ranges should be like XXXX-YYYY" raise RuntimeError(msg) for idx, _perm in enumerate(desired_perm): desired_perm[idx] = desired_perm[idx].strip('"').strip("'").lstrip("0").zfill(4) if desired_perm[idx][0] != "0": # Always include a leading zero desired_perm[idx] = f"0{desired_perm[idx]}" if desired_perm[idx][1] != "o": desired_perm[idx] = "0o" + desired_perm[idx][1:] if sys.platform.startswith("win"): # Windows does not distinguish between user/group/other. # They must all be the same. Also, Windows will automatically # set the execution bit on files with a known extension # (eg .exe, .bat, .com). So we cannot reliably test the # execution bit on other files such as .py files. user_perm_noexec = int(desired_perm[idx][-3]) if user_perm_noexec % 2 == 1: user_perm_noexec -= 1 desired_perm[idx] = desired_perm[idx][:-3] + (str(user_perm_noexec) * 3) module_perms = oct(stat.S_IMODE(os.stat(node.file).st_mode)) if len(desired_perm) == 1: if module_perms != desired_perm[0]: if sys.platform.startswith("win"): # Check the variant with execution bit set due to the # unreliability of checking the execution bit on Windows. user_perm_noexec = int(desired_perm[0][-3]) desired_perm_exec = desired_perm[0][:-3] + (str(user_perm_noexec + 1) * 3) if module_perms == desired_perm_exec: return self.add_message("E0599", line=1, args=(desired_perm[0], module_perms)) elif module_perms < desired_perm[0] or module_perms > desired_perm[1]: if sys.platform.startswith("win"): # Check the variant with execution bit set due to the # unreliability of checking the execution bit on Windows. user_perm_noexec0 = int(desired_perm[0][-3]) desired_perm_exec0 = desired_perm[0][:-3] + (str(user_perm_noexec0 + 1) * 3) user_perm_noexec1 = int(desired_perm[1][-3]) desired_perm_exec1 = desired_perm[1][:-3] + (str(user_perm_noexec1 + 1) * 3) if desired_perm_exec0 <= module_perms <= desired_perm_exec1: return desired_perm = ">= {} OR <= {}".format(*desired_perm) self.add_message("E0599", line=1, args=(desired_perm, module_perms)) def register(linter): """Required method to auto register this checker.""" linter.register_checker(FilePermsChecker(linter)) salt-pylint-2024.2.5/saltpylint/smartup.py000066400000000000000000000015621456014540200205030ustar00rootroot00000000000000""" Pylint Smartup Transformers =========================== This plugin will register some transform functions which will allow PyLint to better understand some classed used in Salt which trigger, `no-member` and `maybe-no-member` A bridge between the `pep8`_ library and PyLint """ from astroid import MANAGER from astroid import nodes def rootlogger_transform(obj): if obj.name != "RootLogger": return def _inject_method(cls, msg, *args, **kwargs): pass if not hasattr(obj, "trace"): obj.trace = _inject_method if not hasattr(obj, "garbage"): obj.garbage = _inject_method def register(linter): """Register the transformation functions.""" try: MANAGER.register_transform(nodes.Class, rootlogger_transform) except AttributeError: MANAGER.register_transform(nodes.ClassDef, rootlogger_transform) salt-pylint-2024.2.5/saltpylint/thirdparty.py000066400000000000000000000160111456014540200211750ustar00rootroot00000000000000""" saltpylint.thirdparty ~~~~~~~~~~~~~~~~~~~~~ Checks all imports against a list of known and allowed 3rd-party modules and raises a lint error if an import not in that known 3rd-party modules list is not gated. """ import os import pkgutil from typing import ClassVar import astroid import astroid.exceptions from astroid.modutils import is_relative from astroid.modutils import is_standard_module from pylint.checkers import BaseChecker MSGS = { "W8410": ( "3rd-party module import is not gated in a try/except: %r", "3rd-party-module-not-gated", "3rd-party module imported without being gated in a try/except.", ), "C8410": ( "3rd-party local module import is not gated in a try/except: %r. " "Consider importing at the module global scope level and gate it " "in a try/except.", "3rd-party-local-module-not-gated", "3rd-party module locally imported without being gated. Consider importing " "at the module global scope level and gate it in a try/except", ), } def get_import_package(modname): """Return the import package. Given modname is 'salt.utils', returns 'salt' """ return modname.split(".")[0] class ThirdPartyImportsChecker(BaseChecker): name = "3rd-party-imports" msgs = MSGS priority = -2 options = ( ( "allowed-3rd-party-modules", { "default": (), "type": "csv", "metavar": "<3rd-party-modules>", "help": "Known 3rd-party modules which don' require being gated, separated by a comma", }, ), ) known_py3_modules: ClassVar = ["builtins"] unix_modules = ( "posix", "pwd", "spwd", "grp", "crypt", "termios", "tty", "pty", "fcntl", "pipes", "resource", "nis", "syslog", "posixpath", ) win_modules = ("msilib", "msvcrt", "winreg", "winsound", "ntpath") all_modules: ClassVar = {m[1]: m[0] for m in pkgutil.iter_modules()} std_modules_path: ClassVar = all_modules["os"] std_modules: ClassVar = [] for mod, path in all_modules.items(): if path == std_modules_path and mod not in unix_modules + win_modules: std_modules.append(mod) known_std_modules = known_py3_modules + std_modules def __init__(self, linter=None) -> None: BaseChecker.__init__(self, linter) self._inside_try_except = False self._inside_funcdef = False self._inside_if = False self.cwd = None self.allowed_3rd_party_modules = [] def open(self): super().open() self.cwd = os.getcwd() self.allowed_3rd_party_modules = set( self.linter.config.allowed_3rd_party_modules, ) # pylint: disable=no-member # pylint: disable=unused-argument def visit_if(self, node): self._inside_if = True def leave_if(self, node): self._inside_if = True def visit_try(self, node): self._inside_try_except = True def leave_try(self, node): self._inside_try_except = False def visit_functiondef(self, node): self._inside_funcdef = True def leave_functiondef(self, node): self._inside_funcdef = False # pylint: enable=unused-argument def visit_import(self, node): names = [name for name, _ in node.names] for name in names: self._check_third_party_import(node, name) def visit_importfrom(self, node): self._check_third_party_import(node, node.modname) def _check_third_party_import(self, node, modname): if modname in self.known_std_modules: # Don't even care about these return module_file = node.root().file if is_relative(modname, module_file): # Is the import relative to the curent module being checked return base_modname = modname.split(".", 1)[0] import_modname = modname while True: try: imported_module = node.do_import_module(import_modname) if not imported_module: break if imported_module.file.startswith(self.cwd): # This is an import to package under the project being tested return # If we reached this far, we were able to import the module but it's # not considered a module from within the project being checked break except Exception: # pylint: disable=broad-except # This is, for example, from salt.ext.six.moves import Y # Because `moves` is a dynamic/runtime module import_modname = import_modname.rsplit(".", 1)[0] if import_modname == base_modname or not import_modname: break try: if not is_standard_module(modname) and self._inside_try_except is False: if get_import_package(modname) in self.allowed_3rd_party_modules: return if self._inside_if or self._inside_funcdef: message_id = "3rd-party-local-module-not-gated" else: message_id = "3rd-party-module-not-gated" self.add_message(message_id, node=node, args=modname) except astroid.exceptions.AstroidBuildingException: # Failed to import if self._inside_try_except is False: if get_import_package(modname) in self.allowed_3rd_party_modules: return if self._inside_if or self._inside_funcdef: message_id = "3rd-party-local-module-not-gated" else: message_id = "3rd-party-module-not-gated" self.add_message(message_id, node=node, args=modname) except astroid.exceptions.InferenceError: # Failed to import if self._inside_try_except is False: if get_import_package(modname) in self.allowed_3rd_party_modules: return if self._inside_if or self._inside_funcdef: message_id = "3rd-party-local-module-not-gated" else: message_id = "3rd-party-module-not-gated" self.add_message(message_id, node=node, args=modname) except ImportError: # Definitly not a standard library import if self._inside_try_except is False: if get_import_package(modname) in self.allowed_3rd_party_modules: return if self._inside_if or self._inside_funcdef: message_id = "3rd-party-local-module-not-gated" else: message_id = "3rd-party-module-not-gated" self.add_message(message_id, node=node, args=modname) def register(linter): """Required method to auto register this checker.""" linter.register_checker(ThirdPartyImportsChecker(linter)) salt-pylint-2024.2.5/saltpylint/virt.py000066400000000000000000000042421456014540200177720ustar00rootroot00000000000000from typing import ClassVar import astroid from pylint.checkers import BaseChecker VIRT_LOG = "log-in-virtual" class VirtChecker(BaseChecker): """checks for compliance inside __virtual__.""" name = "virt-checker" msgs: ClassVar = { "E1401": ( "Log statement detected inside __virtual__ function. Remove it.", VIRT_LOG, "Loader processes __virtual__ so logging not in scope", ), } options = () priority = -1 def visit_functiondef(self, node): """Verifies no logger statements inside __virtual__.""" if ( not isinstance(node, astroid.FunctionDef) or node.is_method() or node.type != "function" or not node.body ): # only process functions return try: if node.name != "__virtual__": # only need to process the __virtual__ function return except AttributeError: return # walk contents of __virtual__ function for child in node.get_children(): for functions in child.get_children(): if isinstance(functions, astroid.Call) and isinstance( functions.func, astroid.Attribute, ): try: # Inspect each statement for an instance of 'logging' for inferred in functions.func.expr.infer(): try: instance_type = inferred.pytype().split(".")[0] except TypeError: continue if instance_type == "logging": self.add_message(VIRT_LOG, node=functions) # Found logger, don't need to keep processing this line break except AttributeError: # Not a log function return def register(linter): """Required method to auto register this checker.""" linter.register_checker(VirtChecker(linter)) salt-pylint-2024.2.5/setup.cfg000066400000000000000000000030051456014540200160460ustar00rootroot00000000000000[metadata] name = SaltPyLint description = Required PyLint plugins needed in the several SaltStack projects. long_description = file: README.rst long_description_content_type = text/x-rst author = Pedro Algarvio author_email = pedro@algarvio.me url = https://github.com/saltstack/salt-pylint project_urls = Source=https://github.com/saltstack/salt-pylint Tracker=https://github.com/saltstack/salt-pylint/issues Documentation=https://salt-pylint.readthedocs.io license = Apache Software License 2.0 classifiers = Programming Language :: Python Programming Language :: Cython Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Development Status :: 5 - Production/Stable License :: OSI Approved :: Apache Software License Environment :: Console Intended Audience :: Developers Intended Audience :: Information Technology Intended Audience :: System Administrators platforms = unix, linux, osx, cygwin, win32 [options] zip_safe = False include_package_data = True packages = find: python_requires = >= 3.8 setup_requires = setuptools>=50.3.2 setuptools_scm[toml]>=3.4 setuptools-declarative-requirements install_requires = PyLint [options.packages.find] exclude = tests* [bdist_wheel] universal = false [sdist] owner = root group = root salt-pylint-2024.2.5/setup.py000077500000000000000000000001571456014540200157470ustar00rootroot00000000000000#!/usr/bin/env python import setuptools if __name__ == "__main__": setuptools.setup(use_scm_version=True)