Skip to content

Commit 58bfd93

Browse files
committed
Scancode: Fix false positive reported by scancode output analyser script
ScanCode can possibly return many licenses found for a single file scanned. This commit ensures that the file is not reported as lacking a permissive license if at least one license found in it is permissive. Previously the script was reporting an issue if it found at least one license in a file that was not permissive. Additionally catch more errors and provide specific details about failures. Provide unitest.
1 parent 3c6c8ae commit 58bfd93

File tree

6 files changed

+1256
-1222
lines changed

6 files changed

+1256
-1222
lines changed

tools/test/travis-ci/scancode-evaluate.py

Lines changed: 93 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -13,119 +13,135 @@
1313
distributed under the License is distributed on an "AS IS" BASIS,
1414
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1515
See the License for the specific language governing permissions and
16-
limitations
16+
limitations
1717
"""
1818

19-
# Asumptions for this script:
19+
# Asumptions for this script:
2020
# 1. directory_name is scanned directory.
2121
# Files are copied to this directory with full tree. As result, if we find
2222
# license offender, we can have full path (just scrape directory_name). We do this
2323
# magic because scancode allows to scan directories/one file.
2424
# 2. SPDX and license text is a must for all code files
2525

26-
import json
2726
import argparse
28-
import sys
29-
import os.path
27+
import json
3028
import logging
29+
import os.path
3130
import re
31+
import sys
32+
from enum import Enum
33+
34+
35+
class ReturnCode(Enum):
36+
"""Return codes."""
37+
38+
SUCCESS = 0
39+
ERROR = -1
3240

3341
userlog = logging.getLogger("scancode-evaluate")
3442
userlog.setLevel(logging.INFO)
35-
logfile = os.path.join(os.getcwd(), 'scancode-evaluate.log')
36-
log_file_handler = logging.FileHandler(logfile, mode='w')
37-
userlog.addHandler(log_file_handler)
43+
userlog.addHandler(
44+
logging.FileHandler(
45+
os.path.join(os.getcwd(), 'scancode-evaluate.log'), mode='w'
46+
)
47+
)
3848

3949
MISSING_LICENSE_TEXT = "Missing license header"
40-
MISSING_PERMISIVE_LICENSE_TEXT = "Non-permissive license"
50+
MISSING_PERMISSIVE_LICENSE_TEXT = "Non-permissive license"
4151
MISSING_SPDX_TEXT = "Missing SPDX license identifier"
4252

43-
def license_check(directory_name, file):
44-
""" Check licenses in the scancode json file for specified directory
53+
54+
def path_leaf(path):
55+
"""Return the leaf of a path."""
56+
head, tail = os.path.split(path)
57+
# Ensure the correct file name is returned if the file ends with a slash
58+
return tail or os.path.basename(head)
59+
60+
def has_permissive_text_in_scancode_output(scancode_output_data_file_licenses):
61+
"""Returns true if at list one license in the scancode output is permissive."""
62+
return any(
63+
scancode_output_data_file_license['category'] == 'Permissive'
64+
for scancode_output_data_file_license in scancode_output_data_file_licenses
65+
)
66+
67+
def has_spdx_text_in_scancode_output(scancode_output_data_file_licenses):
68+
"""Returns true if at least one license in the scancode output has the spdx identifier."""
69+
return any(
70+
'spdx' in scancode_output_data_file_license['matched_rule']['identifier']
71+
for scancode_output_data_file_license in scancode_output_data_file_licenses
72+
)
73+
74+
def has_spdx_text_in_analysed_file(scanned_file_content):
75+
"""Returns true if the file analysed by ScanCode contains SPDX identifier."""
76+
return bool(re.findall("SPDX-License-Identifier:?", scanned_file_content))
77+
78+
def license_check(scancode_output):
79+
"""Check licenses in the scancode json file for specified directory.
4580
4681
This function does not verify if file exists, should be done prior the call.
4782
4883
Args:
49-
directory_name - where scancode was run, used to scrape this from paths
5084
file - scancode json output file (output from scancode --license --json-pp)
5185
52-
Returns:
86+
Returns:
5387
0 if nothing found
5488
>0 - count how many license isses found
55-
-1 if any error in file licenses found
89+
ReturnCode.ERROR.value if any error in file licenses found
5690
"""
5791

5892
offenders = []
5993
try:
60-
# find all licenses in the files, must be licensed and permissive
61-
with open(file, 'r') as scancode_output:
62-
results = json.load(scancode_output)
63-
except ValueError:
64-
userlog.warning("JSON could not be decoded")
65-
return -1
66-
67-
try:
68-
for file in results['files']:
69-
license_offender = {}
70-
license_offender['file'] = file
71-
# ignore directory, not relevant here
72-
if license_offender['file']['type'] == 'directory':
94+
with open(scancode_output, 'r') as read_file:
95+
scancode_output_data = json.load(read_file)
96+
except json.JSONDecodeError as jex:
97+
userlog.warning("JSON could not be decoded, Invalid JSON in body: %s", jex)
98+
return ReturnCode.ERROR.value
99+
100+
if 'files' not in scancode_output_data:
101+
userlog.warning("Missing `files` attribute in %s" % (scancode_output))
102+
return ReturnCode.ERROR.value
103+
104+
for scancode_output_data_file in scancode_output_data['files']:
105+
try:
106+
if scancode_output_data_file['type'] != 'file':
73107
continue
74-
if not license_offender['file']['licenses']:
75-
license_offender['reason'] = MISSING_LICENSE_TEXT
76-
offenders.append(license_offender.copy())
108+
109+
if not scancode_output_data_file['licenses']:
110+
scancode_output_data_file['fail_reason'] = MISSING_LICENSE_TEXT
111+
offenders.append(scancode_output_data_file)
112+
# check the next file in the scancode output
77113
continue
78114

79-
found_spdx = spdx_check(offenders, license_offender)
115+
if not has_permissive_text_in_scancode_output(scancode_output_data_file['licenses']):
116+
scancode_output_data_file['fail_reason'] = MISSING_PERMISSIVE_LICENSE_TEXT
117+
offenders.append(scancode_output_data_file)
80118

81-
if not found_spdx:
119+
if not has_spdx_text_in_scancode_output(scancode_output_data_file['licenses']):
120+
# Scancode does not recognize license notice in Python file headers.
121+
# Issue: https://github.com/nexB/scancode-toolkit/issues/1913
122+
# Therefore check if the file tested by ScanCode actually has a licence notice.
123+
file_path = os.path.abspath(scancode_output_data_file['path'])
82124
try:
83-
# Issue reported here https://github.com/nexB/scancode-toolkit/issues/1913
84-
# We verify here if SPDX is not really there as SDPX is part of the license text
85-
# scancode has some problems detecting it properly
86-
with open(os.path.join(os.path.abspath(license_offender['file']['path'])), 'r') as spdx_file_check:
87-
filetext = spdx_file_check.read()
88-
matches = re.findall("SPDX-License-Identifier:?", filetext)
89-
if matches:
90-
continue
91-
license_offender['reason'] = MISSING_SPDX_TEXT
92-
offenders.append(license_offender.copy())
125+
with open(file_path, 'r') as read_file:
126+
scanned_file_content = read_file.read()
93127
except UnicodeDecodeError:
94-
# not valid file for license check
128+
userlog.warning("Unable to look for SPDX text in `{}`:".format(file_path))
129+
# Ignore files that cannot be decoded
130+
# check the next file in the scancode output
95131
continue
96-
except KeyError:
97-
userlog.warning("Invalid scancode json file")
98-
return -1
132+
if not has_spdx_text_in_analysed_file(scanned_file_content):
133+
scancode_output_data_file['fail_reason'] = MISSING_SPDX_TEXT
134+
offenders.append(scancode_output_data_file)
135+
except KeyError as error:
136+
userlog.warning("Could not find %s attribute in %s" % (str(error), scancode_output))
137+
return ReturnCode.ERROR.value
99138

100139
if offenders:
101140
userlog.warning("Found files with missing license details, please review and fix")
102141
for offender in offenders:
103-
userlog.warning("File: " + offender['file']['path'][len(directory_name):] + " " + "reason: " + offender['reason'])
142+
userlog.warning("File: %s reason: %s" % (path_leaf(offender['path']), offender['fail_reason']))
104143
return len(offenders)
105144

106-
107-
def spdx_check(offenders, license_offender):
108-
""" Parse through list of licenses to determine whether licenses are permissive
109-
@input list of offender, individual offender dict
110-
@output none
111-
"""
112-
found_spdx = False
113-
# iterate through licenses, stop once permissive license has been found
114-
for i in range(len(license_offender['file']['licenses'])):
115-
# is any of the licenses permissive ?
116-
if license_offender['file']['licenses'][i]['category'] == 'Permissive':
117-
# confirm that it has spdx license key
118-
if license_offender['file']['licenses'][i]['matched_rule']['identifier'].find("spdx") != -1:
119-
found_spdx = True
120-
# if no spdx found return anyway
121-
return found_spdx
122-
# otherwise file is missing permissive license
123-
license_offender['reason'] = MISSING_PERMISIVE_LICENSE_TEXT
124-
offenders.append(license_offender.copy())
125-
126-
# missing spdx and permissive license
127-
return found_spdx
128-
129145
def parse_args():
130146
parser = argparse.ArgumentParser(
131147
description="License check.")
@@ -135,15 +151,15 @@ def parse_args():
135151
help='Directory name where are files being checked')
136152
return parser.parse_args()
137153

138-
139154
if __name__ == "__main__":
155+
140156
args = parse_args()
141157
if args.file and os.path.isfile(args.file):
142-
count = license_check(args.directory_name, args.file)
143-
if count == 0:
144-
sys.exit(0)
145-
else:
146-
sys.exit(-1)
158+
sys.exit(
159+
ReturnCode.SUCCESS.value
160+
if license_check(args.file) == 0
161+
else ReturnCode.ERROR.value
162+
)
147163
else:
148164
userlog.warning("Could not find the scancode json file")
149-
sys.exit(-1)
165+
sys.exit(ReturnCode.ERROR.value)

tools/test/travis-ci/scancode_evaluate_test.py

Lines changed: 66 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,23 @@
44
# SPDX-License-Identifier: Apache-2.0
55
import importlib
66
import os
7-
import sys
8-
from unittest import TestCase
7+
import pytest
98

10-
# TODO: fix scancode to match python naming conventROOTi
11-
SCANCODE_EVALUATE = importlib.import_module("scancode-evaluate")
12-
license_check = SCANCODE_EVALUATE.license_check
9+
license_check = importlib.import_module("scancode-evaluate").license_check
1310

14-
ROOT = os.path.abspath(
15-
os.path.join(os.path.dirname(__file__))
11+
STUBS_PATH = os.path.join(
12+
os.path.abspath(os.path.join(os.path.dirname(__file__))), "scancode_test"
1613
)
1714

18-
# path to stub files
19-
stub_path = ROOT + "/scancode_test/"
20-
21-
# template copyright notices
22-
invalid_header_1 = "/* Copyright (C) Arm Limited, Inc - All Rights Reserved\
15+
HEADER_WITHOUT_SPDX = "/* Copyright (C) Arm Limited, Inc - All Rights Reserved\
2316
* Unauthorized copying of this. file, via any medium is strictly prohibited\
2417
* Proprietary and confidential\
2518
*/"
2619

27-
invalid_header_2 = "/* mbed Microcontroller Library\
20+
HEADER_WITH_SPDX = "/* mbed Microcontroller Library\
2821
* Copyright (c) 2006-2013 ARM Limited\
2922
*\
23+
* SPDX-License-Identifier: Apache-2.0\
3024
* Licensed under the Apache License, Version 2.0 (the \"License\");\
3125
* you may not use this file except in compliance with the License.\
3226
* You may obtain a copy of the License at\
@@ -40,67 +34,62 @@
4034
* limitations under the License.\
4135
*/"
4236

43-
44-
# implement test class
45-
class TestScancodeEvaluate(TestCase):
46-
""" Test scancode evaluation script """
47-
48-
def test_scancode_case_1(self):
49-
""" Test Case 1 -- faulty json file
50-
@inputs scancode_test_1.json
51-
@outputs -1 if any error in file licenses found
52-
"""
53-
expected_result = -1
54-
test_json = ROOT + "/scancode_test/scancode_test_1.json"
55-
56-
# pass json path to test function
57-
result = license_check(ROOT, test_json)
58-
59-
self.assertEqual(expected_result, result)
60-
61-
def test_scancode_case_2(self):
62-
""" Test Case 2 -- no errors in license headers, try multiple types i.e Apache-2.0, BSD3
63-
@inputs scancode_test_2.json [4 Apache-2.0, 4 BSD-3.0]
64-
@outputs 0
65-
"""
66-
expected_result = 0
67-
test_json = ROOT + "/scancode_test/scancode_test_2.json"
68-
69-
result = license_check(ROOT, test_json)
70-
self.assertEqual(expected_result, result, "False Negative(s)")
71-
72-
def test_scancode_case_3(self):
73-
""" Test Case 3 -- all files containing errors
74-
@inputs scancode_test_3.json [2 no header, 2 non-permissive + spdx, 1 missing SPDX]
75-
@output 5
76-
"""
77-
# create stub files with a non-permissive license and missing spdx
78-
for i in range(3, 6):
79-
with open(stub_path + "test" + str(i) + ".h", "w") as file:
80-
if i == 5:
81-
file.write(invalid_header_2)
82-
else:
83-
file.write(invalid_header_1)
84-
85-
expected_result = 7
86-
test_json = ROOT + "/scancode_test/scancode_test_3.json"
87-
88-
result = license_check(ROOT, test_json)
89-
90-
self.assertEqual(expected_result, result, "False Positive(s)")
91-
# delete stub files
92-
os.remove(stub_path + "test3.h")
93-
os.remove(stub_path + "test4.h")
94-
os.remove(stub_path + "test5.h")
95-
96-
def test_scancode_case_4(self):
97-
""" Test Case 4 -- license header permissive and non-permissive 'license' [FP]
98-
@inputs scancode_test_4.json
99-
@outputs 0
100-
"""
101-
expected_result = 0
102-
test_json = ROOT + "/scancode_test/scancode_test_4.json"
103-
104-
result = license_check(ROOT, test_json)
105-
106-
self.assertEqual(expected_result, result, "Non-Permissive Header False Positive")
37+
@pytest.fixture()
38+
def create_scanned_files():
39+
"""Create stub files.
40+
test3.h missing license notice
41+
test4.h with license notice
42+
test5.h with license notice
43+
"""
44+
file_paths = [
45+
os.path.join(STUBS_PATH, "test3.h"),
46+
os.path.join(STUBS_PATH, "test4.h"),
47+
os.path.join(STUBS_PATH, "test5.h")
48+
]
49+
for file_path in file_paths:
50+
with open(file_path, "w") as new_file:
51+
if file_path in [os.path.join(STUBS_PATH, "test3.h")]:
52+
new_file.write(HEADER_WITHOUT_SPDX)
53+
else:
54+
new_file.write(HEADER_WITH_SPDX)
55+
yield
56+
for file_path in file_paths:
57+
os.remove(file_path)
58+
59+
60+
class TestScancodeEvaluate:
61+
62+
def test_missing_files_attribute(self):
63+
""" Missing `files` attribute in JSON.
64+
@inputs scancode_test/scancode_test_1.json
65+
@outputs -1
66+
"""
67+
assert license_check(os.path.join(STUBS_PATH, "scancode_test_1.json")) == -1
68+
69+
def test_various_combinations_permissive_license_with_spdx(self):
70+
""" Various combinations where at least one license in
71+
a file is permissive and has spdx in the match.identifier
72+
attribute.
73+
@inputs scancode_test/scancode_test_2.json
74+
@outputs 0
75+
"""
76+
assert license_check(os.path.join(STUBS_PATH, "scancode_test_2.json")) == 0
77+
78+
def test_missing_license_permissive_license_and_spdx(self, create_scanned_files):
79+
""" Test four files scanned with various issues.
80+
test.h: Missing license text (error count += 1)
81+
test3.h: Missing `Permissive` license text and `spdx` in match.identifier and not in file tested by ScanCode (error count += 2)
82+
test4.h: Missing `Permissive` license text and `spdx` in match.identifier but found in file tested by ScanCode (error count += 1)
83+
test5.h: Missing `spdx` in match.identifier but found in file tested by ScanCode. (error count += 0)
84+
@inputs scancode_test/scancode_test_2.json
85+
@output 4
86+
"""
87+
assert license_check(os.path.join(STUBS_PATH, "scancode_test_3.json")) == 4
88+
89+
def test_permissive_license_no_spdx(self, create_scanned_files):
90+
""" Multiple `Permissive` licenses in one file but none with `spdx` in
91+
match.identifier and not in file tested by ScanCode (error count += 1)
92+
@inputs scancode_test/scancode_test_2.json
93+
@outputs 1
94+
"""
95+
assert license_check(os.path.join(STUBS_PATH, "scancode_test_4.json")) == 1

0 commit comments

Comments
 (0)