├── .bumpversion.cfg
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── PULL_REQUEST_TEMPLATE.md
├── release-drafter-config.yml
└── workflows
│ ├── publish-release.yml
│ ├── pull-request.yml
│ └── release-drafter-config.yml
├── .reuse
└── dep5
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── LICENSES
├── Apache-2.0.txt
├── LicenseRef-MIT-like.txt
└── MIT.txt
├── MANIFEST.in
├── README.md
├── requirements-dev.txt
├── requirements.txt
├── setup.py
├── src
└── fosslight_source
│ ├── __init__.py
│ ├── _help.py
│ ├── _license_matched.py
│ ├── _parsing_scancode_file_item.py
│ ├── _parsing_scanoss_file.py
│ ├── _scan_item.py
│ ├── cli.py
│ ├── run_scancode.py
│ ├── run_scanoss.py
│ └── run_spdx_extractor.py
├── tests
├── cli_test.py
├── json_result
│ └── scan_has_error.json
├── scancode_raw.json
├── test_files
│ ├── LICENSE
│ ├── Sample_MIT_LICENSE.txt
│ ├── dual.txt
│ ├── run_scancode.py
│ ├── run_scancode2.py
│ ├── sample.cpp
│ ├── sample_license.txt
│ ├── spdx_lic.txt
│ ├── temp.cpp
│ ├── test
│ │ ├── MIT_TEST.txt
│ │ └── temp.cpp
│ ├── test_known_spdx.txt
│ └── test_unknown_spdx.txt
└── test_tox.py
└── tox.ini
/.bumpversion.cfg:
--------------------------------------------------------------------------------
1 | [bumpversion]
2 | commit = True
3 | tag = False
4 | message = Bump version: {current_version} → {new_version}
5 | current_version = 2.1.8
6 |
7 | [bumpversion:file:setup.py]
8 | search = '{current_version}'
9 | replace = '{new_version}'
10 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: soimkim
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 |
16 | **Expected behavior**
17 | A clear and concise description of what you expected to happen.
18 |
19 | **System environment (please complete the following information):**
20 | - OS: [e.g. Ubuntu 16.04, Windows, Mac OS]
21 | - Python : [e.g. python3.7]
22 |
23 | **Additional context**
24 | Add any other context about the problem here.
25 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: enhancement
6 | assignees: soimkim
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ## Description
2 |
5 |
6 | ## Type of change
7 |
10 | - [ ] Bug fix (non-breaking change which fixes an issue)
11 | - [ ] New feature (non-breaking change which adds functionality)
12 | - [ ] Documentation update
13 | - [ ] Refactoring, Maintenance
14 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
15 |
16 |
--------------------------------------------------------------------------------
/.github/release-drafter-config.yml:
--------------------------------------------------------------------------------
1 | name-template: 'v$RESOLVED_VERSION'
2 | tag-template: 'v$RESOLVED_VERSION'
3 | categories:
4 | - title: '🚀 Features'
5 | label: 'enhancement'
6 | - title: '🐛 Hotfixes'
7 | labels:
8 | - 'bug'
9 | - 'bug fix'
10 | - title: '🔧 Maintenance'
11 | labels:
12 | - 'documentation'
13 | - 'chore'
14 | change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
15 | version-resolver:
16 | major:
17 | labels:
18 | - 'major'
19 | minor:
20 | labels:
21 | - 'minor'
22 | patch:
23 | labels:
24 | - 'patch'
25 | default: patch
26 | template: |
27 | ## Changes
28 | $CHANGES
29 |
--------------------------------------------------------------------------------
/.github/workflows/publish-release.yml:
--------------------------------------------------------------------------------
1 | # 1. Update changelog
2 | # 2. Upload a Python Package using Twine
3 |
4 | name: Release fosslight_source
5 |
6 | on:
7 | release:
8 | types: [published]
9 |
10 | jobs:
11 | update-changelog:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v3
15 | with:
16 | fetch-depth: 0
17 | - name: Get Release
18 | uses: bruceadams/get-release@v1.3.2
19 | id: get_release
20 | env:
21 | GITHUB_TOKEN: ${{ github.token }}
22 | - name: Bump up version
23 | env:
24 | NEW_TAG: ${{ steps.get_release.outputs.tag_name }}
25 | run: |
26 | pip install --upgrade bumpversion
27 | LAST_TWO_TAGS=$(git for-each-ref refs/tags/ --count=2 --sort=-v:refname --format="%(refname:short)")
28 | LAST_ONE=$(echo $LAST_TWO_TAGS | cut -d' ' -f 2)
29 | last_version=$(echo ${LAST_ONE//v/""})
30 | echo Last version: ${last_version}
31 | new_version=$(echo ${NEW_TAG//v/""})
32 | echo New version: ${new_version}
33 | git config --global user.name "github-actions[bot]"
34 | git config --global user.email "fosslight-dev@lge.com"
35 | bumpversion --current-version $last_version --new-version $new_version setup.py
36 | - name: update changelog with gren
37 | env:
38 | GREN_GITHUB_TOKEN: ${{ secrets.TOKEN }}
39 | run: |
40 | npm install github-release-notes@0.17.3
41 | node_modules/.bin/gren changelog --override
42 | - name: Commit files
43 | run: |
44 | git config --local user.name "github-actions[bot]"
45 | git add CHANGELOG.md
46 | git commit -m "Update ChangeLog"
47 | - name: Push changes
48 | uses: ad-m/github-push-action@master
49 | with:
50 | github_token: ${{ secrets.TOKEN }}
51 | branch: main
52 |
53 | deploy:
54 | runs-on: ubuntu-latest
55 | needs: update-changelog
56 | steps:
57 | - uses: actions/checkout@v3
58 | with:
59 | ref: main
60 | - name: Set up Python
61 | uses: actions/setup-python@v4
62 | with:
63 | python-version: '3.8'
64 | - name: Install dependencies
65 | run: |
66 | python -m pip install --upgrade pip
67 | pip install setuptools wheel twine
68 | - name: Build and publish
69 | env:
70 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
71 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
72 | run: |
73 | python setup.py sdist bdist_wheel
74 | twine upload dist/*
75 |
--------------------------------------------------------------------------------
/.github/workflows/pull-request.yml:
--------------------------------------------------------------------------------
1 | # Running tests with tox for releasing new version
2 |
3 | name: Pull requests fosslight_source_scanner
4 |
5 | on:
6 | pull_request:
7 | branches:
8 | - '*'
9 |
10 | jobs:
11 | check-commit-message:
12 | uses: fosslight/.github/.github/workflows/base-check-commit-message.yml@main
13 | secrets:
14 | envPAT: ${{ secrets.GITHUB_TOKEN }}
15 |
16 | build:
17 | strategy:
18 | matrix:
19 | python-version: [3.8, 3.11]
20 | os: [ubuntu-latest, windows-latest]
21 | runs-on: ${{ matrix.os }}
22 | steps:
23 | - uses: actions/checkout@v3
24 | - name: Set up Python ${{ matrix.python-version }}
25 | uses: actions/setup-python@v4
26 | with:
27 | python-version: ${{ matrix.python-version }}
28 | - name: Install dependencies
29 | run: |
30 | python -m pip install --upgrade pip
31 | pip install tox
32 | - name: Run Tox
33 | run: |
34 | tox -e release
35 | build_macos:
36 | strategy:
37 | matrix:
38 | python-version: [3.9, 3.11]
39 | runs-on: macos-latest
40 | steps:
41 | - uses: actions/checkout@v3
42 | - name: Set up Python ${{ matrix.python-version }}
43 | uses: actions/setup-python@v4
44 | with:
45 | python-version: ${{ matrix.python-version }}
46 | - name: Install dependencies
47 | run: |
48 | brew install openssl
49 | brew install libmagic
50 | brew install postgresql
51 | python -m pip install --upgrade pip
52 | pip install tox
53 | - name: Run Tox
54 | run: |
55 | tox -e release
56 |
57 | reuse:
58 | runs-on: ubuntu-latest
59 | steps:
60 | - uses: actions/checkout@v3
61 | - name: REUSE Compliance Check
62 | uses: fsfe/reuse-action@v1
63 |
--------------------------------------------------------------------------------
/.github/workflows/release-drafter-config.yml:
--------------------------------------------------------------------------------
1 | name: Release Drafter
2 | on:
3 | push:
4 | branches:
5 | - main
6 | jobs:
7 | update_release_draft:
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: release-drafter/release-drafter@v5
11 | with:
12 | config-name: release-drafter-config.yml
13 | env:
14 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
15 |
--------------------------------------------------------------------------------
/.reuse/dep5:
--------------------------------------------------------------------------------
1 | Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2 | Upstream-Name: FOSSLight Source
3 | Source: https://github.com/fosslight/fosslight_source
4 |
5 | Files: *.md
6 | Copyright: 2021 LG Electronics
7 | License: Apache-2.0
8 |
9 | Files: tests/*
10 | Copyright: 2021 LG Electronics
11 | License: Apache-2.0
12 |
13 | Files: .github/*
14 | Copyright: 2021 LG Electronics
15 | License: Apache-2.0
16 |
17 | Files: MANIFEST.in
18 | Copyright: 2021 LG Electronics
19 | License: Apache-2.0
20 |
21 | Files: requirements*.txt
22 | Copyright: 2021 LG Electronics
23 | License: Apache-2.0
24 |
25 | Files: .bumpversion.cfg
26 | Copyright: 2021 LG Electronics
27 | License: Apache-2.0
28 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## v2.1.8 (09/04/2025)
4 | ## Changes
5 | ## 🔧 Maintenance
6 |
7 | - Fix api_limit_exceed_parameter @JustinWonjaePark (#206)
8 |
9 | ---
10 |
11 | ## v2.1.7 (26/02/2025)
12 | ## Changes
13 | ## 🔧 Maintenance
14 |
15 | - Update SCANOSS version and redirect log @JustinWonjaePark (#204)
16 |
17 | ---
18 |
19 | ## v2.1.6 (06/02/2025)
20 | ## Changes
21 | ## 🐛 Hotfixes
22 |
23 | - Fix scancode copyright scanning err @dd-jy (#203)
24 | - Fix exclude error @JustinWonjaePark (#201)
25 |
26 | ---
27 |
28 | ## v2.1.5 (09/12/2024)
29 | ## Changes
30 | ## 🐛 Hotfixes
31 |
32 | - Fix the bug @dd-jy (#200)
33 |
34 | ---
35 |
36 | ## v2.1.4 (05/12/2024)
37 | ## Changes
38 | ## 🚀 Features
39 |
40 | - Support cycloneDX format @dd-jy (#199)
41 |
42 | ---
43 |
44 | ## v2.1.3 (13/11/2024)
45 | ## Changes
46 | - Fix errors related to SCANOSS @JustinWonjaePark (#198)
47 |
48 | ## 🔧 Maintenance
49 |
50 | - Fix the cover_comment @ethanleelge (#197)
51 |
52 | ---
53 |
54 | ## v2.1.2 (18/10/2024)
55 | ## Changes
56 | ## 🔧 Maintenance
57 |
58 | - Print option name with error msg @bjk7119 (#195)
59 | - Fix the scancode ver for macos @dd-jy (#194)
60 |
61 | ---
62 |
63 | ## v2.1.1 (13/10/2024)
64 | ## Changes
65 | ## 🔧 Maintenance
66 |
67 | - Remove typecode-libmagic from requirements.txt @soonhong99 (#192)
68 |
69 | ---
70 |
71 | ## v2.1.0 (08/10/2024)
72 | ## Changes
73 | ## 🚀 Features
74 |
75 | - Support spdx (only Linux) @dd-jy (#190)
76 |
77 | ## 🔧 Maintenance
78 |
79 | - Tox to pytest @hkkim2021 (#188)
80 | - Add type hint @hkkim2021 (#184)
81 |
82 | ---
83 |
84 | ## v2.0.0 (06/09/2024)
85 | ## Changes
86 | ## 🔧 Maintenance
87 |
88 | - Refactoring OSS Item @soimkim (#183)
89 |
90 | ---
91 |
92 | ## v1.7.16 (06/09/2024)
93 | ## Changes
94 | ## 🔧 Maintenance
95 |
96 | - Limit installation to fosslight_util 1.4.* @soimkim (#182)
97 | - Change SCANOSS Invocation Method from Command Line to Library Function @YongGoose (#178)
98 | - Modify error comment @bjk7119 (#176)
99 | - Add --ignore-cert-errors to ScanOSS command @soimkim (#174)
100 |
101 | ---
102 |
103 | ## v1.7.15 (17/07/2024)
104 | ## Changes
105 | ## 🐛 Hotfixes
106 |
107 | - Version up FOSSLight util to fix default file bug @JustinWonjaePark (#170)
108 | - Complying with SPDX License expression spec @JustinWonjaePark (#167)
109 |
110 | ---
111 |
112 | ## v1.7.14 (15/07/2024)
113 | ## 🚀 Features
114 |
115 | - Enable multiple input for -f and -o option @JustinWonjaePark (#164)
116 |
117 | ## 🐛 Hotfixes
118 |
119 | - Update scancode version for mac @soimkim (#168)
120 | - Fix SPDX expression split bug @JustinWonjaePark (#165)
121 | - Revert "Fix SPDX expression split bug" @soimkim (#169)
122 |
123 | ## 🔧 Maintenance
124 |
125 | - Check hidden files and mark 'Exlcude'. @JustinWonjaePark (#166)
126 |
127 | ---
128 |
129 | ## v1.7.13 (25/06/2024)
130 | ## Changes
131 | ## 🐛 Hotfixes
132 |
133 | - Amend exclude option @SeongjunJo (#162)
134 |
135 | ---
136 |
137 | ## v1.7.12 (21/06/2024)
138 | ## Changes
139 | ## 🔧 Maintenance
140 |
141 | - Update scancode version for web service @soimkim (#161)
142 |
143 | ---
144 |
145 | ## v1.7.11 (11/06/2024)
146 | ## Changes
147 | ## 🐛 Hotfixes
148 |
149 | - Bug fix related to license duplication @soimkim (#159)
150 |
151 | ## 🔧 Maintenance
152 |
153 | - Check empty license @soimkim (#160)
154 |
155 | ---
156 |
157 | ## v1.7.10 (11/06/2024)
158 | ## Changes
159 | ## 🐛 Hotfixes
160 |
161 | - Move method to limit license characters @soimkim (#158)
162 |
163 | ---
164 |
165 | ## v1.7.9 (11/06/2024)
166 | ## Changes
167 | ## 🔧 Maintenance
168 |
169 | - Limit the maximum number of characters in the license @soimkim (#157)
170 |
171 | ---
172 |
173 | ## v1.7.8 (10/06/2024)
174 | ## Changes
175 | ## 🚀 Features
176 |
177 | - Supports for excluding paths @SeongjunJo (#154)
178 |
179 | ## 🔧 Maintenance
180 |
181 | - Modify column name @bjk7119 (#156)
182 | - Change column name for SCANOSS reference @JustinWonjaePark (#155)
183 |
184 | ---
185 |
186 | ## v1.7.7 (26/04/2024)
187 | ## Changes
188 | ## 🚀 Features
189 |
190 | - Add detection summary message (cover sheet) @dd-jy (#153)
191 |
192 | ## 🔧 Maintenance
193 |
194 | - Check notice file name for scancode @JustinWonjaePark (#152)
195 |
196 | ---
197 |
198 | ## v1.7.6 (29/02/2024)
199 | ## Changes
200 | ## 🐛 Hotfixes
201 |
202 | - Fix cli_test log path @JustinWonjaePark (#148)
203 |
204 | ## 🔧 Maintenance
205 |
206 | - Change SCANOSS thread using -c option @JustinWonjaePark (#151)
207 | - Remove fosslight_convert @JustinWonjaePark (#150)
208 |
209 | ---
210 |
211 | ## v1.7.5 (19/10/2023)
212 | ## Changes
213 | ## 🔧 Maintenance
214 |
215 | - Merge copyrights with new line @JustinWonjaePark (#147)
216 | - Add .in and .po to the excluded extensions @JustinWonjaePark (#146)
217 |
218 | ---
219 |
220 | ## v1.7.4 (13/10/2023)
221 | ## Changes
222 | - Optimize Dockerfile to reduce image size @jaehee329 (#136)
223 |
224 | ## 🐛 Hotfixes
225 |
226 | - Modify it to work on mac ARM chip @soimkim (#145)
227 |
228 | ## 🔧 Maintenance
229 |
230 | - Upgrade minimum version of python to 3.8 @JustinWonjaePark (#144)
231 | - Modify run_scanners to return @soimkim (#143)
232 | - Fetch base-check-commit-message.yml from .github @jaehee329 (#142)
233 |
234 | ---
235 |
236 | ## v1.7.3 (14/09/2023)
237 | ## Changes
238 | ## 🔧 Maintenance
239 |
240 | - Create run_scanners for api and exclude unwanted outputs @JustinWonjaePark (#140)
241 | - Add test for fl scanner and fl android @JustinWonjaePark (#139)
242 |
243 | ---
244 |
245 | ## v1.7.2 (31/08/2023)
246 | ## Changes
247 | ## 🐛 Hotfixes
248 |
249 | - Fix vulnerability from requirements.txt @JustinWonjaePark (#138)
250 |
251 | ---
252 |
253 | ## v1.7.1 (31/08/2023)
254 | ## Changes
255 | ## 🔧 Maintenance
256 |
257 | - Priority change between Download Location extraction and scanner operation @JustinWonjaePark (#133)
258 |
259 | ---
260 |
261 | ## v1.7.0 (14/08/2023)
262 | ## Changes
263 | - Fix the bug when nothing is detected @soimkim (#134)
264 |
265 | ## 🚀 Features
266 |
267 | - Load v32 and later of ScanCode @soimkim (#131)
268 |
269 | ## 🔧 Maintenance
270 |
271 | - Fix the scancdoe and util version @dd-jy (#132)
272 |
273 | ---
274 |
275 | ## v1.6.32 (03/08/2023)
276 | ## Changes
277 | ## 🐛 Hotfixes
278 |
279 | - Fix the util version @dd-jy (#130)
280 |
281 | ---
282 |
283 | ## v1.6.31 (03/08/2023)
284 | ## Changes
285 | ## 🐛 Hotfixes
286 |
287 | - Revert the scancode-toolkit version @dd-jy (#129)
288 |
289 | ## 🔧 Maintenance
290 |
291 | - Remove sorting @JustinWonjaePark (#128)
292 |
293 | ---
294 |
295 | ## v1.6.30 (25/07/2023)
296 | ## Changes
297 | ## 🔧 Maintenance
298 |
299 | - Update scancode-toolkit version @dd-jy (#127)
300 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | opensource@lge.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributing
2 |
3 | Hi! I'm really appreciate that you'd like to contribute to this project. Your help is essential for keeping it great.
4 |
5 | ## Submitting a pull request
6 |
7 | 1. ```Fork``` and clone the repository
8 | 2. Create a new branch: `git checkout -b my-branch-name`
9 | 3. Make your change and make sure it works properly.
10 | 4. Push to your fork and submit a pull request.
11 | 5. When you write to PR template, you can add labels based on your type of changes.
12 | -  : Bug fix
13 | -  : New feature
14 | -  : Documentation update
15 | -  : Refactoring, Maintenance
16 | 6. Please wait for your pull request to be reviewed and merged!
17 |
18 | Here are a few things you can do that will increase the likelihood of your pull request being accepted:
19 |
20 | - Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
21 | - Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
22 |
23 | Work in Progress pull request are also welcome to get feedback early on, or if there is something blocked you.
24 |
25 | ## Resources
26 |
27 | - [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
28 | - [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)
29 | - [GitHub Help](https://help.github.com)
30 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021 LG Electronics Inc.
2 | # SPDX-License-Identifier: Apache-2.0
3 | FROM python:3.8-slim-buster
4 |
5 | RUN ln -sf /bin/bash /bin/sh && \
6 | apt-get update && \
7 | apt-get install --no-install-recommends -y \
8 | build-essential \
9 | python3 python3-distutils python3-pip python3-dev python3-magic \
10 | libxml2-dev libxslt1-dev libhdf5-dev bzip2 xz-utils zlib1g libpopt0 && \
11 | apt-get clean && \
12 | rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
13 |
14 | WORKDIR /app
15 |
16 | COPY . /app
17 |
18 | RUN pip3 install --upgrade pip && \
19 | pip3 install . && \
20 | pip3 install dparse && \
21 | rm -rf ~/.cache/pip /root/.cache/pipe
22 |
23 | ENTRYPOINT ["/usr/local/bin/fosslight_source"]
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/LICENSES/Apache-2.0.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/LICENSES/LicenseRef-MIT-like.txt:
--------------------------------------------------------------------------------
1 | # This License text is the License text for testing unknown-spdx.
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/LICENSES/MIT.txt:
--------------------------------------------------------------------------------
1 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
2 |
3 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
4 |
5 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include LICENSE
2 | include README.md
3 | include requirements.txt
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 | [Korean]
8 |
9 |
10 |
11 | # FOSSLight Source Scanner
12 |
13 |
[](https://api.reuse.software/info/github.com/fosslight/fosslight_source_scanner) [](https://fosslight.org/fosslight-guide-en/scanner/2_source.html)
14 |
15 |
16 | ```note
17 | Detect the license for the source code.
18 | Use Source Code Scanner and process the scanner results.
19 | ```
20 |
21 | **FOSSLight Source Scanner** uses source code scanners, [ScanCode][sc] and [SCANOSS][scanoss]. [ScanCode][sc] detects copyright and license phrases contained in the file and [SCANOSS][scanoss] searches OSS Name, OSS Version, download location, copyright and license information from [OSSKB][osskb]. Some files (ex- build script), binary files, directory and files in specific directories (ex-test) are excluded from the result. And removes words such as "-only" and "-old-style" from the license name to be printed. The output result is generated in spreadsheet format.
22 |
23 |
24 | [sc]: https://github.com/nexB/scancode-toolkit
25 | [scanoss]: https://github.com/scanoss/scanoss.py
26 | [osskb]: https://osskb.org/
27 |
28 |
29 | ## 📖 User Guide
30 |
31 | We describe the user guide in the FOSSLight guide page.
32 | Please see the [**User Guide**](https://fosslight.org/fosslight-guide-en/scanner/2_source.html) for more information on how to install and run it.
33 |
34 |
35 | ## 👏 Contributing Guide
36 |
37 | We always welcome your contributions.
38 | Please see the [CONTRIBUTING guide](https://fosslight.org/hub-guide-en/contribution/1_contribution.html) for how to contribute.
39 |
40 |
41 | ## 📄 License
42 |
43 | FOSSLight Source Scanner is Apache-2.0, as found in the [LICENSE][l] file.
44 |
45 | [l]: https://github.com/fosslight/fosslight_source_scanner/blob/main/LICENSE
46 |
--------------------------------------------------------------------------------
/requirements-dev.txt:
--------------------------------------------------------------------------------
1 | tox
2 | pytest
3 | pytest-cov
4 | pytest-flake8
5 | flake8==3.9.2
6 | dataclasses
7 | scanoss
8 | importlib-metadata==4.12.0
9 | pytest-xdist
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pyparsing
2 | scanoss>=1.18.0
3 | XlsxWriter
4 | fosslight_util>=2.1.10
5 | PyYAML
6 | wheel>=0.38.1
7 | intbitset
8 | fosslight_binary>=5.0.0
9 | scancode-toolkit==32.0.*;sys_platform=="darwin"
10 | scancode-toolkit==32.2.*;sys_platform!="darwin"
11 | psycopg2-binary==2.9.9
12 | beautifulsoup4==4.12.*
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2021 LG Electronics
4 | # SPDX-License-Identifier: Apache-2.0
5 | from codecs import open
6 | from setuptools import setup, find_packages
7 |
8 | with open('README.md', 'r', 'utf-8') as f:
9 | readme = f.read()
10 |
11 | with open('requirements.txt', 'r', 'utf-8') as f:
12 | required = f.read().splitlines()
13 |
14 | if __name__ == "__main__":
15 | setup(
16 | name='fosslight_source',
17 | version='2.1.8',
18 | package_dir={"": "src"},
19 | packages=find_packages(where='src'),
20 | description='FOSSLight Source Scanner',
21 | long_description=readme,
22 | long_description_content_type='text/markdown',
23 | license='Apache-2.0',
24 | author='LG Electronics',
25 | url='https://github.com/fosslight/fosslight_source_scanner',
26 | download_url='https://github.com/fosslight/fosslight_source_scanner',
27 | classifiers=['License :: OSI Approved :: Apache Software License',
28 | "Programming Language :: Python :: 3",
29 | "Programming Language :: Python :: 3.8",
30 | "Programming Language :: Python :: 3.9",
31 | "Programming Language :: Python :: 3.10",
32 | "Programming Language :: Python :: 3.11", ],
33 | python_requires=">=3.8",
34 | install_requires=required,
35 | entry_points={
36 | "console_scripts": [
37 | "fosslight_source = fosslight_source.cli:main",
38 | "run_scancode = fosslight_source.run_scancode:main"
39 | ]
40 | }
41 | )
42 |
--------------------------------------------------------------------------------
/src/fosslight_source/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fosslight/fosslight_source_scanner/2d80c3b75424bddfe52ec8b62af2526c2308b55e/src/fosslight_source/__init__.py
--------------------------------------------------------------------------------
/src/fosslight_source/_help.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2021 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 | from fosslight_util.help import PrintHelpMsg, print_package_version
6 |
7 | _HELP_MESSAGE_SOURCE_SCANNER = """
8 | FOSSLight Source Scanner Usage: fosslight_source [option1] [option2] ...
9 |
10 | FOSSLight Source Scanner uses ScanCode and SCANOSS, the source code scanners, to detect
11 | the copyright and license phrases contained in the file.
12 | Some files (ex- build script), binary files, directory and files in specific
13 | directories (ex-test) are excluded from the result.
14 |
15 | Options:
16 | Optional
17 | -p \t Path to analyze source (Default: current directory)
18 | -h\t\t\t Print help message
19 | -v\t\t\t Print FOSSLight Source Scanner version
20 | -m\t\t\t Print additional information for scan result on separate sheets
21 | -e \t\t Path to exclude from analysis (file and directory)
22 | -o \t Output path (Path or file name)
23 | -f \t\t Output file formats (excel, csv, opossum, yaml). Multi formats are supported.
24 | Options only for FOSSLight Source Scanner
25 | -s \t Select which scanner to be run (scancode, scanoss, all)
26 | -j\t\t\t Generate raw result of scanners in json format
27 | -t \t\t Stop scancode scanning if scanning takes longer than a timeout in seconds.
28 | -c \t\t Select the number of cores to be scanned with ScanCode or threads with SCANOSS.
29 | --no_correction\t Enter if you don't want to correct OSS information with sbom-info.yaml
30 | --correct_fpath Path to the sbom-info.yaml file"""
31 |
32 |
33 | def print_version(pkg_name: str) -> None:
34 | print_package_version(pkg_name, "FOSSLight Source Scanner Version:")
35 |
36 |
37 | def print_help_msg_source_scanner() -> None:
38 | helpMsg = PrintHelpMsg(_HELP_MESSAGE_SOURCE_SCANNER)
39 | helpMsg.print_help_msg(True)
40 |
--------------------------------------------------------------------------------
/src/fosslight_source/_license_matched.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2021 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 | import logging
6 | import fosslight_util.constant as constant
7 |
8 | logger = logging.getLogger(constant.LOGGER_NAME)
9 | HEADER = ['No', 'Category', 'License',
10 | 'Matched Text', 'File Count', 'Files']
11 | HEADER_32_LATER = ['No', 'License', 'Matched Text',
12 | 'File Count', 'Files']
13 | LOW_PRIORITY = ['Permissive', 'Public Domain']
14 |
15 |
16 | class MatchedLicense:
17 | license = ""
18 | files = []
19 | category = ""
20 | matched_text = ""
21 | priority = 0
22 |
23 | def __init__(self, lic: str, category: str, text: str, file: str) -> None:
24 | self.files = [file]
25 | self.license = lic
26 | self.matched_text = text
27 | self.set_category(category)
28 |
29 | def __del__(self) -> None:
30 | pass
31 |
32 | def set_license(self, value: str) -> None:
33 | self.license = value
34 |
35 | def set_files(self, value: str) -> None:
36 | if value not in self.files:
37 | self.files.append(value)
38 |
39 | def set_category(self, value: str) -> None:
40 | self.category = value
41 | if value in LOW_PRIORITY:
42 | self.priority = 1
43 | else:
44 | self.priority = 0
45 |
46 | def set_matched_text(self, value: str) -> None:
47 | self.matched_text = value
48 |
49 | def get_row_to_print(self, result_for_32_earlier: bool = True) -> list:
50 | if result_for_32_earlier:
51 | print_rows = [self.category, self.license, self.matched_text, str(len(self.files)), ','.join(self.files)]
52 | else:
53 | print_rows = [self.license, self.matched_text, str(len(self.files)), ','.join(self.files)]
54 | return print_rows
55 |
56 |
57 | def get_license_list_to_print(license_list: dict) -> list:
58 | result_for_32_earlier = any([value.category for key, value in license_list.items()])
59 | license_items = license_list.values()
60 | license_items = sorted(license_items, key=lambda row: (row.priority, row.category, row.license))
61 | license_rows = [lic_item.get_row_to_print(result_for_32_earlier) for lic_item in license_items]
62 | license_rows.insert(0, HEADER if result_for_32_earlier else HEADER_32_LATER)
63 | return license_rows
64 |
--------------------------------------------------------------------------------
/src/fosslight_source/_parsing_scancode_file_item.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 | import logging
8 | import re
9 | import fosslight_util.constant as constant
10 | from ._license_matched import MatchedLicense
11 | from ._scan_item import SourceItem
12 | from ._scan_item import is_exclude_dir
13 | from ._scan_item import is_exclude_file
14 | from ._scan_item import replace_word
15 | from ._scan_item import is_notice_file
16 | from typing import Tuple
17 |
18 | logger = logging.getLogger(constant.LOGGER_NAME)
19 | _exclude_directory = ["test", "tests", "doc", "docs"]
20 | _exclude_directory = [os.path.sep + dir_name +
21 | os.path.sep for dir_name in _exclude_directory]
22 | _exclude_directory.append("/.")
23 | REMOVE_LICENSE = ["warranty-disclaimer"]
24 | regex = re.compile(r'licenseref-(\S+)', re.IGNORECASE)
25 | find_word = re.compile(rb"SPDX-PackageDownloadLocation\s*:\s*(\S+)", re.IGNORECASE)
26 | KEYWORD_SPDX_ID = r'SPDX-License-Identifier\s*[\S]+'
27 | KEYWORD_DOWNLOAD_LOC = r'DownloadLocation\s*[\S]+'
28 | KEYWORD_SCANCODE_UNKNOWN = "unknown-spdx"
29 | SPDX_REPLACE_WORDS = ["(", ")"]
30 | KEY_AND = r"(?<=\s)and(?=\s)"
31 | KEY_OR = r"(?<=\s)or(?=\s)"
32 |
33 |
34 | def get_error_from_header(header_item: list) -> Tuple[bool, str]:
35 | has_error = False
36 | str_error = ""
37 | key_error = "errors"
38 |
39 | try:
40 | for header in header_item:
41 | if key_error in header:
42 | errors = header[key_error]
43 | error_cnt = len(errors)
44 | if error_cnt > 0:
45 | has_error = True
46 | str_error = '{}...({})'.format(errors[0], error_cnt)
47 | break
48 | except Exception as ex:
49 | logger.debug(f"Error_parsing_header: {ex}")
50 | return has_error, str_error
51 |
52 |
53 | def parsing_scancode_32_earlier(scancode_file_list: list, has_error: bool = False) -> Tuple[bool, list, list, dict]:
54 | rc = True
55 | msg = []
56 | scancode_file_item = []
57 | license_list = {} # Key :[license]+[matched_text], value: MatchedLicense()
58 | prev_dir = ""
59 | prev_dir_value = False
60 |
61 | if scancode_file_list:
62 | for file in scancode_file_list:
63 | try:
64 | is_dir = False
65 | file_path = file.get("path", "")
66 | if not file_path:
67 | continue
68 | is_binary = file.get("is_binary", False)
69 | if "type" in file:
70 | is_dir = file["type"] == "directory"
71 | if is_dir:
72 | prev_dir_value = is_exclude_dir(file_path)
73 | prev_dir = file_path
74 |
75 | if not is_binary and not is_dir:
76 | licenses = file.get("licenses", [])
77 | copyright_list = file.get("copyrights", [])
78 |
79 | result_item = SourceItem(file_path)
80 |
81 | if has_error and "scan_errors" in file:
82 | error_msg = file.get("scan_errors", [])
83 | if len(error_msg) > 0:
84 | result_item.comment = ",".join(error_msg)
85 | scancode_file_item.append(result_item)
86 | continue
87 | copyright_value_list = []
88 | for x in copyright_list:
89 | latest_key_data = x.get("copyright", "")
90 | if latest_key_data:
91 | copyright_data = latest_key_data
92 | else:
93 | copyright_data = x.get("value", "")
94 | if copyright_data:
95 | try:
96 | copyright_data = re.sub(KEYWORD_SPDX_ID, '', copyright_data, flags=re.I)
97 | copyright_data = re.sub(KEYWORD_DOWNLOAD_LOC, '', copyright_data, flags=re.I).strip()
98 | except Exception:
99 | pass
100 | copyright_value_list.append(copyright_data)
101 |
102 | result_item.copyright = copyright_value_list
103 |
104 | # Set the license value
105 | license_detected = []
106 | if licenses is None or licenses == "":
107 | continue
108 |
109 | license_expression_list = file.get("license_expressions", {})
110 | if len(license_expression_list) > 0:
111 | license_expression_list = [
112 | x.lower() for x in license_expression_list
113 | if x is not None]
114 |
115 | for lic_item in licenses:
116 | license_value = ""
117 | key = lic_item.get("key", "")
118 | if key in REMOVE_LICENSE:
119 | if key in license_expression_list:
120 | license_expression_list.remove(key)
121 | continue
122 | spdx = lic_item.get("spdx_license_key", "")
123 | # logger.debug("LICENSE_KEY:"+str(key)+",SPDX:"+str(spdx))
124 |
125 | if key is not None and key != "":
126 | key = key.lower()
127 | license_value = key
128 | if key in license_expression_list:
129 | license_expression_list.remove(key)
130 | if spdx is not None and spdx != "":
131 | # Print SPDX instead of Key.
132 | license_value = spdx.lower()
133 |
134 | if license_value != "":
135 | if key == KEYWORD_SCANCODE_UNKNOWN:
136 | try:
137 | matched_txt = lic_item.get("matched_text", "").lower()
138 | matched = regex.search(matched_txt)
139 | if matched:
140 | license_value = str(matched.group())
141 | except Exception:
142 | pass
143 |
144 | for word in replace_word:
145 | if word in license_value:
146 | license_value = license_value.replace(word, "")
147 | license_detected.append(license_value)
148 |
149 | # Add matched licenses
150 | if "category" in lic_item:
151 | lic_category = lic_item["category"]
152 | if "matched_text" in lic_item:
153 | lic_matched_text = lic_item["matched_text"]
154 | lic_matched_key = license_value + lic_matched_text
155 | if lic_matched_key in license_list:
156 | license_list[lic_matched_key].set_files(file_path)
157 | else:
158 | lic_info = MatchedLicense(license_value, lic_category, lic_matched_text, file_path)
159 | license_list[lic_matched_key] = lic_info
160 |
161 | matched_rule = lic_item.get("matched_rule", {})
162 | result_item.is_license_text = matched_rule.get("is_license_text", False)
163 |
164 | if len(license_detected) > 0:
165 | result_item.licenses = license_detected
166 |
167 | if len(license_expression_list) > 0:
168 | license_expression_list = list(
169 | set(license_expression_list))
170 | result_item.comment = ','.join(license_expression_list)
171 |
172 | if is_exclude_file(file_path, prev_dir, prev_dir_value):
173 | result_item.exclude = True
174 | scancode_file_item.append(result_item)
175 | except Exception as ex:
176 | msg.append(f"Error Parsing item: {ex}")
177 | rc = False
178 | msg = list(set(msg))
179 | return rc, scancode_file_item, msg, license_list
180 |
181 |
182 | def split_spdx_expression(spdx_string: str) -> list:
183 | license = []
184 | for replace in SPDX_REPLACE_WORDS:
185 | spdx_string = spdx_string.replace(replace, "")
186 | license = re.split(KEY_AND + "|" + KEY_OR, spdx_string)
187 | return license
188 |
189 |
190 | def parsing_scancode_32_later(
191 | scancode_file_list: list, has_error: bool = False
192 | ) -> Tuple[bool, list, list, dict]:
193 | rc = True
194 | msg = []
195 | scancode_file_item = []
196 | license_list = {} # Key :[license]+[matched_text], value: MatchedLicense()
197 |
198 | if scancode_file_list:
199 | for file in scancode_file_list:
200 | try:
201 | file_path = file.get("path", "")
202 | is_binary = file.get("is_binary", False)
203 | is_dir = file.get("type", "") == "directory"
204 | if (not file_path) or is_binary or is_dir:
205 | continue
206 |
207 | result_item = SourceItem(file_path)
208 |
209 | if has_error:
210 | error_msg = file.get("scan_errors", [])
211 | if error_msg:
212 | result_item.comment = ",".join(error_msg)
213 | scancode_file_item.append(result_item)
214 | continue
215 |
216 | copyright_value_list = []
217 | for x in file.get("copyrights", []):
218 | copyright_data = x.get("copyright", "")
219 | if copyright_data:
220 | try:
221 | copyright_data = re.sub(KEYWORD_SPDX_ID, '', copyright_data, flags=re.I)
222 | copyright_data = re.sub(KEYWORD_DOWNLOAD_LOC, '', copyright_data, flags=re.I).strip()
223 | except Exception:
224 | pass
225 | copyright_value_list.append(copyright_data)
226 | result_item.copyright = copyright_value_list
227 |
228 | license_detected = []
229 | licenses = file.get("license_detections", [])
230 | if not licenses:
231 | continue
232 | for lic in licenses:
233 | matched_lic_list = lic.get("matches", [])
234 | for matched_lic in matched_lic_list:
235 | found_lic_list = matched_lic.get("license_expression", "")
236 | matched_txt = matched_lic.get("matched_text", "")
237 | if found_lic_list:
238 | found_lic_list = found_lic_list.lower()
239 | for found_lic in split_spdx_expression(found_lic_list):
240 | if found_lic:
241 | found_lic = found_lic.strip()
242 | if found_lic in REMOVE_LICENSE:
243 | continue
244 | elif found_lic == KEYWORD_SCANCODE_UNKNOWN:
245 | try:
246 | matched = regex.search(matched_txt.lower())
247 | if matched:
248 | found_lic = str(matched.group())
249 | except Exception:
250 | pass
251 | for word in replace_word:
252 | found_lic = found_lic.replace(word, "")
253 | if matched_txt:
254 | lic_matched_key = found_lic + matched_txt
255 | if lic_matched_key in license_list:
256 | license_list[lic_matched_key].set_files(file_path)
257 | else:
258 | lic_info = MatchedLicense(found_lic, "", matched_txt, file_path)
259 | license_list[lic_matched_key] = lic_info
260 | license_detected.append(found_lic)
261 | result_item.licenses = license_detected
262 | if len(license_detected) > 1:
263 | license_expression_spdx = file.get("detected_license_expression_spdx", "")
264 | license_expression = file.get("detected_license_expression", "")
265 | if license_expression_spdx:
266 | license_expression = license_expression_spdx
267 | if license_expression:
268 | result_item.comment = license_expression
269 |
270 | result_item.exclude = is_exclude_file(file_path)
271 | result_item.is_license_text = file.get("percentage_of_license_text", 0) > 90 or is_notice_file(file_path)
272 | scancode_file_item.append(result_item)
273 | except Exception as ex:
274 | msg.append(f"Error Parsing item: {ex}")
275 | rc = False
276 |
277 | return rc, scancode_file_item, msg, license_list
278 |
279 |
280 | def parsing_file_item(
281 | scancode_file_list: list, has_error: bool, need_matched_license: bool = False
282 | ) -> Tuple[bool, list, list, dict]:
283 |
284 | rc = True
285 | msg = []
286 |
287 | first_item = next(iter(scancode_file_list or []), {})
288 | if "licenses" in first_item:
289 | rc, scancode_file_item, msg, license_list = parsing_scancode_32_earlier(scancode_file_list, has_error)
290 | else:
291 | rc, scancode_file_item, msg, license_list = parsing_scancode_32_later(scancode_file_list, has_error)
292 | if not need_matched_license:
293 | license_list = {}
294 | return rc, scancode_file_item, msg, license_list
295 |
--------------------------------------------------------------------------------
/src/fosslight_source/_parsing_scanoss_file.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 | import logging
8 | import fosslight_util.constant as constant
9 | from ._scan_item import SourceItem
10 | from ._scan_item import is_exclude_file
11 | from ._scan_item import replace_word
12 | from typing import Tuple
13 |
14 | logger = logging.getLogger(constant.LOGGER_NAME)
15 | SCANOSS_INFO_HEADER = ['No', 'Source Path', 'Component Declared', 'SPDX Tag',
16 | 'File Header', 'License File', 'Scancode',
17 | 'Matched Rate (line number)', 'scanoss_fileURL']
18 |
19 |
20 | def parsing_extraInfo(scanned_result: dict) -> list:
21 | scanoss_extra_info = []
22 | for scan_item in scanned_result:
23 | license_w_source = scan_item.scanoss_reference
24 | if scan_item.matched_lines:
25 | if license_w_source:
26 | extra_item = [scan_item.source_name_or_path, ','.join(license_w_source['component_declared']),
27 | ','.join(license_w_source['file_spdx_tag']),
28 | ','.join(license_w_source['file_header']),
29 | ','.join(license_w_source['license_file']),
30 | ','.join(license_w_source['scancode']),
31 | scan_item.matched_lines, scan_item.fileURL]
32 | else:
33 | extra_item = [scan_item.source_name_or_path, '', '', '', '', '', scan_item.matched_lines, scan_item.fileURL]
34 | scanoss_extra_info.append(extra_item)
35 | scanoss_extra_info.insert(0, SCANOSS_INFO_HEADER)
36 | return scanoss_extra_info
37 |
38 |
39 | def parsing_scanResult(scanoss_report: dict, path_to_scan: str = "", path_to_exclude: list = []) -> Tuple[bool, list]:
40 | scanoss_file_item = []
41 | abs_path_to_exclude = [os.path.abspath(os.path.join(path_to_scan, path)) for path in path_to_exclude]
42 |
43 | for file_path, findings in scanoss_report.items():
44 | abs_file_path = os.path.abspath(os.path.join(path_to_scan, file_path))
45 | if any(os.path.commonpath([abs_file_path, exclude_path]) == exclude_path for exclude_path in abs_path_to_exclude):
46 | continue
47 | result_item = SourceItem(file_path)
48 |
49 | if 'id' in findings[0]:
50 | if "none" == findings[0]['id']:
51 | continue
52 |
53 | if 'component' in findings[0]:
54 | result_item.oss_name = findings[0]['component']
55 | if 'version' in findings[0]:
56 | result_item.oss_version = findings[0]['version']
57 | if 'url' in findings[0]:
58 | result_item.download_location = list([findings[0]['url']])
59 |
60 | license_detected = []
61 | license_w_source = {"component_declared": [], "file_spdx_tag": [],
62 | "file_header": [], "license_file": [], "scancode": []}
63 | copyright_detected = []
64 | if 'licenses' in findings[0]:
65 | for license in findings[0]['licenses']:
66 |
67 | license_lower = license['name'].lower()
68 | if license_lower.endswith('.'):
69 | license_lower = license_lower[:-1]
70 | for word in replace_word:
71 | if word in license_lower:
72 | license_lower = license_lower.replace(word, "")
73 | license_detected.append(license_lower)
74 |
75 | if license['source'] not in license_w_source:
76 | license_w_source[license['source']] = []
77 | license_w_source[license['source']].append(license['name'])
78 | if len(license_detected) > 0:
79 | result_item.licenses = license_detected
80 | result_item.scanoss_reference = license_w_source
81 | if 'copyrights' in findings[0]:
82 | for copyright in findings[0]['copyrights']:
83 | copyright_detected.append(copyright['name'])
84 | if len(copyright_detected) > 0:
85 | result_item.copyright = copyright_detected
86 |
87 | if is_exclude_file(file_path):
88 | result_item.exclude = True
89 |
90 | if 'file_url' in findings[0]:
91 | result_item.fileURL = findings[0]['file_url']
92 | if 'matched' in findings[0]:
93 | if 'lines' in findings[0]:
94 | result_item.matched_lines = f"{findings[0]['matched']} ({findings[0]['lines']})"
95 | else:
96 | result_item.matched_lines = f"{findings[0]['matched']}"
97 | elif 'lines' in findings[0]:
98 | result_item.matched_lines = f"({findings[0]['lines']})"
99 |
100 | scanoss_file_item.append(result_item)
101 |
102 | return scanoss_file_item
103 |
--------------------------------------------------------------------------------
/src/fosslight_source/_scan_item.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 | import logging
8 | import re
9 | import fosslight_util.constant as constant
10 | from fosslight_util.oss_item import FileItem, OssItem, get_checksum_sha1
11 |
12 | logger = logging.getLogger(constant.LOGGER_NAME)
13 | replace_word = ["-only", "-old-style", "-or-later", "licenseref-scancode-", "licenseref-"]
14 | _notice_filename = ['licen[cs]e[s]?', 'notice[s]?', 'legal', 'copyright[s]?', 'copying*', 'patent[s]?', 'unlicen[cs]e', 'eula',
15 | '[a,l]?gpl[-]?[1-3]?[.,-,_]?[0-1]?', 'mit', 'bsd[-]?[0-4]?', 'bsd[-]?[0-4][-]?clause[s]?',
16 | 'apache[-,_]?[1-2]?[.,-,_]?[0-2]?']
17 | _exclude_filename = ["changelog", "config.guess", "config.sub", "changes", "ltmain.sh",
18 | "configure", "configure.ac", "depcomp", "compile", "missing", "makefile"]
19 | _exclude_extension = [".m4", ".in", ".po"]
20 | _exclude_directory = ["test", "tests", "doc", "docs"]
21 | _exclude_directory = [os.path.sep + dir_name +
22 | os.path.sep for dir_name in _exclude_directory]
23 | _exclude_directory.append("/.")
24 | MAX_LICENSE_LENGTH = 200
25 | MAX_LICENSE_TOTAL_LENGTH = 600
26 | SUBSTRING_LICENSE_COMMENT = "Maximum character limit (License)"
27 |
28 |
29 | class SourceItem(FileItem):
30 |
31 | def __init__(self, value: str) -> None:
32 | super().__init__("")
33 | self.source_name_or_path = value
34 | self.is_license_text = False
35 | self.license_reference = ""
36 | self.scanoss_reference = {}
37 | self.matched_lines = "" # Only for SCANOSS results
38 | self.fileURL = "" # Only for SCANOSS results
39 | self.download_location = []
40 | self.copyright = []
41 | self._licenses = []
42 | self.oss_name = ""
43 | self.oss_version = ""
44 |
45 | self.checksum = get_checksum_sha1(value)
46 |
47 | def __del__(self) -> None:
48 | pass
49 |
50 | def __hash__(self) -> int:
51 | return hash(self.file)
52 |
53 | @property
54 | def licenses(self) -> list:
55 | return self._licenses
56 |
57 | @licenses.setter
58 | def licenses(self, value: list) -> None:
59 | if value:
60 | max_length_exceed = False
61 | for new_lic in value:
62 | if new_lic:
63 | if len(new_lic) > MAX_LICENSE_LENGTH:
64 | new_lic = new_lic[:MAX_LICENSE_LENGTH]
65 | max_length_exceed = True
66 | if new_lic not in self._licenses:
67 | self._licenses.append(new_lic)
68 | if len(",".join(self._licenses)) > MAX_LICENSE_TOTAL_LENGTH:
69 | self._licenses.remove(new_lic)
70 | max_length_exceed = True
71 | break
72 | if max_length_exceed and (SUBSTRING_LICENSE_COMMENT not in self.comment):
73 | self.comment = f"{self.comment}/ {SUBSTRING_LICENSE_COMMENT}" if self.comment else SUBSTRING_LICENSE_COMMENT
74 |
75 | def set_oss_item(self) -> None:
76 | self.oss_items = []
77 | if self.download_location:
78 | for url in self.download_location:
79 | item = OssItem(self.oss_name, self.oss_version, self.licenses, url)
80 | item.copyright = "\n".join(self.copyright)
81 | item.comment = self.comment
82 | self.oss_items.append(item)
83 | else:
84 | item = OssItem(self.oss_name, self.oss_version, self.licenses)
85 | item.copyright = "\n".join(self.copyright)
86 | item.comment = self.comment
87 | self.oss_items.append(item)
88 |
89 | def get_print_array(self) -> list:
90 | print_rows = []
91 | for item in self.oss_items:
92 | print_rows.append([self.source_name_or_path, item.name, item.version, ",".join(item.license),
93 | item.download_location, "",
94 | item.copyright, "Exclude" if self.exclude else "", item.comment,
95 | self.license_reference])
96 | return print_rows
97 |
98 | def __eq__(self, other: object) -> bool:
99 | if type(other) == str:
100 | return self.source_name_or_path == other
101 | else:
102 | return self.source_name_or_path == other.source_name_or_path
103 |
104 |
105 | def is_exclude_dir(dir_path: str) -> bool:
106 | if dir_path != "":
107 | dir_path = dir_path.lower()
108 | dir_path = dir_path if dir_path.endswith(
109 | os.path.sep) else dir_path + os.path.sep
110 | dir_path = dir_path if dir_path.startswith(
111 | os.path.sep) else os.path.sep + dir_path
112 | return any(dir_name in dir_path for dir_name in _exclude_directory)
113 | return False
114 |
115 |
116 | def is_exclude_file(file_path: str, prev_dir: str = None, prev_dir_exclude_value: bool = None) -> bool:
117 | file_path = file_path.lower()
118 | filename = os.path.basename(file_path)
119 | if os.path.splitext(filename)[1] in _exclude_extension:
120 | return True
121 | if filename.startswith('.') or filename in _exclude_filename:
122 | return True
123 |
124 | dir_path = os.path.dirname(file_path)
125 | if prev_dir is not None: # running ScanCode
126 | if dir_path == prev_dir:
127 | return prev_dir_exclude_value
128 | else:
129 | # There will be no execution of this else statement.
130 | # Because scancode json output results are sorted by path,
131 | # most of them will match the previous if statement.
132 | return is_exclude_dir(dir_path)
133 | else: # running SCANOSS
134 | return is_exclude_dir(dir_path)
135 | return False
136 |
137 |
138 | def is_notice_file(file_path: str) -> bool:
139 | pattern = r"({})(? None:
46 | global logger
47 | _result_log = {}
48 |
49 | path_to_scan = os.getcwd()
50 | path_to_exclude = []
51 | write_json_file = False
52 | output_file_name = ""
53 | print_matched_text = False
54 | formats = []
55 | selected_scanner = ""
56 | correct_mode = True
57 |
58 | time_out = 120
59 | core = -1
60 |
61 | parser = argparse.ArgumentParser(description='FOSSLight Source', prog='fosslight_source', add_help=False)
62 | parser.add_argument('-h', '--help', action='store_true', required=False)
63 | parser.add_argument('-v', '--version', action='store_true', required=False)
64 | parser.add_argument('-p', '--path', nargs=1, type=str, required=False)
65 | parser.add_argument('-j', '--json', action='store_true', required=False)
66 | parser.add_argument('-o', '--output', nargs=1, type=str, required=False, default="")
67 | parser.add_argument('-m', '--matched', action='store_true', required=False)
68 | parser.add_argument('-f', '--formats', nargs='*', type=str, required=False)
69 | parser.add_argument('-s', '--scanner', nargs=1, type=str, required=False, default='all')
70 | parser.add_argument('-t', '--timeout', type=int, required=False, default=120)
71 | parser.add_argument('-c', '--cores', type=int, required=False, default=-1)
72 | parser.add_argument('-e', '--exclude', nargs='*', required=False, default=[])
73 | parser.add_argument('--no_correction', action='store_true', required=False)
74 | parser.add_argument('--correct_fpath', nargs=1, type=str, required=False)
75 |
76 | args = parser.parse_args()
77 |
78 | if args.help:
79 | print_help_msg_source_scanner()
80 | if args.version:
81 | print_version(PKG_NAME)
82 | if not args.path:
83 | path_to_scan = os.getcwd()
84 | else:
85 | path_to_scan = ''.join(args.path)
86 | if args.exclude:
87 | path_to_exclude = args.exclude
88 | if args.json:
89 | write_json_file = True
90 | output_file_name = ''.join(args.output)
91 | if args.matched:
92 | print_matched_text = True
93 | if args.formats:
94 | formats = list(args.formats)
95 | if args.scanner:
96 | selected_scanner = ''.join(args.scanner)
97 | if args.no_correction:
98 | correct_mode = False
99 | correct_filepath = path_to_scan
100 | if args.correct_fpath:
101 | correct_filepath = ''.join(args.correct_fpath)
102 |
103 | time_out = args.timeout
104 | core = args.cores
105 |
106 | timer = TimerThread()
107 | timer.setDaemon(True)
108 | timer.start()
109 |
110 | if os.path.isdir(path_to_scan):
111 | result = []
112 | result = run_scanners(path_to_scan, output_file_name, write_json_file, core, True,
113 | print_matched_text, formats, time_out, correct_mode, correct_filepath,
114 | selected_scanner, path_to_exclude)
115 |
116 | _result_log["Scan Result"] = result[1]
117 |
118 | try:
119 | logger.info(yaml.safe_dump(_result_log, allow_unicode=True, sort_keys=True))
120 | except Exception as ex:
121 | logger.debug(f"Failed to print log.: {ex}")
122 | else:
123 | logger.error(f"(-p option) Input path({path_to_scan}) is not a directory. Please enter a valid path.")
124 | sys.exit(1)
125 |
126 |
127 | def count_files(path_to_scan: str, path_to_exclude: list) -> Tuple[int, int]:
128 | total_files = 0
129 | excluded_files = 0
130 | abs_path_to_exclude = [os.path.abspath(os.path.join(path_to_scan, path)) for path in path_to_exclude]
131 |
132 | for root, _, files in os.walk(path_to_scan):
133 | for file in files:
134 | file_path = os.path.join(root, file)
135 | abs_file_path = os.path.abspath(file_path)
136 | if any(os.path.commonpath([abs_file_path, exclude_path]) == exclude_path
137 | for exclude_path in abs_path_to_exclude):
138 | excluded_files += 1
139 | total_files += 1
140 |
141 | return total_files, excluded_files
142 |
143 |
144 | def create_report_file(
145 | _start_time: str, merged_result: list,
146 | license_list: list, scanoss_result: list,
147 | selected_scanner: str, need_license: bool = False,
148 | output_path: str = "", output_files: list = [],
149 | output_extensions: list = [], correct_mode: bool = True,
150 | correct_filepath: str = "", path_to_scan: str = "", path_to_exclude: list = [],
151 | formats: list = [], excluded_file_list: list = [], api_limit_exceed: bool = False
152 | ) -> 'ScannerItem':
153 | """
154 | Create report files for given scanned result.
155 |
156 | :param start_time: start time of scanning.
157 | :param scanned_result: scanned result.
158 | :param license_list: matched text (only for scancode).
159 | :param need_license: if requested, output matched text (only for scancode).
160 | """
161 | extended_header = {}
162 | sheet_list = {}
163 | _json_ext = ".json"
164 |
165 | if output_path == "":
166 | output_path = os.getcwd()
167 | else:
168 | output_path = os.path.abspath(output_path)
169 |
170 | if not output_files:
171 | # If -o does not contains file name, set default name
172 | while len(output_files) < len(output_extensions):
173 | output_files.append(None)
174 | to_remove = [] # elements of spdx format on windows that should be removed
175 | for i, output_extension in enumerate(output_extensions):
176 | if output_files[i] is None or output_files[i] == "":
177 | if formats:
178 | if formats[i].startswith('spdx') or formats[i].startswith('cyclonedx'):
179 | if platform.system() == 'Windows':
180 | logger.warning(f'{formats[i]} is not supported on Windows.Please remove {formats[i]} from format.')
181 | to_remove.append(i)
182 | else:
183 | if formats[i].startswith('spdx'):
184 | output_files[i] = f"fosslight_spdx_src_{_start_time}"
185 | elif formats[i].startswith('cyclonedx'):
186 | output_files[i] = f'fosslight_cyclonedx_src_{_start_time}'
187 | else:
188 | if output_extension == _json_ext:
189 | output_files[i] = f"fosslight_opossum_src_{_start_time}"
190 | else:
191 | output_files[i] = f"fosslight_report_src_{_start_time}"
192 | else:
193 | if output_extension == _json_ext:
194 | output_files[i] = f"fosslight_opossum_src_{_start_time}"
195 | else:
196 | output_files[i] = f"fosslight_report_src_{_start_time}"
197 | for index in sorted(to_remove, reverse=True):
198 | # remove elements of spdx format on windows
199 | del output_files[index]
200 | del output_extensions[index]
201 | del formats[index]
202 | if len(output_extensions) < 1:
203 | sys.exit(0)
204 |
205 | if not correct_filepath:
206 | correct_filepath = path_to_scan
207 |
208 | scan_item = ScannerItem(PKG_NAME, _start_time)
209 | scan_item.set_cover_pathinfo(path_to_scan, path_to_exclude)
210 | files_count, removed_files_count = count_files(path_to_scan, path_to_exclude)
211 |
212 | scan_item.set_cover_comment(f"Total number of files : {files_count}")
213 | scan_item.set_cover_comment(f"Removed files : {removed_files_count}")
214 |
215 | if api_limit_exceed:
216 | scan_item.set_cover_comment("(Some of) SCANOSS scan was skipped. (API limits being exceeded)")
217 |
218 | if not merged_result:
219 | if files_count < 1:
220 | scan_item.set_cover_comment("(No file detected.)")
221 | else:
222 | scan_item.set_cover_comment("(No OSS detected.)")
223 |
224 | if merged_result:
225 | sheet_list = {}
226 | # Remove results that are in excluding file list
227 | for i in range(len(merged_result) - 1, -1, -1): # Iterate from last to first
228 | item_path = merged_result[i].source_name_or_path # Assuming SourceItem has 'file_path' attribute
229 | if item_path in excluded_file_list:
230 | del merged_result[i] # Delete matching item
231 |
232 | scan_item.append_file_items(merged_result, PKG_NAME)
233 |
234 | if selected_scanner == 'scanoss':
235 | extended_header = SCANOSS_HEADER
236 | else:
237 | extended_header = MERGED_HEADER
238 |
239 | if need_license:
240 | if selected_scanner == 'scancode':
241 | sheet_list["scancode_reference"] = get_license_list_to_print(license_list)
242 | elif selected_scanner == 'scanoss':
243 | sheet_list["scanoss_reference"] = get_scanoss_extra_info(scanoss_result)
244 | else:
245 | sheet_list["scancode_reference"] = get_license_list_to_print(license_list)
246 | sheet_list["scanoss_reference"] = get_scanoss_extra_info(scanoss_result)
247 | if sheet_list:
248 | scan_item.external_sheets = sheet_list
249 |
250 | if correct_mode:
251 | success, msg_correct, correct_item = correct_with_yaml(correct_filepath, path_to_scan, scan_item)
252 | if not success:
253 | logger.info(f"No correction with yaml: {msg_correct}")
254 | else:
255 | scan_item = correct_item
256 | logger.info("Success to correct with yaml.")
257 |
258 | combined_paths_and_files = [os.path.join(output_path, file) for file in output_files]
259 | results = []
260 | for combined_path_and_file, output_extension, output_format in zip(combined_paths_and_files, output_extensions, formats):
261 | # if need_license and output_extension == _json_ext and "scanoss_reference" in sheet_list:
262 | # del sheet_list["scanoss_reference"]
263 | results.append(write_output_file(combined_path_and_file, output_extension, scan_item, extended_header, "", output_format))
264 | for success, msg, result_file in results:
265 | if success:
266 | logger.info(f"Output file: {result_file}")
267 | for row in scan_item.get_cover_comment():
268 | logger.info(row)
269 | else:
270 | logger.error(f"Fail to generate result file {result_file}. msg:({msg})")
271 | return scan_item
272 |
273 |
274 | def merge_results(scancode_result: list = [], scanoss_result: list = [], spdx_downloads: dict = {}) -> list:
275 |
276 | """
277 | Merge scanner results and spdx parsing result.
278 | :param scancode_result: list of scancode results in SourceItem.
279 | :param scanoss_result: list of scanoss results in SourceItem.
280 | :param spdx_downloads: dictionary of spdx parsed results.
281 | :return merged_result: list of merged result in SourceItem.
282 | """
283 |
284 | # If anything that is found at SCANOSS only exist, add it to result.
285 | scancode_result.extend([item for item in scanoss_result if item not in scancode_result])
286 |
287 | # If download loc. in SPDX form found, overwrite the scanner result.
288 | # If scanner result doesn't exist, create a new row.
289 | if spdx_downloads:
290 | for file_name, download_location in spdx_downloads.items():
291 | if file_name in scancode_result:
292 | merged_result_item = scancode_result[scancode_result.index(file_name)]
293 | merged_result_item.download_location = download_location
294 | else:
295 | new_result_item = SourceItem(file_name)
296 | new_result_item.download_location = download_location
297 | scancode_result.append(new_result_item)
298 |
299 | for item in scancode_result:
300 | item.set_oss_item()
301 |
302 | return scancode_result
303 |
304 |
305 | def run_scanners(
306 | path_to_scan: str, output_file_name: str = "",
307 | write_json_file: bool = False, num_cores: int = -1,
308 | called_by_cli: bool = True, print_matched_text: bool = False,
309 | formats: list = [], time_out: int = 120,
310 | correct_mode: bool = True, correct_filepath: str = "",
311 | selected_scanner: str = 'all', path_to_exclude: list = []
312 | ) -> Tuple[bool, str, 'ScannerItem', list, list]:
313 | """
314 | Run Scancode and scanoss.py for the given path.
315 |
316 | :param path_to_scan: path of sourcecode to scan.
317 | :param output_file_name: path or file name (with path) for the output.
318 | :param write_json_file: if requested, keep the raw files.
319 | :param num_cores: number of cores used for scancode scanning.
320 | :param called_by_cli: if not called by cli, initialize logger.
321 | :param print_matched_text: if requested, output matched text (only for scancode).
322 | :param format: output format (excel, csv, opossum).
323 | :return success: success or failure of scancode.
324 | :return result_log["Scan Result"]:
325 | :return merged_result: merged scan result of scancode and scanoss.
326 | :return license_list: matched text.(only for scancode)
327 | """
328 | global logger
329 |
330 | start_time = datetime.now().strftime('%y%m%d_%H%M')
331 | scancode_result = []
332 | scanoss_result = []
333 | merged_result = []
334 | license_list = []
335 | spdx_downloads = {}
336 | result_log = {}
337 | scan_item = []
338 | api_limit_exceed = False
339 |
340 | success, msg, output_path, output_files, output_extensions, formats = check_output_formats_v2(output_file_name, formats)
341 |
342 | logger, result_log = init_log(os.path.join(output_path, f"fosslight_log_src_{start_time}.txt"),
343 | True, logging.INFO, logging.DEBUG, PKG_NAME, path_to_scan, path_to_exclude)
344 | excluded_file_list = excluding_files(path_to_exclude, path_to_scan)
345 |
346 | if '.xlsx' not in output_extensions and print_matched_text:
347 | logger.warning("-m option is only available for excel.")
348 | print_matched_text = False
349 |
350 | if success:
351 | if selected_scanner == 'scancode' or selected_scanner == 'all' or selected_scanner == '':
352 | success, result_log[RESULT_KEY], scancode_result, license_list = run_scan(path_to_scan, output_file_name,
353 | write_json_file, num_cores, True,
354 | print_matched_text, formats, called_by_cli,
355 | time_out, correct_mode, correct_filepath)
356 | if selected_scanner == 'scanoss' or selected_scanner == 'all' or selected_scanner == '':
357 | scanoss_result, api_limit_exceed = run_scanoss_py(path_to_scan, output_file_name, formats, True, write_json_file,
358 | num_cores, path_to_exclude)
359 | if selected_scanner in SCANNER_TYPE:
360 | spdx_downloads = get_spdx_downloads(path_to_scan, path_to_exclude)
361 | merged_result = merge_results(scancode_result, scanoss_result, spdx_downloads)
362 | scan_item = create_report_file(start_time, merged_result, license_list, scanoss_result, selected_scanner,
363 | print_matched_text, output_path, output_files, output_extensions, correct_mode,
364 | correct_filepath, path_to_scan, path_to_exclude, formats, excluded_file_list,
365 | api_limit_exceed)
366 | else:
367 | print_help_msg_source_scanner()
368 | result_log[RESULT_KEY] = "Unsupported scanner"
369 | success = False
370 | else:
371 | result_log[RESULT_KEY] = f"Format error. {msg}"
372 | success = False
373 | return success, result_log.get(RESULT_KEY, ""), scan_item, license_list, scanoss_result
374 |
375 |
376 | if __name__ == '__main__':
377 | main()
378 |
--------------------------------------------------------------------------------
/src/fosslight_source/run_scancode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 | import multiprocessing
8 | import warnings
9 | import logging
10 | import yaml
11 | from scancode import cli
12 | from datetime import datetime
13 | import fosslight_util.constant as constant
14 | from fosslight_util.set_log import init_log
15 | from ._parsing_scancode_file_item import parsing_file_item
16 | from ._parsing_scancode_file_item import get_error_from_header
17 | from fosslight_util.output_format import check_output_formats_v2
18 | from fosslight_binary.binary_analysis import check_binary
19 | from typing import Tuple
20 |
21 | logger = logging.getLogger(constant.LOGGER_NAME)
22 | warnings.filterwarnings("ignore", category=FutureWarning)
23 | _PKG_NAME = "fosslight_source"
24 |
25 |
26 | def run_scan(
27 | path_to_scan: str, output_file_name: str = "",
28 | _write_json_file: bool = False, num_cores: int = -1,
29 | return_results: bool = False, need_license: bool = False,
30 | formats: list = [], called_by_cli: bool = False,
31 | time_out: int = 120, correct_mode: bool = True,
32 | correct_filepath: str = "", path_to_exclude: list = []
33 | ) -> Tuple[bool, str, list, list]:
34 | if not called_by_cli:
35 | global logger
36 |
37 | success = True
38 | msg = ""
39 | _str_final_result_log = ""
40 | _result_log = {}
41 | result_list = []
42 | license_list = []
43 | _json_ext = ".json"
44 | _start_time = datetime.now().strftime('%y%m%d_%H%M')
45 |
46 | if not correct_filepath:
47 | correct_filepath = path_to_scan
48 |
49 | success, msg, output_path, output_files, output_extensions, formats = check_output_formats_v2(output_file_name, formats)
50 | if success:
51 | if output_path == "": # if json output with _write_json_file not used, output_path won't be needed.
52 | output_path = os.getcwd()
53 | else:
54 | output_path = os.path.abspath(output_path)
55 | if not called_by_cli:
56 | while len(output_files) < len(output_extensions):
57 | output_files.append(None)
58 | for i, output_extension in enumerate(output_extensions):
59 | if output_files[i] is None or output_files[i] == "":
60 | if output_extension == _json_ext:
61 | output_files[i] = f"fosslight_opossum_src_{_start_time}"
62 | else:
63 | output_files[i] = f"fosslight_report_src_{_start_time}"
64 |
65 | if _write_json_file:
66 | output_json_file = os.path.join(output_path, "scancode_raw_result.json")
67 | else:
68 | output_json_file = ""
69 |
70 | if not called_by_cli:
71 | logger, _result_log = init_log(os.path.join(output_path, f"fosslight_log_src_{_start_time}.txt"),
72 | True, logging.INFO, logging.DEBUG, _PKG_NAME, path_to_scan, path_to_exclude)
73 | num_cores = multiprocessing.cpu_count() - 1 if num_cores < 0 else num_cores
74 |
75 | if os.path.isdir(path_to_scan):
76 | try:
77 | time_out = float(time_out)
78 | pretty_params = {}
79 | pretty_params["path_to_scan"] = path_to_scan
80 | pretty_params["path_to_exclude"] = path_to_exclude
81 | pretty_params["output_file"] = output_file_name
82 | total_files_to_excluded = []
83 |
84 | if path_to_exclude:
85 | target_path = os.path.basename(path_to_scan) if os.path.isabs(path_to_scan) else path_to_scan
86 |
87 | for path in path_to_exclude:
88 | exclude_path = path
89 | isabs_exclude = os.path.isabs(path)
90 | if isabs_exclude:
91 | exclude_path = os.path.relpath(path, os.path.abspath(path_to_scan))
92 |
93 | exclude_path = os.path.join(target_path, exclude_path)
94 | if os.path.isdir(exclude_path):
95 | for root, _, files in os.walk(exclude_path):
96 | total_files_to_excluded.extend([os.path.normpath(os.path.join(root, file)).replace("\\", "/")
97 | for file in files])
98 | elif os.path.isfile(exclude_path):
99 | total_files_to_excluded.append(os.path.normpath(exclude_path).replace("\\", "/"))
100 |
101 | rc, results = cli.run_scan(path_to_scan, max_depth=100,
102 | strip_root=True, license=True,
103 | copyright=True, return_results=True,
104 | processes=num_cores, pretty_params=pretty_params,
105 | output_json_pp=output_json_file, only_findings=True,
106 | license_text=True, url=True, timeout=time_out,
107 | include=(), ignore=tuple(total_files_to_excluded))
108 | if not rc:
109 | msg = "Source code analysis failed."
110 | success = False
111 | if results:
112 | has_error = False
113 | if "headers" in results:
114 | has_error, error_msg = get_error_from_header(results["headers"])
115 | if has_error:
116 | _result_log["Error_files"] = error_msg
117 | msg = "Failed to analyze :" + error_msg
118 | if "files" in results:
119 | rc, result_list, parsing_msg, license_list = parsing_file_item(results["files"],
120 | has_error, need_license)
121 | if parsing_msg:
122 | _result_log["Parsing Log"] = parsing_msg
123 | if rc:
124 | if not success:
125 | success = True
126 | result_list = sorted(
127 | result_list, key=lambda row: (''.join(row.licenses)))
128 |
129 | for scan_item in result_list:
130 | if check_binary(os.path.join(path_to_scan, scan_item.source_name_or_path)):
131 | scan_item.exclude = True
132 | except Exception as ex:
133 | success = False
134 | msg = str(ex)
135 | logger.error(f"Analyze {path_to_scan}: {msg}")
136 | else:
137 | success = False
138 | msg = f"(-p option) Check the path to scan: {path_to_scan}"
139 |
140 | if not return_results:
141 | result_list = []
142 |
143 | scan_result_msg = str(success) if msg == "" else f"{success}, {msg}"
144 | _result_log["Scan Result"] = scan_result_msg
145 | _result_log["Output Directory"] = output_path
146 | try:
147 | _str_final_result_log = yaml.safe_dump(_result_log, allow_unicode=True, sort_keys=True)
148 | logger.info(_str_final_result_log)
149 | except Exception as ex:
150 | logger.warning(f"Failed to print result log. {ex}")
151 |
152 | if not success:
153 | logger.error(f"Failed to run: {scan_result_msg}")
154 | return success, _result_log["Scan Result"], result_list, license_list
155 |
--------------------------------------------------------------------------------
/src/fosslight_source/run_scanoss.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 | import importlib_metadata
8 | import warnings
9 | import logging
10 | import json
11 | from datetime import datetime
12 | import fosslight_util.constant as constant
13 | from fosslight_util.set_log import init_log
14 | from fosslight_util.output_format import check_output_formats_v2 # , write_output_file
15 | from ._parsing_scanoss_file import parsing_scanResult # scanoss
16 | from ._parsing_scanoss_file import parsing_extraInfo # scanoss
17 | import shutil
18 | from pathlib import Path
19 | from scanoss.scanner import Scanner, ScanType
20 | import io
21 | import contextlib
22 |
23 | logger = logging.getLogger(constant.LOGGER_NAME)
24 | warnings.filterwarnings("ignore", category=FutureWarning)
25 | _PKG_NAME = "fosslight_source"
26 | SCANOSS_RESULT_FILE = "scanner_output.wfp"
27 | SCANOSS_OUTPUT_FILE = "scanoss_raw_result.json"
28 |
29 |
30 | def get_scanoss_extra_info(scanned_result: dict) -> list:
31 | return parsing_extraInfo(scanned_result)
32 |
33 |
34 | def run_scanoss_py(path_to_scan: str, output_file_name: str = "", format: list = [], called_by_cli: bool = False,
35 | write_json_file: bool = False, num_threads: int = -1, path_to_exclude: list = []) -> list:
36 | """
37 | Run scanoss.py for the given path.
38 |
39 | :param path_to_scan: path of sourcecode to scan.
40 | :param output_file_name: file name for the output.
41 | :param format: Output file format (not being used except when calling check_output_format).
42 | :param called_by_cli: if not called by cli, initialize logger.
43 | :param write_json_file: if requested, keep the raw files.
44 | :return scanoss_file_list: list of ScanItem (scanned result by files).
45 | """
46 | success, msg, output_path, output_files, output_extensions, formats = check_output_formats_v2(output_file_name, format)
47 |
48 | if not called_by_cli:
49 | global logger
50 | _start_time = datetime.now().strftime('%y%m%d_%H%M')
51 | logger, _result_log = init_log(os.path.join(output_path, f"fosslight_log_src_{_start_time}.txt"),
52 | True, logging.INFO, logging.DEBUG, _PKG_NAME, path_to_scan, path_to_exclude)
53 |
54 | scanoss_file_list = []
55 | try:
56 | importlib_metadata.distribution("scanoss")
57 | except Exception as error:
58 | logger.warning(f"{error}. Skipping scan with scanoss.")
59 | logger.warning("Please install scanoss and dataclasses before run fosslight_source with scanoss option.")
60 | return scanoss_file_list
61 |
62 | if output_path == "": # if json output with _write_json_file not used, output_path won't be needed.
63 | output_path = os.getcwd()
64 | else:
65 | output_path = os.path.abspath(output_path)
66 | if not os.path.isdir(output_path):
67 | Path(output_path).mkdir(parents=True, exist_ok=True)
68 | output_json_file = os.path.join(output_path, SCANOSS_OUTPUT_FILE)
69 | if os.path.exists(output_json_file): # remove scanner_output.wfp file if exist
70 | os.remove(output_json_file)
71 |
72 | try:
73 | scanner = Scanner(
74 | ignore_cert_errors=True,
75 | skip_folders=path_to_exclude,
76 | scan_output=output_json_file,
77 | scan_options=ScanType.SCAN_SNIPPETS.value,
78 | nb_threads=num_threads if num_threads > 0 else 10
79 | )
80 |
81 | output_buffer = io.StringIO()
82 | with contextlib.redirect_stdout(output_buffer), contextlib.redirect_stderr(output_buffer):
83 | scanner.scan_folder_with_options(scan_dir=path_to_scan)
84 | captured_output = output_buffer.getvalue()
85 | api_limit_exceed = "due to service limits being exceeded" in captured_output
86 | logger.debug(f"{captured_output}")
87 |
88 | if os.path.isfile(output_json_file):
89 | total_files_to_excluded = []
90 | if path_to_exclude:
91 | for path in path_to_exclude:
92 | path = os.path.join(path_to_scan, os.path.relpath(path, os.path.abspath(path_to_scan))) \
93 | if not os.path.isabs(path_to_scan) and os.path.isabs(path) else os.path.join(path_to_scan, path)
94 | if os.path.isdir(path):
95 | for root, _, files in os.walk(path):
96 | root = root[len(path_to_scan) + 1:]
97 | total_files_to_excluded.extend([os.path.normpath(os.path.join(root, file)).replace('\\', '/')
98 | for file in files])
99 | elif os.path.isfile(path):
100 | path = path[len(path_to_scan) + 1:]
101 | total_files_to_excluded.append(os.path.normpath(path).replace('\\', '/'))
102 |
103 | with open(output_json_file, "r") as st_json:
104 | st_python = json.load(st_json)
105 | for key_to_exclude in total_files_to_excluded:
106 | if key_to_exclude in st_python:
107 | del st_python[key_to_exclude]
108 | with open(output_json_file, 'w') as st_json:
109 | json.dump(st_python, st_json, indent=4)
110 | with open(output_json_file, "r") as st_json:
111 | st_python = json.load(st_json)
112 | scanoss_file_list = parsing_scanResult(st_python, path_to_scan, path_to_exclude)
113 |
114 | except Exception as error:
115 | logger.debug(f"SCANOSS Parsing {path_to_scan}: {error}")
116 |
117 | logger.info(f"|---Number of files detected with SCANOSS: {(len(scanoss_file_list))}")
118 |
119 | try:
120 | if write_json_file:
121 | shutil.move(SCANOSS_RESULT_FILE, output_path)
122 | else:
123 | os.remove(output_json_file)
124 | os.remove(SCANOSS_RESULT_FILE)
125 | except Exception as error:
126 | logger.debug(f"Moving scanoss raw files failed.: {error}")
127 |
128 | return scanoss_file_list, api_limit_exceed
129 |
--------------------------------------------------------------------------------
/src/fosslight_source/run_spdx_extractor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2023 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 | import logging
8 | import re
9 | import fosslight_util.constant as constant
10 | import mmap
11 |
12 | logger = logging.getLogger(constant.LOGGER_NAME)
13 |
14 |
15 | def get_file_list(path_to_scan: str, path_to_exclude: list = []) -> list:
16 | file_list = []
17 | abs_path_to_exclude = [os.path.abspath(os.path.join(path_to_scan, path)) for path in path_to_exclude]
18 | for root, dirs, files in os.walk(path_to_scan):
19 | for file in files:
20 | file_path = os.path.join(root, file)
21 | abs_file_path = os.path.abspath(file_path)
22 | if any(os.path.commonpath([abs_file_path, exclude_path]) == exclude_path
23 | for exclude_path in abs_path_to_exclude):
24 | continue
25 | file_list.append(file_path)
26 | return file_list
27 |
28 |
29 | def get_spdx_downloads(path_to_scan: str, path_to_exclude: list = []) -> dict:
30 | download_dict = {}
31 | find_word = re.compile(rb"SPDX-PackageDownloadLocation\s*:\s*(\S+)", re.IGNORECASE)
32 |
33 | file_list = get_file_list(path_to_scan, path_to_exclude)
34 |
35 | for file in file_list:
36 | try:
37 | rel_path_file = os.path.relpath(file, path_to_scan)
38 | # remove the path_to_scan from the file paths
39 | if os.path.getsize(file) > 0:
40 | with open(file, "r") as f:
41 | with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mmap_obj:
42 | for word in find_word.findall(mmap_obj):
43 | if rel_path_file in download_dict:
44 | download_dict[rel_path_file].append(word.decode('utf-8'))
45 | else:
46 | download_dict[rel_path_file] = [word.decode('utf-8')]
47 | except Exception as ex:
48 | msg = str(ex)
49 | logger.warning(f"Failed to extract SPDX download location. {rel_path_file}, {msg}")
50 | return download_dict
51 |
--------------------------------------------------------------------------------
/tests/cli_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 | from datetime import datetime
8 | import logging
9 | import fosslight_util.constant as constant
10 | from fosslight_util.set_log import init_log
11 | from fosslight_source.run_scancode import run_scan
12 | from fosslight_source.run_scanoss import run_scanoss_py
13 |
14 | logger = logging.getLogger(constant.LOGGER_NAME)
15 |
16 |
17 | def main():
18 | global logger
19 |
20 | path_to_find_bin = os.path.abspath("tests/test_files/test")
21 | _start_time = datetime.now().strftime('%y%m%d_%H%M')
22 |
23 | fosslight_report_name = "test_result_func_call/result"
24 | output_dir = os.path.abspath(fosslight_report_name)
25 |
26 | logger, result_item = init_log(os.path.join(output_dir, "fosslight_log_"+_start_time+".txt"))
27 |
28 | ret = run_scan(path_to_find_bin, fosslight_report_name, True, -1, True, True, [], False)
29 | ret_scanoss, api_limit_exceed = run_scanoss_py(path_to_find_bin, fosslight_report_name, [], False, True, -1)
30 |
31 | logger.warning("[Scan] Result: %s" % (ret[0]))
32 | logger.warning("[Scan] Result_msg: %s" % (ret[1]))
33 |
34 | if len(ret) > 2:
35 | try:
36 | for scan_item in ret[2]:
37 | logger.warning(scan_item.get_print_array())
38 | except Exception as ex:
39 | logger.error("Error:"+str(ex))
40 | if ret_scanoss:
41 | for scan_item in ret_scanoss:
42 | logger.warning(scan_item.get_print_array())
43 |
44 |
45 | if __name__ == '__main__':
46 | main()
47 |
--------------------------------------------------------------------------------
/tests/scancode_raw.json:
--------------------------------------------------------------------------------
1 | {
2 | "headers": [
3 | {
4 | "tool_name": "scancode-toolkit",
5 | "tool_version": "21.3.31",
6 | "options": {},
7 | "notice": "Generated with ScanCode and provided on an \"AS IS\" BASIS, WITHOUT WARRANTIES\nOR CONDITIONS OF ANY KIND, either express or implied. No content created from\nScanCode should be considered or used as legal advice. Consult an Attorney\nfor any legal advice.\nScanCode is a free software code scanning tool from nexB Inc. and others.\nVisit https://github.com/nexB/scancode-toolkit/ for support and download.",
8 | "start_timestamp": "2022-07-28T054744.186055",
9 | "end_timestamp": "2022-07-28T054746.936098",
10 | "duration": 2.750060796737671,
11 | "message": null,
12 | "errors": [],
13 | "extra_data": {
14 | "files_count": 7
15 | }
16 | }
17 | ],
18 | "files": [
19 | {
20 | "path": "LICENSE",
21 | "type": "file",
22 | "licenses": [
23 | {
24 | "key": "apache-2.0",
25 | "score": 100.0,
26 | "name": "Apache License 2.0",
27 | "short_name": "Apache 2.0",
28 | "category": "Permissive",
29 | "is_exception": false,
30 | "owner": "Apache Software Foundation",
31 | "homepage_url": "http://www.apache.org/licenses/",
32 | "text_url": "http://www.apache.org/licenses/LICENSE-2.0",
33 | "reference_url": "https://scancode-licensedb.aboutcode.org/apache-2.0",
34 | "scancode_text_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.LICENSE",
35 | "scancode_data_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.yml",
36 | "spdx_license_key": "Apache-2.0",
37 | "spdx_url": "https://spdx.org/licenses/Apache-2.0",
38 | "start_line": 1,
39 | "end_line": 73,
40 | "matched_rule": {
41 | "identifier": "apache-2.0.LICENSE",
42 | "license_expression": "apache-2.0",
43 | "licenses": [
44 | "apache-2.0"
45 | ],
46 | "is_license_text": true,
47 | "is_license_notice": false,
48 | "is_license_reference": false,
49 | "is_license_tag": false,
50 | "is_license_intro": false,
51 | "matcher": "1-hash",
52 | "rule_length": 1581,
53 | "matched_length": 1581,
54 | "match_coverage": 100.0,
55 | "rule_relevance": 100
56 | },
57 | "matched_text": "Apache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n\"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.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n\"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.\n\n\"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).\n\n\"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.\n\n\"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,\n but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"\n\n\"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.\n\n2. 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.\n\n3. 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.\n\n4. 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:\n\n (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices stating that You changed the files; and\n\n (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\n\n (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.\n\n 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.\n\n5. 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.\n\n6. 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.\n\n7. 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.\n\n8. 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.\n\n9. 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.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\nTo 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.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License."
58 | }
59 | ],
60 | "license_expressions": [
61 | "apache-2.0"
62 | ],
63 | "percentage_of_license_text": 100.0,
64 | "copyrights": [],
65 | "holders": [],
66 | "authors": [],
67 | "scan_errors": []
68 | },
69 | {
70 | "path": "run_scancode.py",
71 | "type": "file",
72 | "licenses": [
73 | {
74 | "key": "apache-2.0",
75 | "score": 100.0,
76 | "name": "Apache License 2.0",
77 | "short_name": "Apache 2.0",
78 | "category": "Permissive",
79 | "is_exception": false,
80 | "owner": "Apache Software Foundation",
81 | "homepage_url": "http://www.apache.org/licenses/",
82 | "text_url": "http://www.apache.org/licenses/LICENSE-2.0",
83 | "reference_url": "https://scancode-licensedb.aboutcode.org/apache-2.0",
84 | "scancode_text_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.LICENSE",
85 | "scancode_data_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.yml",
86 | "spdx_license_key": "Apache-2.0",
87 | "spdx_url": "https://spdx.org/licenses/Apache-2.0",
88 | "start_line": 4,
89 | "end_line": 4,
90 | "matched_rule": {
91 | "identifier": "spdx-license-identifier: apache-2.0",
92 | "license_expression": "apache-2.0",
93 | "licenses": [
94 | "apache-2.0"
95 | ],
96 | "is_license_text": false,
97 | "is_license_notice": false,
98 | "is_license_reference": false,
99 | "is_license_tag": true,
100 | "is_license_intro": false,
101 | "matcher": "1-spdx-id",
102 | "rule_length": 6,
103 | "matched_length": 6,
104 | "match_coverage": 100.0,
105 | "rule_relevance": 100
106 | },
107 | "matched_text": "# SPDX-License-Identifier: Apache-2.0"
108 | }
109 | ],
110 | "license_expressions": [
111 | "apache-2.0"
112 | ],
113 | "percentage_of_license_text": 0.89,
114 | "copyrights": [
115 | {
116 | "value": "Copyright (c) 2020 LG Electronics Inc.",
117 | "start_line": 3,
118 | "end_line": 4
119 | }
120 | ],
121 | "holders": [
122 | {
123 | "value": "LG Electronics Inc.",
124 | "start_line": 3,
125 | "end_line": 4
126 | }
127 | ],
128 | "authors": [],
129 | "scan_errors": []
130 | },
131 | {
132 | "path": "sample_license.txt",
133 | "type": "file",
134 | "licenses": [
135 | {
136 | "key": "apache-2.0",
137 | "score": 100.0,
138 | "name": "Apache License 2.0",
139 | "short_name": "Apache 2.0",
140 | "category": "Permissive",
141 | "is_exception": false,
142 | "owner": "Apache Software Foundation",
143 | "homepage_url": "http://www.apache.org/licenses/",
144 | "text_url": "http://www.apache.org/licenses/LICENSE-2.0",
145 | "reference_url": "https://scancode-licensedb.aboutcode.org/apache-2.0",
146 | "scancode_text_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.LICENSE",
147 | "scancode_data_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.yml",
148 | "spdx_license_key": "Apache-2.0",
149 | "spdx_url": "https://spdx.org/licenses/Apache-2.0",
150 | "start_line": 1,
151 | "end_line": 73,
152 | "matched_rule": {
153 | "identifier": "apache-2.0.LICENSE",
154 | "license_expression": "apache-2.0",
155 | "licenses": [
156 | "apache-2.0"
157 | ],
158 | "is_license_text": true,
159 | "is_license_notice": false,
160 | "is_license_reference": false,
161 | "is_license_tag": false,
162 | "is_license_intro": false,
163 | "matcher": "1-hash",
164 | "rule_length": 1581,
165 | "matched_length": 1581,
166 | "match_coverage": 100.0,
167 | "rule_relevance": 100
168 | },
169 | "matched_text": "Apache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n\"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.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n\"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.\n\n\"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).\n\n\"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.\n\n\"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,\n but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"\n\n\"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.\n\n2. 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.\n\n3. 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.\n\n4. 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:\n\n (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices stating that You changed the files; and\n\n (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\n\n (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.\n\n 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.\n\n5. 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.\n\n6. 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.\n\n7. 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.\n\n8. 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.\n\n9. 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.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\nTo 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.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License."
170 | }
171 | ],
172 | "license_expressions": [
173 | "apache-2.0"
174 | ],
175 | "percentage_of_license_text": 100.0,
176 | "copyrights": [],
177 | "holders": [],
178 | "authors": [],
179 | "scan_errors": []
180 | },
181 | {
182 | "path": "Sample_MIT_LICENSE.txt",
183 | "type": "file",
184 | "licenses": [
185 | {
186 | "key": "mit",
187 | "score": 100.0,
188 | "name": "MIT License",
189 | "short_name": "MIT License",
190 | "category": "Permissive",
191 | "is_exception": false,
192 | "owner": "MIT",
193 | "homepage_url": "http://opensource.org/licenses/mit-license.php",
194 | "text_url": "http://opensource.org/licenses/mit-license.php",
195 | "reference_url": "https://scancode-licensedb.aboutcode.org/mit",
196 | "scancode_text_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/mit.LICENSE",
197 | "scancode_data_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/mit.yml",
198 | "spdx_license_key": "MIT",
199 | "spdx_url": "https://spdx.org/licenses/MIT",
200 | "start_line": 1,
201 | "end_line": 5,
202 | "matched_rule": {
203 | "identifier": "mit.LICENSE",
204 | "license_expression": "mit",
205 | "licenses": [
206 | "mit"
207 | ],
208 | "is_license_text": true,
209 | "is_license_notice": false,
210 | "is_license_reference": false,
211 | "is_license_tag": false,
212 | "is_license_intro": false,
213 | "matcher": "1-hash",
214 | "rule_length": 161,
215 | "matched_length": 161,
216 | "match_coverage": 100.0,
217 | "rule_relevance": 100
218 | },
219 | "matched_text": "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
220 | }
221 | ],
222 | "license_expressions": [
223 | "mit"
224 | ],
225 | "percentage_of_license_text": 100.0,
226 | "copyrights": [],
227 | "holders": [],
228 | "authors": [],
229 | "scan_errors": []
230 | },
231 | {
232 | "path": "test_known_spdx.txt",
233 | "type": "file",
234 | "licenses": [
235 | {
236 | "key": "apache-2.0",
237 | "score": 100.0,
238 | "name": "Apache License 2.0",
239 | "short_name": "Apache 2.0",
240 | "category": "Permissive",
241 | "is_exception": false,
242 | "owner": "Apache Software Foundation",
243 | "homepage_url": "http://www.apache.org/licenses/",
244 | "text_url": "http://www.apache.org/licenses/LICENSE-2.0",
245 | "reference_url": "https://scancode-licensedb.aboutcode.org/apache-2.0",
246 | "scancode_text_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.LICENSE",
247 | "scancode_data_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/apache-2.0.yml",
248 | "spdx_license_key": "Apache-2.0",
249 | "spdx_url": "https://spdx.org/licenses/Apache-2.0",
250 | "start_line": 4,
251 | "end_line": 4,
252 | "matched_rule": {
253 | "identifier": "spdx-license-identifier: apache-2.0",
254 | "license_expression": "apache-2.0",
255 | "licenses": [
256 | "apache-2.0"
257 | ],
258 | "is_license_text": false,
259 | "is_license_notice": false,
260 | "is_license_reference": false,
261 | "is_license_tag": true,
262 | "is_license_intro": false,
263 | "matcher": "1-spdx-id",
264 | "rule_length": 6,
265 | "matched_length": 6,
266 | "match_coverage": 100.0,
267 | "rule_relevance": 100
268 | },
269 | "matched_text": "# SPDX-License-Identifier: Apache-2.0"
270 | }
271 | ],
272 | "license_expressions": [
273 | "apache-2.0"
274 | ],
275 | "percentage_of_license_text": 19.35,
276 | "copyrights": [
277 | {
278 | "value": "Copyright (c) 2020 LG Electronics Inc.",
279 | "start_line": 3,
280 | "end_line": 4
281 | }
282 | ],
283 | "holders": [
284 | {
285 | "value": "LG Electronics Inc.",
286 | "start_line": 3,
287 | "end_line": 4
288 | }
289 | ],
290 | "authors": [],
291 | "scan_errors": []
292 | },
293 | {
294 | "path": "test_unknown_spdx.txt",
295 | "type": "file",
296 | "licenses": [
297 | {
298 | "key": "unknown-spdx",
299 | "score": 100.0,
300 | "name": "Unknown SPDX license detected but not recognized",
301 | "short_name": "unknown SPDX",
302 | "category": "Unstated License",
303 | "is_exception": false,
304 | "owner": "Unspecified",
305 | "homepage_url": null,
306 | "text_url": "",
307 | "reference_url": "https://scancode-licensedb.aboutcode.org/unknown-spdx",
308 | "scancode_text_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/unknown-spdx.LICENSE",
309 | "scancode_data_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/unknown-spdx.yml",
310 | "spdx_license_key": "LicenseRef-scancode-unknown-spdx",
311 | "spdx_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/unknown-spdx.LICENSE",
312 | "start_line": 4,
313 | "end_line": 4,
314 | "matched_rule": {
315 | "identifier": "spdx-license-identifier: unknown-spdx",
316 | "license_expression": "unknown-spdx",
317 | "licenses": [
318 | "unknown-spdx"
319 | ],
320 | "is_license_text": false,
321 | "is_license_notice": false,
322 | "is_license_reference": false,
323 | "is_license_tag": true,
324 | "is_license_intro": false,
325 | "matcher": "1-spdx-id",
326 | "rule_length": 6,
327 | "matched_length": 6,
328 | "match_coverage": 100.0,
329 | "rule_relevance": 100
330 | },
331 | "matched_text": "# SPDX-License-Identifier: LicenseRef-MIT-like"
332 | }
333 | ],
334 | "license_expressions": [
335 | "unknown-spdx"
336 | ],
337 | "percentage_of_license_text": 19.35,
338 | "copyrights": [
339 | {
340 | "value": "Copyright (c) 2020 LG Electronics Inc.",
341 | "start_line": 3,
342 | "end_line": 4
343 | }
344 | ],
345 | "holders": [
346 | {
347 | "value": "LG Electronics Inc.",
348 | "start_line": 3,
349 | "end_line": 4
350 | }
351 | ],
352 | "authors": [],
353 | "scan_errors": []
354 | },
355 | {
356 | "path": "test/MIT_TEST.txt",
357 | "type": "file",
358 | "licenses": [
359 | {
360 | "key": "mit",
361 | "score": 100.0,
362 | "name": "MIT License",
363 | "short_name": "MIT License",
364 | "category": "Permissive",
365 | "is_exception": false,
366 | "owner": "MIT",
367 | "homepage_url": "http://opensource.org/licenses/mit-license.php",
368 | "text_url": "http://opensource.org/licenses/mit-license.php",
369 | "reference_url": "https://scancode-licensedb.aboutcode.org/mit",
370 | "scancode_text_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/mit.LICENSE",
371 | "scancode_data_url": "https://github.com/nexB/scancode-toolkit/tree/develop/src/licensedcode/data/licenses/mit.yml",
372 | "spdx_license_key": "MIT",
373 | "spdx_url": "https://spdx.org/licenses/MIT",
374 | "start_line": 1,
375 | "end_line": 5,
376 | "matched_rule": {
377 | "identifier": "mit.LICENSE",
378 | "license_expression": "mit",
379 | "licenses": [
380 | "mit"
381 | ],
382 | "is_license_text": true,
383 | "is_license_notice": false,
384 | "is_license_reference": false,
385 | "is_license_tag": false,
386 | "is_license_intro": false,
387 | "matcher": "1-hash",
388 | "rule_length": 161,
389 | "matched_length": 161,
390 | "match_coverage": 100.0,
391 | "rule_relevance": 100
392 | },
393 | "matched_text": "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
394 | }
395 | ],
396 | "license_expressions": [
397 | "mit"
398 | ],
399 | "percentage_of_license_text": 100.0,
400 | "copyrights": [],
401 | "holders": [],
402 | "authors": [],
403 | "scan_errors": []
404 | }
405 | ]
406 | }
--------------------------------------------------------------------------------
/tests/test_files/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10 |
11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12 |
13 | "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.
14 |
15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16 |
17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18 |
19 | "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.
20 |
21 | "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).
22 |
23 | "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.
24 |
25 | "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."
26 |
27 | "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.
28 |
29 | 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.
30 |
31 | 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.
32 |
33 | 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:
34 |
35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36 |
37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38 |
39 | (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
40 |
41 | (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.
42 |
43 | 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.
44 |
45 | 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.
46 |
47 | 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.
48 |
49 | 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.
50 |
51 | 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.
52 |
53 | 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.
54 |
55 | END OF TERMS AND CONDITIONS
56 |
57 | APPENDIX: How to apply the Apache License to your work.
58 |
59 | 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.
60 |
61 | Copyright [yyyy] [name of copyright owner]
62 |
63 | Licensed under the Apache License, Version 2.0 (the "License");
64 | you may not use this file except in compliance with the License.
65 | You may obtain a copy of the License at
66 |
67 | http://www.apache.org/licenses/LICENSE-2.0
68 |
69 | Unless required by applicable law or agreed to in writing, software
70 | distributed under the License is distributed on an "AS IS" BASIS,
71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72 | See the License for the specific language governing permissions and
73 | limitations under the License.
--------------------------------------------------------------------------------
/tests/test_files/Sample_MIT_LICENSE.txt:
--------------------------------------------------------------------------------
1 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
2 |
3 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
4 |
5 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 |
--------------------------------------------------------------------------------
/tests/test_files/dual.txt:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2020 LG Electronics Inc.
2 | # Copyright (c) 2021 LG Electronics Inc.
3 | # REUSE-IgnoreStart
4 | # SPDX-License-Identifier: GPL-2.0 or MIT
5 | # REUSE-IgnoreEnd
6 |
--------------------------------------------------------------------------------
/tests/test_files/run_scancode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | # SPDX-PackageDownloadLocation: https://dummy_url_for_test.com
7 | # The code is not licensed under GPL-2.0.
8 |
9 | import sys
10 | import os
11 | import multiprocessing
12 | import warnings
13 | import platform
14 | import getopt
15 | import logging
16 | import yaml
17 | from scancode import cli
18 | from datetime import datetime
19 | import fosslight_util.constant as constant
20 | from fosslight_util.set_log import init_log
21 | from fosslight_util.timer_thread import TimerThread
22 | from ._parsing_scancode_file_item import parsing_file_item
23 | from ._parsing_scancode_file_item import get_error_from_header
24 | from fosslight_util.write_excel import write_excel_and_csv
25 | from ._help import print_help_msg_source_scanner
26 | from ._license_matched import get_license_list_to_print
27 |
28 | logger = logging.getLogger(constant.LOGGER_NAME)
29 | warnings.filterwarnings("ignore", category=FutureWarning)
30 | _PKG_NAME = "fosslight_source"
31 |
32 |
33 | def main():
34 | argv = sys.argv[1:]
35 | path_to_scan = ""
36 | write_json_file = False
37 | output_file = ""
38 | print_matched_text = False
39 |
40 | try:
41 | opts, args = getopt.getopt(argv, 'hmjp:o:')
42 | for opt, arg in opts:
43 | if opt == "-h":
44 | print_help_msg_source_scanner()
45 | elif opt == "-p":
46 | path_to_scan = arg
47 | elif opt == "-j":
48 | write_json_file = True
49 | elif opt == "-o":
50 | output_file = arg
51 | elif opt == "-m":
52 | print_matched_text = True
53 | except Exception:
54 | print_help_msg_source_scanner()
55 |
56 | timer = TimerThread()
57 | timer.setDaemon(True)
58 | timer.start()
59 | run_scan(path_to_scan, output_file, write_json_file, -1, False, print_matched_text)
60 |
61 |
62 | def run_scan(path_to_scan, output_file_name="",
63 | _write_json_file=False, num_cores=-1, return_results=False, need_license=False):
64 | global logger
65 |
66 | success = True
67 | msg = ""
68 | _str_final_result_log = ""
69 | _result_log = {}
70 | result_list = []
71 |
72 | _windows = platform.system() == "Windows"
73 | _start_time = datetime.now().strftime('%y%m%d_%H%M')
74 |
75 | if output_file_name == "":
76 | output_file = f"fosslight_report_{_start_time}"
77 | output_json_file = f"scancode_{_start_time}"
78 | output_dir = os.getcwd()
79 | else:
80 | output_file = output_file_name
81 | output_json_file = output_file_name
82 | output_dir = os.path.dirname(os.path.abspath(output_file_name))
83 |
84 | logger, _result_log = init_log(os.path.join(output_dir, f"fosslight_log_{_start_time}.txt"),
85 | True, logging.INFO, logging.DEBUG, _PKG_NAME, path_to_scan)
86 |
87 | if path_to_scan == "":
88 | if _windows:
89 | path_to_scan = os.getcwd()
90 | else:
91 | print_help_msg_source_scanner()
92 |
93 | num_cores = multiprocessing.cpu_count() - 1 if num_cores < 0 else num_cores
94 |
95 | if os.path.isdir(path_to_scan):
96 | try:
97 | output_json_file = f"{output_json_file}.json" if _write_json_file\
98 | else ""
99 |
100 | rc, results = cli.run_scan(path_to_scan, max_depth=100,
101 | strip_root=True, license=True,
102 | copyright=True, return_results=True,
103 | processes=num_cores,
104 | output_json_pp=output_json_file,
105 | only_findings=True, license_text=True)
106 |
107 | if not rc:
108 | msg = "Source code analysis failed."
109 | success = False
110 |
111 | if results:
112 | sheet_list = {}
113 | has_error = False
114 | if "headers" in results:
115 | has_error, error_msg = get_error_from_header(results["headers"])
116 | if has_error:
117 | _result_log["Error_files"] = error_msg
118 | msg = "Failed to analyze :" + error_msg
119 | if "files" in results:
120 | rc, result_list, parsing_msg, license_list = parsing_file_item(results["files"], has_error, need_license)
121 | _result_log["Parsing Log"] = parsing_msg
122 | if rc:
123 | if not success:
124 | success = True
125 | result_list = sorted(
126 | result_list, key=lambda row: (''.join(row.licenses)))
127 | sheet_list["SRC"] = [scan_item.get_row_to_print() for scan_item in result_list]
128 | if need_license:
129 | sheet_list["matched_text"] = get_license_list_to_print(license_list)
130 |
131 | success_to_write, writing_msg = write_excel_and_csv(
132 | output_file, sheet_list)
133 | logger.info(f"Writing excel : {success_to_write} {writing_msg}")
134 | if success_to_write:
135 | _result_log["FOSSLight Report"] = f"{output_file}.xlsx"
136 | except Exception as ex:
137 | success = False
138 | msg = str(ex)
139 | logger.error(f"Analyze {path_to_scan}: {msg}")
140 | else:
141 | success = False
142 | msg = f"Check the path to scan. : {path_to_scan}"
143 |
144 | if not return_results:
145 | result_list = []
146 |
147 | scan_result_msg = str(success) if msg == "" else str(success) + "," + msg
148 | _result_log["Scan Result"] = scan_result_msg
149 | _result_log["Output Directory"] = output_dir
150 | try:
151 | _str_final_result_log = yaml.safe_dump(_result_log, allow_unicode=True, sort_keys=True)
152 | logger.info(_str_final_result_log)
153 | except Exception as ex:
154 | logger.warning(f"Failed to print result log. {ex}")
155 | return success, _result_log["Scan Result"], result_list
156 |
157 |
158 | if __name__ == '__main__':
159 | main()
160 |
--------------------------------------------------------------------------------
/tests/test_files/run_scancode2.py:
--------------------------------------------------------------------------------
1 | # This file is a sample code for testing.
2 | # It should not be listed at Scancode result and
3 | # should be listed at SCANOSS result.
4 |
5 | import sys
6 | import os
7 | import multiprocessing
8 | import warnings
9 | import platform
10 | import getopt
11 | import logging
12 | import yaml
13 | from scancode import cli
14 | from datetime import datetime
15 | import fosslight_util.constant as constant
16 | from fosslight_util.set_log import init_log
17 | from fosslight_util.timer_thread import TimerThread
18 | from ._parsing_scancode_file_item import parsing_file_item
19 | from ._parsing_scancode_file_item import get_error_from_header
20 | from fosslight_util.write_excel import write_excel_and_csv
21 | from ._help import print_help_msg_source_scanner
22 | from ._license_matched import get_license_list_to_print
23 |
24 | logger = logging.getLogger(constant.LOGGER_NAME)
25 | warnings.filterwarnings("ignore", category=FutureWarning)
26 | _PKG_NAME = "fosslight_source"
27 |
28 |
29 | def main():
30 | argv = sys.argv[1:]
31 | path_to_scan = ""
32 | write_json_file = False
33 | output_file = ""
34 | print_matched_text = False
35 |
36 | try:
37 | opts, args = getopt.getopt(argv, 'hmjp:o:')
38 | for opt, arg in opts:
39 | if opt == "-h":
40 | print_help_msg_source_scanner()
41 | elif opt == "-p":
42 | path_to_scan = arg
43 | elif opt == "-j":
44 | write_json_file = True
45 | elif opt == "-o":
46 | output_file = arg
47 | elif opt == "-m":
48 | print_matched_text = True
49 | except Exception:
50 | print_help_msg_source_scanner()
51 |
52 | timer = TimerThread()
53 | timer.setDaemon(True)
54 | timer.start()
55 | run_scan(path_to_scan, output_file, write_json_file, -1, False, print_matched_text)
56 |
57 |
58 | def run_scan(path_to_scan, output_file_name="",
59 | _write_json_file=False, num_cores=-1, return_results=False, need_license=False):
60 | global logger
61 |
62 | success = True
63 | msg = ""
64 | _str_final_result_log = ""
65 | _result_log = {}
66 | result_list = []
67 |
68 | _windows = platform.system() == "Windows"
69 | _start_time = datetime.now().strftime('%y%m%d_%H%M')
70 |
71 | if output_file_name == "":
72 | output_file = f"fosslight_report_{_start_time}"
73 | output_json_file = f"scancode_{_start_time}"
74 | output_dir = os.getcwd()
75 | else:
76 | output_file = output_file_name
77 | output_json_file = output_file_name
78 | output_dir = os.path.dirname(os.path.abspath(output_file_name))
79 |
80 | logger, _result_log = init_log(os.path.join(output_dir, f"fosslight_log_{_start_time}.txt"),
81 | True, logging.INFO, logging.DEBUG, _PKG_NAME, path_to_scan)
82 |
83 | if path_to_scan == "":
84 | if _windows:
85 | path_to_scan = os.getcwd()
86 | else:
87 | print_help_msg_source_scanner()
88 |
89 | num_cores = multiprocessing.cpu_count() - 1 if num_cores < 0 else num_cores
90 |
91 | if os.path.isdir(path_to_scan):
92 | try:
93 | output_json_file = f"{output_json_file}.json" if _write_json_file\
94 | else ""
95 |
96 | rc, results = cli.run_scan(path_to_scan, max_depth=100,
97 | strip_root=True, license=True,
98 | copyright=True, return_results=True,
99 | processes=num_cores,
100 | output_json_pp=output_json_file,
101 | only_findings=True, license_text=True)
102 |
103 | if not rc:
104 | msg = "Source code analysis failed."
105 | success = False
106 |
107 | if results:
108 | sheet_list = {}
109 | has_error = False
110 | if "headers" in results:
111 | has_error, error_msg = get_error_from_header(results["headers"])
112 | if has_error:
113 | _result_log["Error_files"] = error_msg
114 | msg = "Failed to analyze :" + error_msg
115 | if "files" in results:
116 | rc, result_list, parsing_msg, license_list = parsing_file_item(results["files"], has_error, need_license)
117 | _result_log["Parsing Log"] = parsing_msg
118 | if rc:
119 | if not success:
120 | success = True
121 | result_list = sorted(
122 | result_list, key=lambda row: (''.join(row.licenses)))
123 | sheet_list["SRC"] = [scan_item.get_row_to_print() for scan_item in result_list]
124 | if need_license:
125 | sheet_list["matched_text"] = get_license_list_to_print(license_list)
126 |
127 | success_to_write, writing_msg = write_excel_and_csv(
128 | output_file, sheet_list)
129 | logger.info(f"Writing excel : {success_to_write} {writing_msg}")
130 | if success_to_write:
131 | _result_log["FOSSLight Report"] = f"{output_file}.xlsx"
132 | except Exception as ex:
133 | success = False
134 | msg = str(ex)
135 | logger.error(f"Analyze {path_to_scan}: {msg}")
136 | else:
137 | success = False
138 | msg = f"Check the path to scan. : {path_to_scan}"
139 |
140 | if not return_results:
141 | result_list = []
142 |
143 | scan_result_msg = str(success) if msg == "" else str(success) + "," + msg
144 | _result_log["Scan Result"] = scan_result_msg
145 | _result_log["Output Directory"] = output_dir
146 | try:
147 | _str_final_result_log = yaml.safe_dump(_result_log, allow_unicode=True, sort_keys=True)
148 | logger.info(_str_final_result_log)
149 | except Exception as ex:
150 | logger.warning(f"Failed to print result log. {ex}")
151 | return success, _result_log["Scan Result"], result_list
152 |
153 |
154 | if __name__ == '__main__':
155 | main()
156 |
--------------------------------------------------------------------------------
/tests/test_files/sample.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: Copyright 2022 LG Electronics Inc.
3 | * SPDX-License-Identifier: Apache-2.0
4 | * DownloadLocation: https://github.com/browserify/acorn-node
5 | * SPDX-FileCopyrightText: Copyright 2017 Free Software Foundation Europe e.V.
6 | * SPDX-License-Identifier: MIT
7 | * DownloadLocation: https://github.com/fsfe/reuse-tool
8 | * SPDX-PackageDownloadLocation: https://dummy_url_for_test.com
9 | * SPDX-PackageDownloadLocation: https://second_dummy_url_for_test.com
10 | * SPDX-PackageDownloadLocation: https://third_dummy_url_for_test.com
11 | */
12 | #include
13 |
14 | int main()
15 | {
16 | std::cout << "Hello, world!" << std::endl;
17 | return 0;
18 | }
19 |
--------------------------------------------------------------------------------
/tests/test_files/sample_license.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10 |
11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12 |
13 | "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.
14 |
15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16 |
17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18 |
19 | "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.
20 |
21 | "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).
22 |
23 | "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.
24 |
25 | "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."
26 |
27 | "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.
28 |
29 | 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.
30 |
31 | 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.
32 |
33 | 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:
34 |
35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36 |
37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38 |
39 | (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
40 |
41 | (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.
42 |
43 | 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.
44 |
45 | 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.
46 |
47 | 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.
48 |
49 | 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.
50 |
51 | 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.
52 |
53 | 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.
54 |
55 | END OF TERMS AND CONDITIONS
56 |
57 | APPENDIX: How to apply the Apache License to your work.
58 |
59 | 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.
60 |
61 | Copyright [yyyy] [name of copyright owner]
62 |
63 | Licensed under the Apache License, Version 2.0 (the "License");
64 | you may not use this file except in compliance with the License.
65 | You may obtain a copy of the License at
66 |
67 | http://www.apache.org/licenses/LICENSE-2.0
68 |
69 | Unless required by applicable law or agreed to in writing, software
70 | distributed under the License is distributed on an "AS IS" BASIS,
71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72 | See the License for the specific language governing permissions and
73 | limitations under the License.
74 |
--------------------------------------------------------------------------------
/tests/test_files/spdx_lic.txt:
--------------------------------------------------------------------------------
1 | # REUSE-IgnoreStart
2 | # SPDX-License-Identifier: licenseref-TEMP_LICENSE
3 | # REUSE-IgnoreEnd
4 |
--------------------------------------------------------------------------------
/tests/test_files/temp.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: Copyright 2022 LG Electronics Inc.
3 | * SPDX-License-Identifier: Apache-2.0
4 | * DownloadLocation: https://github.com/browserify/acorn-node
5 | */
6 | #include
7 |
8 | int main()
9 | {
10 | std::cout << "Hello, world!" << std::endl;
11 | return 0;
12 | }
13 |
--------------------------------------------------------------------------------
/tests/test_files/test/MIT_TEST.txt:
--------------------------------------------------------------------------------
1 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
2 |
3 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
4 |
5 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 |
--------------------------------------------------------------------------------
/tests/test_files/test/temp.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: Copyright 2022 LG Electronics Inc.
3 | * SPDX-License-Identifier: Apache-2.0
4 | * DownloadLocation: https://github.com/browserify/acorn-node
5 | */
6 | #include
7 |
8 | int main()
9 | {
10 | std::cout << "Hello, world!" << std::endl;
11 | return 0;
12 | }
13 |
--------------------------------------------------------------------------------
/tests/test_files/test_known_spdx.txt:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | import os
7 |
8 |
9 | def main():
10 | print("Sample Python File")
11 |
12 |
13 | if __name__ == '__main__':
14 | main()
15 |
--------------------------------------------------------------------------------
/tests/test_files/test_unknown_spdx.txt:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: LicenseRef-MIT-like
5 |
6 | import os
7 |
8 |
9 | def main():
10 | print("Sample Python File")
11 |
12 |
13 | if __name__ == '__main__':
14 | main()
15 |
--------------------------------------------------------------------------------
/tests/test_tox.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Copyright (c) 2020 LG Electronics Inc.
4 | # SPDX-License-Identifier: Apache-2.0
5 | import os
6 | import subprocess
7 | import pytest
8 | import shutil
9 |
10 | remove_directories = ["test_scan", "test_scan2", "test_scan3"]
11 |
12 |
13 | @pytest.fixture(scope="module", autouse=True)
14 | def setup_test_result_dir():
15 | print("==============setup==============")
16 | for dir in remove_directories:
17 | if os.path.exists(dir):
18 | shutil.rmtree(dir)
19 |
20 | yield
21 |
22 |
23 | def run_command(command):
24 | process = subprocess.run(command, shell=True, capture_output=True, text=True)
25 | success = (process.returncode == 0)
26 | return success, process.stdout if success else process.stderr
27 |
28 |
29 | def test_run():
30 | scan_success, _ = run_command("fosslight_source -p tests/test_files -j -m -o test_scan")
31 | scan_exclude_success, _ = run_command("fosslight_source -p tests -e test_files/test cli_test.py -j -m -o test_scan2")
32 | scan_files = os.listdir("test_scan")
33 | scan2_files = os.listdir('test_scan2')
34 |
35 | assert scan_success is True, "Test Run: Scan command failed"
36 | assert scan_exclude_success is True, "Test Run: Exclude command failed"
37 | assert len(scan_files) > 0, "Test Run: No scan files created in test_scan directory"
38 | assert len(scan2_files) > 0, "Test Run: No scan files created in test_scan2 directory"
39 |
40 |
41 | def test_help_command():
42 | success, msg = run_command("fosslight_source -h")
43 | assert success is True, f"Test Release: Help command failed :{msg}"
44 |
45 |
46 | def test_scan_command():
47 | success, _ = run_command("fosslight_source -p tests/test_files -o test_scan/scan_result.csv")
48 | assert success is True, "Test Release: Failed to generate scan result CSV file"
49 |
50 | assert os.path.exists("test_scan/scan_result.csv"), "Test Release: scan_result.csv file not generated"
51 |
52 | with open("test_scan/scan_result.csv", 'r') as file:
53 | content = file.read()
54 |
55 | assert len(content) > 0, "Test Release: scan_result.csv is empty"
56 | print(f"Content of scan_result.csv:\n{content}")
57 |
58 |
59 | def test_exclude_command():
60 | success, _ = run_command(
61 | "fosslight_source -p tests -e test_files/test cli_test.py -j -m -o test_scan2/scan_exclude_result.csv"
62 | )
63 | assert success is True, "Test release: Exclude scan failded"
64 |
65 | assert os.path.exists("test_scan2/scan_exclude_result.csv"), "Test Release: scan_exclude_result.csv file not generated"
66 |
67 | with open("test_scan2/scan_exclude_result.csv", 'r') as file:
68 | content = file.read()
69 |
70 | assert len(content) > 0, "Test Release: scan_exclude_result.csv is empty"
71 | print(f"Content of scan_exclude_result.csv:\n{content}")
72 |
73 |
74 | def test_json_command():
75 | success, _ = run_command("fosslight_source -p tests/test_files -m -j -o test_scan3/")
76 | assert success is True, "Test release: Failed to generate JSON files"
77 |
78 |
79 | def test_ls_test_scan3_command():
80 | files_in_test_scan3 = os.listdir("test_scan3")
81 | assert len(files_in_test_scan3) > 0, "Test Release: test_scan3 is empty"
82 | print(f"Files in test_scan3: {files_in_test_scan3}")
83 |
84 |
85 | def test_flake8():
86 | success, _ = run_command("flake8 -j 4")
87 | assert success is True, "Flake8: Style check failed"
88 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021 LG Electronics
2 | # SPDX-License-Identifier: Apache-2.0
3 | [tox]
4 | envlist = test_run
5 | skipdist = true
6 |
7 | [testenv]
8 | install_command = pip install {opts} {packages}
9 | allowlist_externals =
10 | cat
11 | rm
12 | ls
13 | pytest
14 | setenv =
15 | PYTHONPATH=.
16 |
17 | [flake8]
18 | max-line-length = 130
19 | exclude = .tox/*
20 |
21 | [pytest]
22 | filterwarnings = ignore::DeprecationWarning
23 |
24 | [testenv:test_run]
25 | deps =
26 | -r{toxinidir}/requirements-dev.txt
27 |
28 | commands =
29 | pytest tests/test_tox.py::test_run --maxfail=1 --disable-warnings --cache-clear
30 |
31 | [testenv:release]
32 | deps =
33 | -r{toxinidir}/requirements-dev.txt
34 |
35 | commands =
36 | pytest tests/test_tox.py::test_help_command tests/test_tox.py::test_scan_command \
37 | tests/test_tox.py::test_exclude_command tests/test_tox.py::test_json_command \
38 | --maxfail=1 --disable-warnings
39 |
40 | python tests/cli_test.py
41 | pytest -v --flake8
42 |
43 | [testenv:flake8]
44 | deps = flake8
45 | commands =
46 | pytest tests/test_tox.py::test_flake8
--------------------------------------------------------------------------------