diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..8288985 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @miroslavpojer @Zejnilovic @benedeki diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..3aa610b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,25 @@ +--- +name: Bug report +about: Create a report to help us improve +labels: 'bug' + +--- + +## Describe the bug +A clear and concise description of what the bug is. + +## To Reproduce +Steps to reproduce the behavior OR commands run: +1. Go to '...' +2. Click on '....' +3. Enter value '...' +4. See error + +## Expected behavior +A clear and concise description of what you expected to happen. + +## Screenshots +If applicable, add screenshots to help explain your problem. + +## Additional context +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..74a56c3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: Feature request +about: Suggest an idea for this project +labels: 'enhancement' + +--- + +## Background +A clear and concise description of where the limitation lies. + +## Feature +A description of the requested feature. + +## Example [Optional] +A simple example if applicable. + +## Proposed Solution [Optional] +Solution Ideas: +1. +2. +3. diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000..24ba89d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,13 @@ +--- +name: Question +about: Ask a question +labels: 'question' + +--- + +## Background [Optional] +A clear explanation of the reason for raising the question. +This gives us a better understanding of your use cases and how we might accommodate them. + +## Question +A clear and concise inquiry diff --git a/.github/ISSUE_TEMPLATE/spike_task.md b/.github/ISSUE_TEMPLATE/spike_task.md new file mode 100644 index 0000000..d071e81 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/spike_task.md @@ -0,0 +1,36 @@ +--- +name: Spike +about: Issue template for spikes, research and investigation tasks +labels: 'spike' + +--- + +## Background +A clear and concise description of the problem or a topic we need to understand. + +Feel free to add information about why it's needed and what assumptions you have at the moment. + +## Questions To Answer + +1. +2. +3. + +## Desired Outcome + +The list of desired outcomes of this spike ticket. + +```[tasklist] +### Tasks +- [ ] Questions have been answered or we have a clearer idea of how to get to our goal +- [ ] Discussion with the team +- [ ] Documentation +- [ ] Create recommendations and new implementation tickets +- [ ] item here.. +``` + +## Additional Info/Resources [Optional] + +1. +2. +3. diff --git a/.github/workflows/check_pr_release_notes.yml b/.github/workflows/check_pr_release_notes.yml new file mode 100644 index 0000000..0ce19ed --- /dev/null +++ b/.github/workflows/check_pr_release_notes.yml @@ -0,0 +1,87 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +name: Check PR Release Notes in Description + +on: + pull_request: + types: [opened, synchronize, reopened, edited, labeled, unlabeled] + branches: [ master ] + +env: + SKIP_LABEL: 'no RN' + RLS_NOTES_TAG_REGEX: 'Release Notes:' + +jobs: + check-release-notes: + runs-on: ubuntu-latest + + steps: + - name: Get Pull Request Info + id: pr_info + uses: actions/github-script@v7 + with: + script: | + const pr_number = context.payload.pull_request.number; + const pr = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pr_number + }); + const labels = pr.data.labels ? pr.data.labels.map(label => label.name) : []; + + if (labels.includes("${{ env.SKIP_LABEL }}")) { + console.log("Skipping release notes check because '${{ env.SKIP_LABEL }}' label is present."); + core.setOutput("skip_check", 'true'); + core.setOutput("pr_body", ""); + return; + } + + const pr_body = pr.data.body; + if (!pr_body) { + core.setFailed("Pull request description is empty."); + core.setOutput("pr_body", ""); + core.setOutput("skip_check", 'false'); + return; + } + core.setOutput("pr_body", pr_body); + core.setOutput("skip_check", 'false'); + return; + + - name: Skip check if SKIP_LABEL is present + if: steps.pr_info.outputs.skip_check == 'true' + run: echo "Skipping release notes validation." + + - name: Check for 'Release Notes:' and bullet list + if: steps.pr_info.outputs.skip_check == 'false' + run: | + # Extract the body from the previous step + PR_BODY="${{ steps.pr_info.outputs.pr_body }}" + + # Check if "Release Notes:" exists + if ! echo "$PR_BODY" | grep -q '${{ env.RLS_NOTES_TAG_REGEX }}'; then + echo "Error: release notes tag not found in pull request description. Has to adhere to format '${{ env.RLS_NOTES_TAG_REGEX }}'." + exit 1 + fi + + # Extract text after "Release Notes:" line + TEXT_BELOW_RELEASE_NOTES_TAG=$(echo "$PR_BODY" | sed -n '/${{ env.RLS_NOTES_TAG_REGEX }}/,$p' | tail -n +2) + + # Check if there's a bullet list (lines starting with '-', '+' or '*') + if ! echo "$TEXT_BELOW_RELEASE_NOTES_TAG" | grep -qE '^\s*[-+*]\s+.+$'; then + echo "Error: No bullet list found under release notes tag." + exit 1 + fi diff --git a/.github/workflows/release_draft.yml b/.github/workflows/release_draft.yml new file mode 100644 index 0000000..82662f5 --- /dev/null +++ b/.github/workflows/release_draft.yml @@ -0,0 +1,117 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +name: Release - create draft release +on: + workflow_dispatch: + inputs: + tag-name: + description: 'Name of git version tag to be created, and then draft release created. Syntax: "v[0-9]+.[0-9]+.[0-9]+".' + required: true + +jobs: + check-tag: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-python@v5.1.1 + with: + python-version: '3.11' + + - name: Version Tag Check + id: version_tag_check + uses: AbsaOSS/version-tag-check@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + github-repository: ${{ github.repository }} + version-tag: ${{ github.event.inputs.tag-name }} + branch: 'master' + fails-on-error: 'true' + + release-draft: + needs: check-tag + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-python@v5.1.1 + with: + python-version: '3.11' + + - name: Generate Release Notes + id: generate_release_notes + uses: AbsaOSS/generate-release-notes@v0.4.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag-name: ${{ github.event.inputs.tag-name }} + chapters: '[ + {"title": "No entry 🚫", "label": "duplicate"}, + {"title": "No entry 🚫", "label": "invalid"}, + {"title": "No entry 🚫", "label": "wontfix"}, + {"title": "No entry 🚫", "label": "no RN"}, + {"title": "Breaking Changes 💥", "label": "breaking-change"}, + {"title": "New Features 🎉", "label": "enhancement"}, + {"title": "New Features 🎉", "label": "feature"}, + {"title": "Bugfixes 🛠", "label": "bug"}, + {"title": "Infrastructure ⚙️", "label": "infrastructure"}, + {"title": "Silent-live 🤫", "label": "silent-live"}, + {"title": "Documentation 📜", "label": "documentation"} + ]' + skip-release-notes-label: 'no RN' + verbose: true + + warnings: true + print-empty-chapters: true + + + - name: Create and Push Tag + uses: actions/github-script@v7 + with: + script: | + const tag = core.getInput('tag-name') + const ref = `refs/tags/${tag}`; + const sha = context.sha; // The SHA of the commit to tag + + await github.rest.git.createRef({ + owner: context.repo.owner, + repo: context.repo.repo, + ref: ref, + sha: sha + }); + + console.log(`Tag created: ${tag}`); + github-token: ${{ secrets.GITHUB_TOKEN }} + tag-name: ${{ github.event.inputs.tag-name }} + + - name: Create Draft Release + uses: softprops/action-gh-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + name: ${{ github.event.inputs.tag-name }} + body: ${{ steps.generate_release_notes.outputs.release-notes }} + tag_name: ${{ github.event.inputs.tag-name }} + draft: true + prerelease: false diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..fd653ea --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,150 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +name: Test +on: + pull_request: + branches: + - '**' + types: [ opened, synchronize, reopened ] + +jobs: + static-code-analysis: + runs-on: ubuntu-latest + name: Pylint Static Code Analysis + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + cache: 'pip' + + - name: Install dependencies + run: | + pip install -r requirements.txt + + - name: Analyze code with Pylint + id: analyze-code + run: | + pylint_score=$(pylint $(git ls-files '*.py')| grep 'rated at' | awk '{print $7}' | cut -d'/' -f1) + echo "PYLINT_SCORE=$pylint_score" >> $GITHUB_ENV + + - name: Check Pylint score + run: | + if (( $(echo "$PYLINT_SCORE < 9.5" | bc -l) )); then + echo "Failure: Pylint score is below 9.5 (project score: $PYLINT_SCORE)." + exit 1 + else + echo "Success: Pylint score is above 9.5 (project score: $PYLINT_SCORE)." + fi + + code-format-check: + runs-on: ubuntu-latest + name: Black Format Check + steps: + - name: Checkout repository + uses: actions/checkout@v4.1.5 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@v5.1.0 + with: + python-version: '3.11' + cache: 'pip' + + - name: Install dependencies + run: | + pip install -r requirements.txt + + - name: Check code format with Black + id: check-format + run: | + black --check $(git ls-files '*.py') + + unit-test: + name: Unit Tests + runs-on: ubuntu-latest + + defaults: + run: + shell: bash + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + cache: 'pip' + + - name: Install Python dependencies + run: | + pip install -r requirements.txt + + - name: Set PYTHONPATH environment variable + run: echo "PYTHONPATH=${GITHUB_WORKSPACE}/version_tag_check/version_tag_check" >> $GITHUB_ENV + + - name: Build and run unit tests + run: pytest --cov=. --cov-report=html tests/ -vv + + - name: Check overall coverage + run: | + coverage report --fail-under=80 + coverage xml -o coverage_overall.xml + + - name: Check changed files coverage + run: | + # Get the list of changed Python files + CHANGED_FILES=$(git diff --name-only --diff-filter=AMR ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | grep '.py$' || true) + echo "Changed Python files: $CHANGED_FILES" + + # If no Python files have changed, skip the coverage check + if [ -z "$CHANGED_FILES" ]; then + echo "No Python files have changed. Skipping coverage check for changed files." + exit 0 + fi + + # Convert list to comma-delimited string + CHANGED_FILES=$(echo "$CHANGED_FILES" | awk '{printf "%s,", $0} END {print ""}' | sed 's/,$//') + + # Generate coverage report for changed files + coverage report --include="$CHANGED_FILES" > coverage_report.txt + echo -e "\nChanged Python files report:\n\n" + cat coverage_report.txt + + # Fail if the coverage for changed files is below threshold + COVERAGE_TOTAL=$(awk '/TOTAL/ {print $4}' coverage_report.txt) + echo "Total coverage for changed files: $COVERAGE_TOTAL" + + if (( $(echo "$COVERAGE_TOTAL < 80.0" | bc -l) )); then + echo "Coverage is below 80%" + exit 1 + fi + + - name: Upload coverage report + uses: actions/upload-artifact@v3 + with: + name: coverage-report + path: coverage_overall.xml diff --git a/.gitignore b/.gitignore index 82f9275..7b6caf3 100644 --- a/.gitignore +++ b/.gitignore @@ -159,4 +159,4 @@ cython_debug/ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ +.idea/ diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..04256cb --- /dev/null +++ b/.pylintrc @@ -0,0 +1,649 @@ +[MAIN] + +# 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 + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# 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-allow-list= + +# 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. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked and +# will not be imported (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= + +# 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, and will cap the count on Windows to +# avoid hangs. +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 + +# Resolve imports to .pyi stubs if available. May reduce no-member messages and +# increase not-an-iterable messages. +prefer-stubs=no + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.11 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots= + +# 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 + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[MASTER] + +ignore-paths=tests + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# 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. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set 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. If left empty, constant names will be checked with the set 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. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# 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. If left empty, inline iteration names will be checked +# with the set 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. If left empty, method names will be checked with the set 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. If left empty, module names will be checked with the set 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 + +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +#typealias-rgx= + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# 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 + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=10 + +# Maximum number of attributes for a class (see R0902). +max-attributes=8 + +# 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 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[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=120 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# 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 + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to 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= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# 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 re-enable 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=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero + +# 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= + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[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,argparse.parse_error + +# Let 'consider-using-join' be raised when the separator to join on would be +# non-empty (resulting in expected fixes of the type: ``"- " + " - +# ".join(items)``) +suggest-join-with-non-empty-separator=yes + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' 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=max(0, 0 if fatal else 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, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# 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 + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[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 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 symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# 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,argparse.Namespace + +# 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 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[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 names allowed to shadow builtins +allowed-redefined-builtins= + +# 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. +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 diff --git a/README.md b/README.md index e8a355a..3a061b4 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,242 @@ -# release-notes-presence-check -A GH action for validating presence of release notes. +# Release Notes Presence Checker + +A GH action for validating the presence of release notes in pull requests. + +## Motivation + +This action is designed to help maintainers and contributors ensure that release notes are present in pull requests. It can be used to prevent common issues such as: +- Missing release notes +- Incomplete release notes +- Incorrect release note formats +- Release notes in the wrong location + +## Requirements +- **GitHub Token**: A GitHub token with permission to fetch repository data such as Issues and Pull Requests. +- **Python 3.11+**: Ensure you have Python 3.11 installed on your system. + +## Inputs + +### `GITHUB_TOKEN` +- **Description**: Your GitHub token for authentication. Store it as a secret and reference it in the workflow file as secrets.GITHUB_TOKEN. +- **Required**: Yes + +### `pr-number` +- **Description**: The pull request number to check for release notes. Example: `1`. +- **Required**: Yes + +### `github-repository` +- **Description**: The GitHub repository to check for version tags. Example: `AbsaOSS/release-notes-presence-check`. +- **Required**: Yes + +### `location` +- **Description**: The location of the release notes in the pull request. Example: `body`. +- **Required**: No + +### `title` +- **Description**: The title of the release notes in the pull request. Example without regex: `Release Notes:`, with regex: `[Rr]elease [Nn]otes:`. +- **Required**: No + +### `skip-labels` +- **Description**: The labels to skip the release notes check. Example: `skip-release-notes`. +- **Required**: No + +### `fails-on-error` +- **Description**: Whether the action should fail if an error occurs. +- **Required**: No +- **Default**: `true` + +## Outputs + +### `valid` +- **Description**: Whether the release notes are present. +- **Value**: `true` or `false` + +## Usage + +### Adding the Action to Your Workflow + +See the default action step definition: + +```yaml +- name: Release Notes Presence Check + id: release_notes_presence_check + uses: AbsaOSS/release-notes-presence-check@v0.1.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + github-repository: "{ org }/{ repo }" + pr-numer: 109 + location: "body" + title: "[Rr]elease [Nn]otes:" + skip-labels: "skip-release-notes,no-release-notes" + fails-on-error: "false" + ``` + +## Running Static Code Analysis + +This project uses Pylint tool for static code analysis. Pylint analyses your code without actually running it. It checks for errors, enforces, coding standards, looks for code smells etc. + +Pylint displays a global evaluation score for the code, rated out of a maximum score of 10.0. We are aiming to keep our code quality high above the score 9.5. + +### Set Up Python Environment +```shell +python3 -m venv venv +source venv/bin/activate +pip install -r requirements.txt + +# run your commands + +deactivate +``` + +This command will also install a Pylint tool, since it is listed in the project requirements. + +### Run Pylint +Run Pylint on all files that are currently tracked by Git in the project. +``` +pylint $(git ls-files '*.py') +``` + +To run Pylint on a specific file, follow the pattern `pylint /.py`. + +Example: +``` +pylint ./release_notes_presence_check/release_notes_presence_check_action.py +``` + +## Run Black Tool Locally +This project uses the [Black](https://github.com/psf/black) tool for code formatting. +Black aims for consistency, generality, readability and reducing git diffs. +The coding style used can be viewed as a strict subset of PEP 8. + +The project root file `pyproject.toml` defines the Black tool configuration. +In this project we are accepting the line length of 120 characters. + +Follow these steps to format your code with Black locally: + +### Set Up Python Environment +From terminal in the root of the project, run the following command: + +```shell +python3 -m venv venv +source venv/bin/activate +pip install -r requirements.txt +``` + +This command will also install a Black tool, since it is listed in the project requirements. + +### Run Black +Run Black on all files that are currently tracked by Git in the project. +```shell +black $(git ls-files '*.py') +``` + +To run Black on a specific file, follow the pattern `black /.py`. + +Example: +```shell +black ./release_notes_presence_check/release_notes_presence_check_action.py +``` + +### Expected Output +This is the console expected output example after running the tool: +``` +All done! ✨ 🍰 ✨ +1 file reformatted. +``` + +## Running Unit Test + +Unit tests are written using pytest. To run the tests, use the following command: + +``` +pytest tests/ +``` + +This will execute all tests located in the tests directory. + +## Code Coverage + +Code coverage is collected using pytest-cov coverage tool. To run the tests and collect coverage information, use the following command: + +``` +pytest --cov=. --cov-report=html tests/ +``` + +This will execute all tests located in the tests directory and generate a code coverage report. + +See the coverage report on the path: + +``` +htmlcov/index.html +``` + +## Run Action Locally +Create *.sh file and place it in the project root. + +```bash +#!/bin/bash + +# Ensure that Python virtual environment is activated +if [ ! -d ".venv" ]; then + echo "Python virtual environment not found. Creating one..." + python3 -m venv .venv +fi + +source .venv/bin/activate + +# Install dependencies +pip install -r requirements.txt + +# Check if GITHUB_TOKEN is set +if [ -z "$GITHUB_TOKEN" ]; then + echo "Error: GITHUB_TOKEN environment variable is not set." + exit 1 +fi + +# Set necessary environment variables +export INPUT_GITHUB_TOKEN="$GITHUB_TOKEN" +export INPUT_PR_NUMBER=109 +export INPUT_GITHUB_REPOSITORY="AbsaOSS/generate-release-notes" +export INPUT_LOCATION="body" +export INPUT_TITLE="[Rr]elease notes:" +export INPUT_SKIP_LABELS="skip-release-notes,another-skip-label" +export INPUT_FAILS_ON_ERROR="true" +export GITHUB_OUTPUT="output.txt" # File to capture outputs + +# Remove existing output file if it exists +if [ -f "$GITHUB_OUTPUT" ]; then + rm "$GITHUB_OUTPUT" +fi + +# Run the main script +python main.py + +# Display the outputs +echo "Action Outputs:" +cat "$GITHUB_OUTPUT" +``` + +## Contribution Guidelines + +We welcome contributions to the Version Tag Check Action! Whether you're fixing bugs, improving documentation, or proposing new features, your help is appreciated. + +### How to Contribute +- **Submit Pull Requests**: Feel free to fork the repository, make changes, and submit a pull request. Please ensure your code adheres to the existing style and all tests pass. +- **Report Issues**: If you encounter any bugs or issues, please report them via the repository's [Issues page](https://github.com/AbsaOSS/version-tag-check/issues). +- **Suggest Enhancements**: Have ideas on how to make this action better? Open an issue to suggest enhancements. + +Before contributing, please review our [contribution guidelines](https://github.com/AbsaOSS/version-tag-check/blob/master/CONTRIBUTING.md) for more detailed information. + +## License Information + +This project is licensed under the Apache License 2.0. It is a liberal license that allows you great freedom in using, modifying, and distributing this software, while also providing an express grant of patent rights from contributors to users. + +For more details, see the [LICENSE](https://github.com/AbsaOSS/version-tag-check/blob/master/LICENSE) file in the repository. + +## Contact or Support Information + +If you need help with using or contributing to Generate Release Notes Action, or if you have any questions or feedback, don't hesitate to reach out: + +- **Issue Tracker**: For technical issues or feature requests, use the [GitHub Issues page](https://github.com/AbsaOSS/version-tag-check/issues). +- **Discussion Forum**: For general questions and discussions, join our [GitHub Discussions forum](https://github.com/AbsaOSS/version-tag-check/discussions). diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..5e8b6fa --- /dev/null +++ b/action.yml @@ -0,0 +1,91 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +name: 'Release Notes Presence Check' +description: 'A GH action for checking the presence of release notes in a GitHub Pull Request.' +inputs: + pr-number: + description: 'The number of the PR to check for release notes.' + required: true + github-repository: + description: 'The repository to check for release notes.' + required: true + location: + description: 'The location of the release notes in the PR. Supported value is "body"' + required: false + default: 'body' + title: + description: 'The title of the release notes section in the PR body. Value supports regex.' + required: false + default: '[Rr]elease [Nn]otes:' + skip-labels: + description: 'A comma-separated list of labels that will cause the action to skip the check.' + required: false + default: '' + fails-on-error: + description: 'Set to "true" to fail the action if validation errors are found.' + required: false + default: 'true' + +outputs: + valid: + description: 'Indicates whether the release notes are present in the PR.' + value: ${{ steps.release-notes-presence-check.outputs.valid }} + +branding: + icon: 'book' + color: 'yellow' + +runs: + using: 'composite' + steps: + # setup-python is not called as it is expected that it was done in the workflow that uses this action + - name: Install Python dependencies + run: | + python_version=$(python --version 2>&1 | grep -oP '\d+\.\d+\.\d+') + minimal_required_version="3.11.0" + + function version { echo "$@" | awk -F. '{ printf("%d%03d%03d\n", $1,$2,$3); }'; } + + echo "Current Python version: $python_version" + echo "Minimal required Python version: $minimal_required_version" + + if [ $(version $python_version) -lt $(version $minimal_required_version) ]; then + echo "Python version is less than $minimal_required_version" + exit 1 + else + echo "Python version meets the minimum requirement of $minimal_required_version" + fi + + python -m venv .venv + source .venv/bin/activate + pip install -r ${{ github.action_path }}/requirements.txt + shell: bash + + - name: Call version tag check logic + id: version-tag-check + env: + INPUT_GITHUB_TOKEN: ${{ env.GITHUB_TOKEN }} + INPUT_PR_NUMBER: ${{ inputs.pr-number }} + INPUT_GITHUB_REPOSITORY: ${{ inputs.github-repository }} + INPUT_LOCATION: ${{ inputs.location }} + INPUT_TITLE: ${{ inputs.title }} + INPUT_SKIP_LABELS: ${{ inputs.skip-labels }} + INPUT_FAILS_ON_ERROR: ${{ inputs.fails-on-error }} + run: | + source .venv/bin/activate + python ${{ github.action_path }}/main.py + shell: bash diff --git a/main.py b/main.py new file mode 100644 index 0000000..cd2bace --- /dev/null +++ b/main.py @@ -0,0 +1,33 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +""" +This module contains the main script for the Version Tag Check GH Action. +""" + +import logging + +from release_notes_presence_check.release_notes_presence_check_action import ReleaseNotesPresenceCheckAction +from release_notes_presence_check.utils.logging_config import setup_logging + +if __name__ == "__main__": + setup_logging() + logger = logging.getLogger(__name__) + + logger.info("Starting Release Notes Presence Check.") + + action = ReleaseNotesPresenceCheckAction() + action.run() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..bc4e9be --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,7 @@ +[tool.black] +line-length = 120 +target-version = ['py311'] +force-exclude = '''test''' + +[tool.coverage.run] +omit = ["tests/*", "main.py", "version_tag_check/github_repository.py"] diff --git a/release_notes_presence_check/__init__.py b/release_notes_presence_check/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/release_notes_presence_check/github_repository.py b/release_notes_presence_check/github_repository.py new file mode 100644 index 0000000..c3768ba --- /dev/null +++ b/release_notes_presence_check/github_repository.py @@ -0,0 +1,60 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +""" +This module contains the GitHubRepository class that is used to interact with the GitHub API. +""" + +import logging +import sys +import requests + +logger = logging.getLogger(__name__) + + +# pylint: disable=too-few-public-methods +class GitHubRepository: + """ + A class that represents a GitHub repository and provides methods to interact + """ + + def __init__(self, owner: str, repo: str, token: str) -> None: + """ + Initialize the GitHubRepository with the owner, repo and token. + + @param owner: The owner of the repository + @param repo: The name of the repository + @param token: The GitHub API token + @return: None + """ + self.owner = owner + self.repo = repo + self.token = token + self.headers = {"Authorization": f"Bearer {self.token}", "Accept": "application/vnd.github.v3+json"} + + def get_pr_info(self, pr_number) -> dict: + """ + Get Pull Request information for the repository. + + @return: A Pull Request object representing the PR. + """ + pr_url = f"https://api.github.com/repos/{self.owner}/{self.repo}/pulls/{pr_number}" + response = requests.get(pr_url, headers=self.headers, timeout=5) + if response.status_code != 200: + logger.error("Error fetching PR details. Status code: %s", response.status_code) + sys.exit(1) + + return response.json() diff --git a/release_notes_presence_check/release_notes_presence_check_action.py b/release_notes_presence_check/release_notes_presence_check_action.py new file mode 100644 index 0000000..7e46a55 --- /dev/null +++ b/release_notes_presence_check/release_notes_presence_check_action.py @@ -0,0 +1,168 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +""" +This module contains the Release Notes Presence Check action. +""" + +import logging +import os +import sys +import re + +from release_notes_presence_check.github_repository import GitHubRepository + +logger = logging.getLogger(__name__) + + +class ReleaseNotesPresenceCheckAction: + """ + Class to handle the Release Notes Presence Check action. + """ + + def __init__(self) -> None: + """ + Initialize the action with the required inputs. + + @return: None + """ + self.github_token: str = os.environ.get("INPUT_GITHUB_TOKEN", default="") + self.location: str = os.environ.get("INPUT_LOCATION", default="body") + self.title: str = os.environ.get("INPUT_TITLE", default="[Rr]elease [Nn]otes:") + self.skip_labels: list[str] = os.environ.get("INPUT_SKIP_LABELS", default="") + self.fails_on_error: bool = os.environ.get("INPUT_FAILS_ON_ERROR", "true").lower() == "true" + + self.__validate_inputs() + + self.pr_number: int = int(os.environ.get("INPUT_PR_NUMBER", default="")) + self.owner, self.repo_name = os.environ.get("INPUT_GITHUB_REPOSITORY", default="").split("/") + + def run(self) -> None: + """ + Run the action. + + @return: None + """ + + # get PR information + repository = GitHubRepository(self.owner, self.repo_name, self.github_token) + pr_data = repository.get_pr_info(self.pr_number) + + # check skip labels presence + labels = [label.get("name", "") for label in pr_data.get("labels", [])] + if self.skip_labels in labels: + logger.info("Skipping release notes check because '%s' label is present.", self.skip_labels) + self.write_output("true") + sys.exit(0) # Exiting with code 0 indicates success but the action is skipped. + + # check release notes presence in defined location + pr_body = pr_data.get("body", "") + if len(pr_body.strip()) == 0: + logger.error("Error: Pull request description is empty.") + self.handle_failure() + + # Check if release notes tag is present + if not re.search(self.title, pr_body): + logger.error("Error: Release notes title '%s' not found in pull request body.", self.title) + self.handle_failure() + + lines = pr_body.split("\n") + release_notes_start_index = None + for i, line in enumerate(lines): + if re.search(self.title, line): + release_notes_start_index = i + 1 # text after the tag line + break + + if release_notes_start_index is None or release_notes_start_index >= len(lines): + logger.error("Error: No content found after the release notes tag.") + self.handle_failure() + + text_below_release_notes = lines[release_notes_start_index:] + if not text_below_release_notes or not text_below_release_notes[0].strip().startswith(("-", "+", "*")): + logger.error("Error: No bullet list found directly under release notes tag.") + self.handle_failure() + + self.write_output("true") + logger.info("Release Notes detected.") + sys.exit(0) + + def write_output(self, valid_value) -> None: + """ + Write the output to the file specified by the GITHUB_OUTPUT environment variable. + + @param valid_value: The value to write to the output file. + @return: None + """ + output_file = os.environ.get("GITHUB_OUTPUT", default="output.txt") + if output_file: + with open(output_file, "a", encoding="utf-8") as fh: + print(f"valid={valid_value}", file=fh) + + def handle_failure(self) -> None: + """ + Handle the failure of the action. + + @return: None + """ + self.write_output("false") + if self.fails_on_error: + sys.exit(1) + else: + sys.exit(0) + + def __validate_inputs(self) -> None: + """ + Validate the required inputs. When the inputs are not valid, the action will fail. + + @return: None + """ + if len(self.github_token) == 0: + logger.error("Failure: GITHUB_TOKEN is not set correctly.") + self.handle_failure() + + value = os.environ.get("INPUT_PR_NUMBER", default="") + if len(value) == 0: + logger.error("Failure: PR_NUMBER is not set correctly.") + self.handle_failure() + + if not value.isdigit(): + logger.error("Failure: PR_NUMBER is not a valid number.") + self.handle_failure() + + value = os.environ.get("INPUT_GITHUB_REPOSITORY", default="") + if len(value) == 0: + logger.error("Failure: GITHUB_REPOSITORY is not set correctly.") + self.handle_failure() + + if value.count("/") != 1: + logger.error("Failure: GITHUB_REPOSITORY is not in the correct format.") + self.handle_failure() + + if len(value.split("/")[0]) == 0 or len(value.split("/")[1]) == 0: + logger.error("Failure: GITHUB_REPOSITORY is not in the correct format.") + self.handle_failure() + + if len(self.location) == 0: + logger.error("Failure: LOCATION is not set correctly.") + self.handle_failure() + + if self.location not in ["body"]: + logger.error("Failure: LOCATION is not one of the supported values.") + self.handle_failure() + + if len(self.title) == 0: + logger.error("Failure: TITLE is not set correctly.") + self.handle_failure() diff --git a/release_notes_presence_check/utils/__init__.py b/release_notes_presence_check/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/release_notes_presence_check/utils/logging_config.py b/release_notes_presence_check/utils/logging_config.py new file mode 100644 index 0000000..b6460ac --- /dev/null +++ b/release_notes_presence_check/utils/logging_config.py @@ -0,0 +1,47 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# + +""" +This module contains a method to set up logging in the project. +""" +import logging +import os +import sys + + +def setup_logging() -> None: + """ + Set up the logging configuration in the project + + @return: None + """ + # Load logging configuration from the environment variables + is_debug_mode = os.getenv("RUNNER_DEBUG", "0") == "1" + level = logging.DEBUG if is_debug_mode else logging.INFO + + # Set up the logging configuration + logging.basicConfig( + level=level, + format="%(asctime)s - %(levelname)s - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + sys.stdout.flush() + + logging.info("Logging configuration set up.") + + if is_debug_mode: + logging.debug("Debug mode enabled by CI runner.") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a6db14e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +coverage==7.5.2 +pytest==7.4.3 +pytest-cov==5.0.0 +pytest-mock==3.14.0 +pylint==3.2.6 +requests==2.31.0 +black==24.8.0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_release_notes_presence_check_action.py b/tests/test_release_notes_presence_check_action.py new file mode 100644 index 0000000..c6400af --- /dev/null +++ b/tests/test_release_notes_presence_check_action.py @@ -0,0 +1,418 @@ +# +# Copyright 2024 ABSA Group Limited +# +# 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. +# +import logging +import os +import pytest + +from release_notes_presence_check.release_notes_presence_check_action import ReleaseNotesPresenceCheckAction + + +# input validation + +def test_validate_inputs_valid(monkeypatch, caplog): + # Set all required environment variables with valid values + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_PR_NUMBER": "109", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "", + "INPUT_FAILS_ON_ERROR": "true", + } + os.environ.update(env_vars) + + # Capture logs + caplog.set_level(logging.ERROR) + + # Instantiate the action; should not raise SystemExit if validation passes + action = ReleaseNotesPresenceCheckAction() + + # There should be no errors or warnings + assert "Failure" not in caplog.text + +@pytest.mark.parametrize("env_name, env_value, error_message", [ + # GITHUB_TOKEN missing or empty + ("INPUT_GITHUB_TOKEN", None, "Failure: GITHUB_TOKEN is not set correctly."), + ("INPUT_GITHUB_TOKEN", "", "Failure: GITHUB_TOKEN is not set correctly."), + + # PR_NUMBER missing, empty, or invalid format + ("INPUT_PR_NUMBER", None, "Failure: PR_NUMBER is not set correctly."), + ("INPUT_PR_NUMBER", "", "Failure: PR_NUMBER is not set correctly."), + ("INPUT_PR_NUMBER", "abc", "Failure: PR_NUMBER is not a valid number."), + + # GITHUB_REPOSITORY missing, empty, or invalid format + ("INPUT_GITHUB_REPOSITORY", None, "Failure: GITHUB_REPOSITORY is not set correctly."), + ("INPUT_GITHUB_REPOSITORY", "", "Failure: GITHUB_REPOSITORY is not set correctly."), + ("INPUT_GITHUB_REPOSITORY", "ownerrepo", "Failure: GITHUB_REPOSITORY is not in the correct format."), + ("INPUT_GITHUB_REPOSITORY", "owner//repo", "Failure: GITHUB_REPOSITORY is not in the correct format."), + ("INPUT_GITHUB_REPOSITORY", "owner/", "Failure: GITHUB_REPOSITORY is not in the correct format."), + ( "INPUT_GITHUB_REPOSITORY", "/repo", "Failure: GITHUB_REPOSITORY is not in the correct format."), + + # LOCATION missing, empty, or unsupported value + ("INPUT_LOCATION", "", "Failure: LOCATION is not set correctly."), + ("INPUT_LOCATION", "header", "Failure: LOCATION is not one of the supported values."), + + # TITLE missing or empty + ("INPUT_TITLE", "", "Failure: TITLE is not set correctly."), +]) +def test_validate_inputs_invalid(monkeypatch, caplog, env_name, env_value, error_message): + # Set all required valid environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_PR_NUMBER": "109", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "", + "INPUT_FAILS_ON_ERROR": "true", + } + + # Update or remove the environment variable for the tested scenario + if env_value is None: + env_vars.pop(env_name, None) # Remove the variable to simulate it missing + if env_name in os.environ: + os.environ.pop(env_name) + else: + env_vars[env_name] = env_value + + # Update environment variables for the test + os.environ.update(env_vars) + + # Mock sys.exit to raise SystemExit exception + with pytest.raises(SystemExit) as e: + # Capture logs + caplog.set_level(logging.ERROR) + + # Instantiate the action; should raise SystemExit if validation fails + ReleaseNotesPresenceCheckAction() + + # Assert that sys.exit was called with exit code 1 + assert e.value.code == 1, f"Expected SystemExit with code 1 for {env_name}={env_value}" + + # Assert that the correct error message was logged + assert error_message in caplog.text, f"Expected error message '{error_message}' for {env_name}={env_value}" + + +# run + +def test_run_successful(mocker): + # Set environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "", + "INPUT_FAILS_ON_ERROR": "true", + } + # Update os.environ with the test environment variables + os.environ.update(env_vars) + if os.path.exists("output.txt"): + os.remove("output.txt") + + # Mock sys.exit to prevent the test from exiting + mock_exit = mocker.patch("sys.exit") + + # Mock the GitHubRepository class + mock_repository_class = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.GitHubRepository") + mock_repository_instance = mock_repository_class.return_value + mock_repository_instance.get_pr_info.return_value = { + "body": "Release Notes:\n- This update includes bug fixes and improvements.", + "labels": [{"name": "bug"}, {"name": "enhancement"}] + } + + # Mock the output writing method + mock_output = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.ReleaseNotesPresenceCheckAction.write_output") + + # Run the action + action = ReleaseNotesPresenceCheckAction() + action.run() + + mock_output.assert_called_once_with("true") + mock_exit.assert_called_once_with(0) + + +def test_run_skip_by_label(mocker): + # Set environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "skip-release-notes-check", + "INPUT_FAILS_ON_ERROR": "true", + } + # Update os.environ with the test environment variables + os.environ.update(env_vars) + if os.path.exists("output.txt"): + os.remove("output.txt") + + # Mock sys.exit to prevent the test from exiting + mock_exit = mocker.patch("sys.exit", side_effect=SystemExit(0)) + + # Mock the GitHubRepository class + mock_repository_class = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.GitHubRepository") + mock_repository_instance = mock_repository_class.return_value + mock_repository_instance.get_pr_info.return_value = { + "body": "Release Notes:\n- This update includes bug fixes and improvements.", + "labels": [{"name": "bug"}, {"name": "enhancement"}, {"name": "skip-release-notes-check"}] + } + + # Mock the output writing method + mock_output = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.ReleaseNotesPresenceCheckAction.write_output") + + # Run the action + with pytest.raises(SystemExit) as exit_info: + action = ReleaseNotesPresenceCheckAction() + action.run() + + assert SystemExit == exit_info.type + assert 0 == exit_info.value.code + + mock_output.assert_called_once_with("true") + + +def test_run_fail_no_body(mocker): + # Set environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "skip-release-notes-check", + "INPUT_FAILS_ON_ERROR": "true", + } + # Update os.environ with the test environment variables + os.environ.update(env_vars) + if os.path.exists("output.txt"): + os.remove("output.txt") + + # Mock sys.exit to prevent the test from exiting + mock_exit = mocker.patch("sys.exit", side_effect=SystemExit(1)) + + # Mock the GitHubRepository class + mock_repository_class = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.GitHubRepository") + mock_repository_instance = mock_repository_class.return_value + mock_repository_instance.get_pr_info.return_value = { + "labels": [{"name": "bug"}, {"name": "enhancement"}] + } + + # Mock the output writing method + mock_output = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.ReleaseNotesPresenceCheckAction.write_output") + + # Run the action + with pytest.raises(SystemExit) as exit_info: + action = ReleaseNotesPresenceCheckAction() + action.run() + + assert SystemExit == exit_info.type + assert 1 == exit_info.value.code + + mock_output.assert_called_once_with("false") + +def test_run_fail_empty_body(mocker): + # Set environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "skip-release-notes-check", + "INPUT_FAILS_ON_ERROR": "true", + } + # Update os.environ with the test environment variables + os.environ.update(env_vars) + if os.path.exists("output.txt"): + os.remove("output.txt") + + # Mock sys.exit to prevent the test from exiting + mock_exit = mocker.patch("sys.exit", side_effect=SystemExit(1)) + + # Mock the GitHubRepository class + mock_repository_class = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.GitHubRepository") + mock_repository_instance = mock_repository_class.return_value + mock_repository_instance.get_pr_info.return_value = { + "body": "", + "labels": [{"name": "bug"}, {"name": "enhancement"}] + } + + # Mock the output writing method + mock_output = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.ReleaseNotesPresenceCheckAction.write_output") + + # Run the action + with pytest.raises(SystemExit) as exit_info: + action = ReleaseNotesPresenceCheckAction() + action.run() + + assert SystemExit == exit_info.type + assert 1 == exit_info.value.code + + mock_output.assert_called_once_with("false") + +def test_run_fail_title_not_found(mocker): + # Set environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "Not present:", + "INPUT_SKIP_LABELS": "skip-release-notes-check", + "INPUT_FAILS_ON_ERROR": "true", + } + # Update os.environ with the test environment variables + os.environ.update(env_vars) + if os.path.exists("output.txt"): + os.remove("output.txt") + + # Mock sys.exit to prevent the test from exiting + mock_exit = mocker.patch("sys.exit", side_effect=SystemExit(1)) + + # Mock the GitHubRepository class + mock_repository_class = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.GitHubRepository") + mock_repository_instance = mock_repository_class.return_value + mock_repository_instance.get_pr_info.return_value = { + "body": "Release Notes:\n- This update includes bug fixes and improvements.", + "labels": [{"name": "bug"}, {"name": "enhancement"}] + } + + # Mock the output writing method + mock_output = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.ReleaseNotesPresenceCheckAction.write_output") + + # Run the action + with pytest.raises(SystemExit) as exit_info: + action = ReleaseNotesPresenceCheckAction() + action.run() + + assert SystemExit == exit_info.type + assert 1 == exit_info.value.code + + mock_output.assert_called_once_with("false") + +def test_run_fail_release_notes_lines_not_found(mocker): + # Set environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "skip-release-notes-check", + "INPUT_FAILS_ON_ERROR": "true", + } + # Update os.environ with the test environment variables + os.environ.update(env_vars) + if os.path.exists("output.txt"): + os.remove("output.txt") + + # Mock sys.exit to prevent the test from exiting + mock_exit = mocker.patch("sys.exit", side_effect=SystemExit(1)) + + # Mock the GitHubRepository class + mock_repository_class = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.GitHubRepository") + mock_repository_instance = mock_repository_class.return_value + mock_repository_instance.get_pr_info.return_value = { + "body": "Release Notes:\nThis update includes bug fixes and improvements.", + "labels": [{"name": "bug"}, {"name": "enhancement"}] + } + + # Mock the output writing method + mock_output = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.ReleaseNotesPresenceCheckAction.write_output") + + # Run the action + with pytest.raises(SystemExit) as exit_info: + action = ReleaseNotesPresenceCheckAction() + action.run() + + assert SystemExit == exit_info.type + assert 1 == exit_info.value.code + + mock_output.assert_called_once_with("false") + +def test_run_fail_no_lines_after_title(mocker): + # Set environment variables + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "skip-release-notes-check", + "INPUT_FAILS_ON_ERROR": "true", + } + # Update os.environ with the test environment variables + os.environ.update(env_vars) + if os.path.exists("output.txt"): + os.remove("output.txt") + + # Mock sys.exit to prevent the test from exiting + mock_exit = mocker.patch("sys.exit", side_effect=SystemExit(1)) + + # Mock the GitHubRepository class + mock_repository_class = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.GitHubRepository") + mock_repository_instance = mock_repository_class.return_value + mock_repository_instance.get_pr_info.return_value = { + "body": "Release Notes:", + "labels": [{"name": "bug"}, {"name": "enhancement"}] + } + + # Mock the output writing method + mock_output = mocker.patch("release_notes_presence_check.release_notes_presence_check_action.ReleaseNotesPresenceCheckAction.write_output") + + # Run the action + with pytest.raises(SystemExit) as exit_info: + action = ReleaseNotesPresenceCheckAction() + action.run() + + assert SystemExit == exit_info.type + assert 1 == exit_info.value.code + + mock_output.assert_called_once_with("false") + +# handle_failure + +def test_handle_failure_fails_on_error_false(mocker): + # Set environment variables with 'INPUT_FAILS_ON_ERROR' set to 'false' + env_vars = { + "INPUT_GITHUB_TOKEN": "fake_token", + "INPUT_PR_NUMBER": "109", + "INPUT_GITHUB_REPOSITORY": "owner/repo", + "INPUT_LOCATION": "body", + "INPUT_TITLE": "[Rr]elease [Nn]otes:", + "INPUT_SKIP_LABELS": "", + "INPUT_FAILS_ON_ERROR": "false", # Set to 'false' to test else branch + } + mocker.patch.dict(os.environ, env_vars) + + # Mock sys.exit to raise SystemExit exception + def mock_exit(code): + raise SystemExit(code) + mocker.patch("sys.exit", mock_exit) + + # Instantiate the action + action = ReleaseNotesPresenceCheckAction() + + # Call handle_failure and expect SystemExit + with pytest.raises(SystemExit) as e: + action.handle_failure() + + # Assert that sys.exit was called with exit code 0 + assert e.value.code == 0