Skip to content

Commit

Permalink
Merge branch 'main' into bugfix/check_fails_with_nonetype
Browse files Browse the repository at this point in the history
  • Loading branch information
ant-u committed Mar 19, 2024
2 parents 3ab9062 + 0cb67b7 commit 665a0b6
Show file tree
Hide file tree
Showing 13 changed files with 193 additions and 17 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,29 @@ options:
-q, --quiet disable most output
```

Additionally, there is an option to ignore single files, folders and types of files.
If there exists a `.scanignore` in the **top level directory** of a package,
everything in it is going to be ignored.
The file entries work similar to a `.gitignore` file, including making comments with `#`.
One Example for a custom `.scanignore` file:

```
.git/* # folder
README.txt # file
README.* # file pattern
```

Per default, ros_license_toolkit ignores the following:

```
.scanignore
package.xml
setup.py
setup.cfg
CMakeLists.txt
.git/*
```

### Using it as a GitHub action

You can use `ros_license_toolkit` inside your GitHub workflow in order to check licenses in your
Expand Down
11 changes: 10 additions & 1 deletion src/ros_license_toolkit/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,16 @@ def _check_licenses(self, package: Package) -> None:
f"License text file '{license_text_file}' is " +\
f"of license {actual_license} but tag is " +\
f"{license_tag.get_license_id()}."
self.missing_license_texts_status[license_tag] = Status.WARNING
# If Tag and File both are in SPDX but don't match -> Error
if is_license_name_in_spdx_list(license_tag.get_license_id()):
self.missing_license_texts_status[license_tag] =\
Status.FAILURE
else:
self.missing_license_texts_status[license_tag] =\
Status.WARNING
self.files_with_wrong_tags[license_tag] = \
{'actual_license': actual_license,
'license_tag': license_tag.get_license_id()}
continue

def _evaluate_results(self):
Expand Down
32 changes: 31 additions & 1 deletion src/ros_license_toolkit/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,44 @@

"""Common utility functions."""

from typing import Any, Dict, Optional
import os
from typing import Any, Dict, List, Optional

REQUIRED_PERCENTAGE_OF_LICENSE_TEXT = 95.0

# files we ignore in scan results
IGNORED = [
".scanignore",
"package.xml",
"setup.py",
"setup.cfg",
"CMakeLists.txt",
".git/*"
]


def get_spdx_license_name(scan_results: Dict[str, Any]) -> Optional[str]:
"""Get the SPDX license name from scan results."""
if scan_results['percentage_of_license_text'] \
>= REQUIRED_PERCENTAGE_OF_LICENSE_TEXT:
return scan_results['detected_license_expression_spdx']
return None


def get_ignored_content(pkg_abspath: str) -> List[str]:
"""Return all ignored patterns from '.scanignore'
and local IGNORED definition."""
ignored_content: List[str] = []
scanignore_path = pkg_abspath + "/.scanignore"
if os.path.exists(scanignore_path):
with open(scanignore_path, 'r', encoding="utf-8") as f:
for line in f:
line_contents = line.split('#')
ignore_pattern = line_contents[0].rstrip()
if len(ignore_pattern) > 0:
ignored_content.append(ignore_pattern)
f.close()
for pattern in IGNORED:
if pattern not in ignored_content:
ignored_content.append(pattern)
return ignored_content
17 changes: 6 additions & 11 deletions src/ros_license_toolkit/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,12 @@
from rospkg.common import PACKAGE_FILE
from scancode.api import get_licenses

from ros_license_toolkit.common import get_spdx_license_name
from ros_license_toolkit.common import (get_ignored_content,
get_spdx_license_name)
from ros_license_toolkit.copyright import get_copyright_strings_per_pkg
from ros_license_toolkit.license_tag import LicenseTag
from ros_license_toolkit.repo import NotARepoError, Repo

# files we ignore in scan results
IGNORED = [
"package.xml",
"setup.py",
"setup.cfg",
"CMakeLists.txt",
".git/*",
]


class PackageException(Exception):
"""Exception raised when a package is invalid."""
Expand Down Expand Up @@ -88,6 +80,9 @@ def __init__(self, path: str, repo: Optional[Repo] = None):
# this is Optional, because it is only evaluated on the first call
self._license_tags: Optional[Dict[str, LicenseTag]] = None

# All ignored files and folders
self._ignored_content: List[str] = get_ignored_content(self.abspath)

def _get_path_relative_to_pkg(self, path: str) -> str:
"""Get path relative to pkg root"""
return os.path.relpath(path, self.abspath)
Expand Down Expand Up @@ -121,7 +116,7 @@ def _run_scan_and_save_results(self):
for (root, _, files) in os.walk(self.abspath):
files_rel_to_pkg = [self._get_path_relative_to_pkg(
os.path.join(root, f)) for f in files]
for pattern in IGNORED:
for pattern in self._ignored_content:
matched = fnmatch.filter(files_rel_to_pkg, pattern)
for m in matched:
files_rel_to_pkg.remove(m)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
This is also a license mentioning text, but it should be ignored since its under the .hidden directory.

The majority of this library is licensed under the Apache-2.0 licensed. However, certain parts are
licensed under different licenses:
- The queue used inside the communication structures is originally written by Cameron Desrochers
and is released under the BSD-2-Clause license.
- The semaphore implementation used inside the queue implementation is written by Jeff Preshing and
licensed under the zlib license
4 changes: 4 additions & 0 deletions test/_test_data/test_pkg_ignore_readme_contents/.scanignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.hidden/*
README.md

README.* # comment in any kind
60 changes: 60 additions & 0 deletions test/_test_data/test_pkg_ignore_readme_contents/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
8 changes: 8 additions & 0 deletions test/_test_data/test_pkg_ignore_readme_contents/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
This readme contains some random license names that shall NOT be checked.

The majority of this library is licensed under the Apache-2.0 licensed. However, certain parts are
licensed under different licenses:
- The queue used inside the communication structures is originally written by Cameron Desrochers
and is released under the BSD-2-Clause license.
- The semaphore implementation used inside the queue implementation is written by Jeff Preshing and
licensed under the zlib license
8 changes: 8 additions & 0 deletions test/_test_data/test_pkg_ignore_readme_contents/README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
This readme contains some random license names that shall NOT be checked, here as txt.

The majority of this library is licensed under the Apache-2.0 licensed. However, certain parts are
licensed under different licenses:
- The queue used inside the communication structures is originally written by Cameron Desrochers
and is released under the BSD-2-Clause license.
- The semaphore implementation used inside the queue implementation is written by Jeff Preshing and
licensed under the zlib license
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright 2020 The Author

# 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 sys

if __name__ == "__main__":
print("hi")
sys.exit(0)
6 changes: 6 additions & 0 deletions test/_test_data/test_pkg_ignore_readme_contents/package.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>test_pkg_ignore_readme_contents</name>
<license file="LICENSE" source-files="code_with_license.py">Apache-2.0</license>
</package>
1 change: 1 addition & 0 deletions test/systemtest/test_all_packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def test_all(self):
b"test_pkg_has_code_of_different_license_and_tag", stdout)
self.assertIn(
b"test_pkg_has_code_of_different_license_and_wrong_tag", stdout)
self.assertIn(b"test_pkg_ignore_readme_contents", stdout)
self.assertIn(b"test_pkg_name_not_in_spdx", stdout)
self.assertIn(b"test_pkg_no_file_attribute", stdout)
self.assertIn(b"test_pkg_no_license", stdout)
Expand Down
13 changes: 9 additions & 4 deletions test/systemtest/test_separate_pkgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ def test_pkg_has_code_of_different_license_and_wrong_tag(self):
["test/_test_data/"
"test_pkg_has_code_of_different_license_and_wrong_tag"]))

def test_pkg_ignore_readme_contents(self):
"""Test on a package with readme files. READMEs mention licenses
that are not in package and shall therefore be ignored."""
test_result = main(["test/_test_data/test_pkg_ignore_readme_contents"])
self.assertEqual(os.EX_OK, test_result)

def test_pkg_name_not_in_spdx(self):
"""Test on a package that has valid License file with BSD-3-Clause
but its license tag BSD is not in SPDX format"""
Expand Down Expand Up @@ -189,10 +195,9 @@ def test_pkg_with_multiple_licenses_one_referenced_incorrect(self):

def test_pkg_wrong_license_file(self):
"""Test on a package with a license text file that does not match
the license declared in the package.xml."""
process, stdout = open_subprocess("test_pkg_wrong_license_file")
self.assertEqual(os.EX_OK, process.returncode)
self.assertIn(b"WARNING", stdout)
the license declared in the package.xml, both tag and file in spdx"""
self.assertEqual(os.EX_DATAERR, main(
["test/_test_data/test_pkg_wrong_license_file"]))


def open_subprocess(test_data_name: str):
Expand Down

0 comments on commit 665a0b6

Please sign in to comment.