diff --git a/.github/workflows/Linter.yml b/.github/workflows/Linter.yml new file mode 100644 index 000000000..c3d82b41e --- /dev/null +++ b/.github/workflows/Linter.yml @@ -0,0 +1,80 @@ +name: Linter +on: + pull_request: + types: [opened, synchronize] +jobs: + Branch: + runs-on: ubuntu-latest + steps: + # If Branch name is not develop, comment + - name: Test Branch Name + if: github.base_ref != 'develop' + uses: mshick/add-pr-comment@v1 + with: + message: | + **Please Set PR to develop. 😊** + repo-token: ${{ secrets.GITHUB_TOKEN }} + C: + runs-on: ubuntu-latest + steps: + # Clone Repository + - name: Checkout + uses: actions/checkout@v2 + # Perform lint on user's files. + - name: User's Lint + run: | + chmod +x style/run-lint.sh + style/run-lint.sh c + Cppcheck: + needs: [Branch] + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Install Requirements + run: | + sudo apt-get install cppcheck=1.82-1 + - name: User's Lint + run: | + chmod +x style/run-lint.sh + style/run-lint.sh cppcheck + Python: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: Install Requirements + run: | + pip install pylint==2.4.4 + - name: Run Pylint + run: | + chmod +x style/run-lint.sh + style/run-lint.sh python + Shell: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Install Requirements + run: | + sudo apt install xz-utils + wget -qO- "https://github.com/koalaman/shellcheck/releases/download/v0.7.0/shellcheck-v0.7.0.linux.x86_64.tar.xz" | tar -xJv + sudo cp "shellcheck-v0.7.0/shellcheck" /usr/bin/ + - name: User's Lint + run: | + chmod +x style/run-lint.sh + style/run-lint.sh shell + Comment: + needs: [Branch,C,Cppcheck,Python,Shell] + runs-on: ubuntu-latest + steps: + - name: Add Comment + uses: mshick/add-pr-comment@v1 + with: + message: | + **All Lint Tests Passed!🚀** + repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 000000000..e8e70d5c0 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,584 @@ +[MASTER] + +# 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= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# 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=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + invalid-name, + bare-except, + duplicate-code, + global-statement, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape + +# 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 (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'error', 'warning', 'refactor', and 'convention' +# which contain the number of messages in each category, as well as 'statement' +# which is the total number of statements analyzed. This score is used by the +# global evaluation report (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# 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= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# 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 + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# 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). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 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 the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# 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 + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# 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 + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# 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 internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# 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=cls + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/.shellcheckrc b/.shellcheckrc new file mode 100644 index 000000000..ee7742cd9 --- /dev/null +++ b/.shellcheckrc @@ -0,0 +1,13 @@ +# Expanding Sourcing Files +disable=SC1090 +# Source File Doesn't Exist +disable=SC1091 + +# Exit On Fail CD +disable=SC2164 + +# Using $? For Exit Code +disable=SC2181 + +# Splitting Array Into Tuple +disable=SC2206 diff --git a/style/git-difftool-changed-lines.sh b/style/git-difftool-changed-lines.sh new file mode 100755 index 000000000..d2a8a8d48 --- /dev/null +++ b/style/git-difftool-changed-lines.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# Don't output info for old (deleted) or unchanged (context) lines +# For new and changed lines, output one LINE_RANGE per line +diff --old-group-format="" --unchanged-group-format="" \ + --new-group-format="%dF-%dL%c'\012'" --changed-group-format="%dF-%dL%c'\012'" \ + "$1" "$2" | while IFS=- read -r LINE END; do + echo -n "$LINE" + + # If there's multiple lines, set a comma beforehand + if [[ ! $LINE == "$END" ]] + then + echo -n " $END" + fi + echo +done diff --git a/style/github-action-style.md b/style/github-action-style.md new file mode 100644 index 000000000..66cbd5188 --- /dev/null +++ b/style/github-action-style.md @@ -0,0 +1,87 @@ +# A CI Static Analysis tool. + +This CI is supported by Github Actions and is triggered when users make pull request to openNetVM. +It's main purpose is to give warnings and suggestions for C, Shell and python scripts. + +Some of the goals of the Linter include: + +* Give feedback to the user's that may have made pull requests to an incorrect branch. + +* Identify places in user's code that *may* not be in non-compliance with [ONVM style rules.](styleguide.md) + +* It does not attempt to fix up these problems but educate. + +## Table of Contents + +* [How it works](#how-it-works) +* [Installing](#installing) +* [How to use](#how-to-use) +* [Github Actions](#github-actions) +* [Other Resources](#other-resources) + +### How it works. + +The Linter can be broken down into a few simple steps. + +* Github Action triggers *run-lint.sh* script. +* Depending on the argument passed in, lint using one of the following static analysis tools: \ + **shellcheck, cppcheck, gwclint.py, pylint** +* Get the name of the files the user has made changes to. +* Get the lines that the user has modified. +* Perform lint on the files using the corresponding linter specified from step two. +* Create a list of errors from the linter's output that only includes lines that has been written/modified by the user. + +## Installing + +* The following three linters need to be installed before you are able to run the linter in your terminal. \ +**pylint 2.4.4** \ +**Cppcheck 1.82** \ +**ShellCheck 0.7.0** + +Run **./style/install-linters.sh** to install the different static tools. + +If you encounter errors during installation, you *may* install the latest version that your OS supports with **pip3 install pylint** and **sudo apt-get install cppcheck** + +* [Other Resources](#other-resources) + +Although the correct linter versions *may* be installed without versions being specified, it's a good idea to manually install the specific versions regardless. +This is especially so as these commands are run every time a new workflow has started. This avoids any surprise build breaks when a new version with new warnings or output formatting is published. + +## How to use + +### From your terminal + +To test the files you would like to be linted, you may run one of the following commands. + +**style/run-lint.sh cppcheck** -- Lints C files with Cppcheck. \ +**style/run-lint.sh c** -- Lints C files for styling errors with gwclint.py. \ +**style/run-lint.sh python** -- Lints Python files with pylint. \ +**style/run-lint.sh shell** -- Lints bash shell script files with shellcheck. + +### Pull requests. + +All four linters are automatically triggered when a pull request has been made. The workflow is synchronized with the current pr and gets automatically restarted if someone has made a push to the current open PR. +Therefore, it is highly suggested to [turn off email notification for githubAction runs.](https://help.github.com/en/github/receiving-notifications-about-activity-on-github/about-email-notifications) + +## Github Actions + +The **.github/workflows/Linter.yml** script is triggered when pull request are opened. The workflow is automatically re-run when a pull request is made. \ +The workflow has five separate jobs that run concurrently. + +* **Branch** -- Checks if the user has made PR to the correct branch. If not, comment on pr to suggest change. +* **Cppcheck** -- Lints C files with Cppcheck. +* **C** -- Lints C files for styling errors with gwclint.py +* **Python** -- Lints Python files with pylint. +* **Shell** -- Lints bash shell script files with shellcheck +* **Comment** -- If all five previous jobs have passed, comment 'All Lint Tests Passed' + + +## Other Resources + +To learn more about how the linters function you may visit one of the following resources. +* https://github.com/koalaman/shellcheck +* https://www.pylint.org/ +* http://cppcheck.sourceforge.net/ + +If you would like to learn more about Github Actions: +* https://help.github.com/en/actions/configuring-and-managing-workflows diff --git a/style/install-linters.sh b/style/install-linters.sh new file mode 100755 index 000000000..0a33e66d5 --- /dev/null +++ b/style/install-linters.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# A script to install static analysis tools pylint, shellcheck, and cppcheck. + +# Install cppcheck-1.82-1 +sudo apt-get install cppcheck=1.82-1 -y +cppcheck --version + +# Install shellcheck-v0.7.0 +sudo apt install xz-utils +wget -qO- "https://github.com/koalaman/shellcheck/releases/download/v0.7.0/shellcheck-v0.7.0.linux.x86_64.tar.xz" | tar -xJv +sudo cp "shellcheck-v0.7.0/shellcheck" /usr/bin/ +rm -r -f shellcheck-v0.7.0 +shellcheck --version + +# Install pylint 2.4.4 +sudo apt install python3-pip +pip3 --version +pip3 install pylint==2.4.4 +echo export PATH="$HOME"/.local/bin:"$PATH" >> ~/.bashrc +echo "Please run source ~/.bashrc" diff --git a/style/run-lint.py b/style/run-lint.py new file mode 100644 index 000000000..3cb89a6b3 --- /dev/null +++ b/style/run-lint.py @@ -0,0 +1,135 @@ +#!/usr/bin/python3 +''' +Run designated linter on files from git diff +Only output errors that were changed in this branch --> upstream/develop +''' +import os +import sys + +def git_changed_files(): + ''' + Run system command to get all C files modified. + Return in an array split by line. + ''' + git_files_cmd = 'git diff --name-only upstream/develop {0}' .format(sys.argv[2]) + return os.popen(git_files_cmd).read().splitlines() + +def git_line_changes(file): + ''' + Run git command to get line changes. + Returns array of strings. + ''' + + git_diff_cmd = 'git difftool --no-prompt --extcmd "./style/git-difftool-changed-lines.sh" \ + -U0 upstream/develop -- ' + return os.popen(git_diff_cmd + file).read().splitlines() + +def gwlint_output(file_name): + ''' + Return output from gwclint and separate into lines for an array + ''' + # Run the specified linter with the input filename. + # Only output lines that contain the specfied filename. + get_python_lint_cmd = '{0} {1} 2>&1\ + | grep -E {1} '.format(sys.argv[1], file_name) + lint_lines = os.popen(get_python_lint_cmd).read().splitlines() + + # If lint with gwclint remove the last line of lint: "Done processing example-filename.c" + if sys.argv[1] == "python ./style/gwclint.py --verbose=2": + lint_lines = lint_lines[:-1] + # If linting with cppcheck, we only want errors. Remove lines such as Checking..." + elif sys.argv[1] == "cppcheck": + cpp_lint_lines = [] + for line in lint_lines: + if "error" in line: + cpp_lint_lines.append(line) + return cpp_lint_lines + return lint_lines + +def get_lint_from_file(lint_file, line_inx): + ''' + Line has to be parsed to find the file line number. + ''' + line = lint_file[line_inx] + number = line.split(":", 2)[1] + + # Cppcheck return return lints in the format [filename.c:488]. + # Remove trailing ']' and set to line number. + if sys.argv[1] == "cppcheck": + number = number[:-1] + # Return both the file line number, and the actual line linted. + + return number, line + +def get_start_end_from_diff(git_diff, line_inx): + ''' + Lines are either in the form of + + or + + Returns a parsed line + ''' + + diffs = git_diff[line_inx].split() + + # Start and end returned (can be the same). + return diffs[0], diffs[-1] + +def log_errors(logfile, all_errors): + ''' + Output list of errors to file line by line. + ''' + + with open(logfile, "w") as linting_out: + + for error in reversed(all_errors): + linting_out.write(error + "\n") + + linting_out.write("Total errors found: {}\n".format(len(all_errors))) + +def run_linter(lint_outfile): + ''' + Run linter only on changed lines, and put errors into lint_outfile. + ''' + + # Grab the files from git diff. + files = git_changed_files() + error_list = [] + # Loop through each changed file. + for modified_file in files: + start = end = error_line = line = None + # Initialize git line change variables. + git_pr_differences = git_line_changes(modified_file) + # Start at last git change. + diff_inx = len(git_pr_differences) - 1 + + # Initialize linter error variables. + file_lint = gwlint_output(modified_file) + # Start at last error in the list. + lint_inx = len(file_lint) - 1 + + # Loop through git diff and linter simultaneously. + # Moves through the lists reversed to potentially end quicker. + while diff_inx >= 0 and lint_inx >= 0: + # Update the indices in the list. + start, end = get_start_end_from_diff(git_pr_differences, diff_inx) + error_line, line = get_lint_from_file(file_lint, lint_inx) + + if int(start) <= int(error_line) <= int(end): + # Found another error, error_line was in range. + error_list.append(line) + # Move to next in the lint output. + lint_inx -= 1 + elif int(error_line) > int(end): + # Move to next from linter. + lint_inx -= 1 + + elif int(error_line) < int(start): + # Move to next git change. + diff_inx -= 1 + if error_list: + # Only output to file if we had errors. + log_errors(lint_outfile, error_list) + +if __name__ == "__main__": + run_linter("linter_out.txt") diff --git a/style/run-lint.sh b/style/run-lint.sh new file mode 100755 index 000000000..f690df267 --- /dev/null +++ b/style/run-lint.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +# A script to run linter functions on updated C/python/bash files. +# This script is triggered by github actions when pull request are created. +# Users may also run this script to lint their file changes before pushing their code. +# Usage: run ./style/run-lint.sh python OR ./style/run-lint.sh c OR ./style/run-lint.sh shell OR ./style/run-lint.sh cppcheck + +# Check if user is in main git repository and correct number of arguments are passed in. +if [[ ! -d .git ]]; then + echo 'Please run in main git repository. Example Usage: ./style/run-lint.sh python'; + exit 1 +fi + +if [[ "$#" -ne 1 ]]; then + echo 'Illegal number of parameters. Example usage: run ./style/run-lint.sh python' + exit 1 +fi + +# If the remote upstream has already been set, update url. Else add upstream then fetch. +git remote set-url upstream https://github.com/sdnfv/openNetVM.git > /dev/null 2>&1 || git remote add upstream https://github.com/sdnfv/openNetVM.git +git fetch upstream + +# Create output log file. +linter_out="linter_out.txt" +touch $linter_out + +case "$1" in + +"python") echo $'Running Python Lint.\n' + python3 "style/run-lint.py" "pylint" "*.py" + ;; +"c") echo $'Running C Lint.\n' + python3 "style/run-lint.py" "python ./style/gwclint.py --verbose=2" "'*.c' '*.cpp' '*.h' | grep -v 'cJSON' | grep -v 'ndpi'" + ;; +"cppcheck") echo $'Running cppcheck Lint.\n' + python3 "style/run-lint.py" "cppcheck" "'*.c' '*.cpp' '*.h' | grep -v 'cJSON' | grep -v 'ndpi'" + ;; +"shell") echo $'Running Shell Lint.\n' + python3 "style/run-lint.py" "shellcheck -f gcc" "*.sh" + ;; +*) echo $'Illegal parameter. Example usage: run ./style/run-lint.sh python' + exit 1 + ;; +esac + +# Check if the linter_out file is empty. If it's not empty, errors are present and the lint exits 1. +if [[ -s $linter_out ]]; then + echo $'\nYour lint results below.\n' + cat "$linter_out" + rm $linter_out + exit 1 +else + echo $'\nNo lint errors.' + rm $linter_out + exit 0 +fi