From 6d0b1ef86864ecd01a65e4c4f87164514071fb17 Mon Sep 17 00:00:00 2001 From: Jonah Williams Date: Wed, 19 Feb 2020 18:56:04 -0800 Subject: [PATCH] [flutter_tools] include LICENSE files as build dependencies (#50945) --- packages/flutter_tools/lib/src/asset.dart | 172 +++++++---- .../lib/src/build_system/targets/assets.dart | 2 +- .../lib/src/dart/package_map.dart | 5 + .../build_system/targets/assets_test.dart | 111 ++++--- .../general.shard/license_collector_test.dart | 283 ++++++++++++++++++ 5 files changed, 472 insertions(+), 101 deletions(-) create mode 100644 packages/flutter_tools/test/general.shard/license_collector_test.dart diff --git a/packages/flutter_tools/lib/src/asset.dart b/packages/flutter_tools/lib/src/asset.dart index 01c29f8620..681d5035b7 100644 --- a/packages/flutter_tools/lib/src/asset.dart +++ b/packages/flutter_tools/lib/src/asset.dart @@ -4,6 +4,7 @@ import 'dart:async'; +import 'package:meta/meta.dart'; import 'package:yaml/yaml.dart'; import 'base/context.dart'; @@ -37,6 +38,10 @@ abstract class AssetBundleFactory { abstract class AssetBundle { Map get entries; + /// Additional files that this bundle depends on that are not included in the + /// output result. + List get additionalDependencies; + bool wasBuiltOnce(); bool needsBuild({ String manifestPath = defaultManifestPath }); @@ -70,6 +75,8 @@ class _ManifestAssetBundle implements AssetBundle { // updated without changes to the manifest. final Map _wildcardDirectories = {}; + final LicenseCollector licenseCollector = LicenseCollector(fileSystem: globals.fs); + DateTime _lastBuildTimestamp; static const String _assetManifestJson = 'AssetManifest.json'; @@ -246,10 +253,15 @@ class _ManifestAssetBundle implements AssetBundle { entries[kFontManifestJson] = DevFSStringContent(json.encode(fonts)); // TODO(ianh): Only do the following line if we've changed packages or if our LICENSE file changed - entries[_license] = _obtainLicenses(packageMap, assetBasePath, reportPackages: reportLicensedPackages); + final LicenseResult licenseResult = licenseCollector.obtainLicenses(packageMap); + entries[_license] = DevFSStringContent(licenseResult.combinedLicenses); + additionalDependencies = licenseResult.dependencies; return 0; } + + @override + List additionalDependencies = []; } class _Asset { @@ -336,78 +348,108 @@ List<_Asset> _getMaterialAssets(String fontSet) { return result; } -final String _licenseSeparator = '\n' + ('-' * 80) + '\n'; -/// Returns a DevFSContent representing the license file. -DevFSContent _obtainLicenses( - PackageMap packageMap, - String assetBase, { - bool reportPackages, -}) { - // Read the LICENSE file from each package in the .packages file, splitting - // each one into each component license (so that we can de-dupe if possible). - // - // Individual licenses inside each LICENSE file should be separated by 80 - // hyphens on their own on a line. - // - // If a LICENSE file contains more than one component license, then each - // component license must start with the names of the packages to which the - // component license applies, with each package name on its own line, and the - // list of package names separated from the actual license text by a blank - // line. (The packages need not match the names of the pub package. For - // example, a package might itself contain code from multiple third-party - // sources, and might need to include a license for each one.) - final Map> packageLicenses = >{}; - final Set allPackages = {}; - for (final String packageName in packageMap.map.keys) { - final Uri package = packageMap.map[packageName]; - if (package == null || package.scheme != 'file') { - continue; - } - final File file = globals.fs.file(package.resolve('../LICENSE')); - if (!file.existsSync()) { - continue; - } - final List rawLicenses = - file.readAsStringSync().split(_licenseSeparator); - for (final String rawLicense in rawLicenses) { - List packageNames; - String licenseText; - if (rawLicenses.length > 1) { - final int split = rawLicense.indexOf('\n\n'); - if (split >= 0) { - packageNames = rawLicense.substring(0, split).split('\n'); - licenseText = rawLicense.substring(split + 2); +/// Processes dependencies into a string representing the license file. +/// +/// Reads the LICENSE file from each package in the .packages file, splitting +/// each one into each component license (so that we can de-dupe if possible). +/// If provided with a pubspec.yaml file, only direct depedencies are included +/// in the resulting LICENSE file. +/// +/// Individual licenses inside each LICENSE file should be separated by 80 +/// hyphens on their own on a line. +/// +/// If a LICENSE file contains more than one component license, then each +/// component license must start with the names of the packages to which the +/// component license applies, with each package name on its own line, and the +/// list of package names separated from the actual license text by a blank +/// line. (The packages need not match the names of the pub package. For +/// example, a package might itself contain code from multiple third-party +/// sources, and might need to include a license for each one.) +// Note: this logic currently has a bug, in that we collect LICENSE information +// for dev_dependencies and transitive dev_dependencies. These are not actually +// compiled into the released application and don't need to be included. Unfortunately, +// the pubspec.yaml alone does not have enough information to determine which +// dependencies are transitive of dev_dependencies, so a simple filter isn't sufficient. +class LicenseCollector { + LicenseCollector({ + @required FileSystem fileSystem + }) : _fileSystem = fileSystem; + + final FileSystem _fileSystem; + + /// The expected separator for multiple licenses. + static final String licenseSeparator = '\n' + ('-' * 80) + '\n'; + + /// Obtain licenses from the `packageMap` into a single result. + LicenseResult obtainLicenses( + PackageMap packageMap, + ) { + final Map> packageLicenses = >{}; + final Set allPackages = {}; + final List dependencies = []; + + for (final String packageName in packageMap.map.keys) { + final Uri package = packageMap.map[packageName]; + if (package == null || package.scheme != 'file') { + continue; + } + final File file = _fileSystem.file(package.resolve('../LICENSE')); + if (!file.existsSync()) { + continue; + } + + dependencies.add(file); + final List rawLicenses = file + .readAsStringSync() + .split(licenseSeparator); + for (final String rawLicense in rawLicenses) { + List packageNames; + String licenseText; + if (rawLicenses.length > 1) { + final int split = rawLicense.indexOf('\n\n'); + if (split >= 0) { + packageNames = rawLicense.substring(0, split).split('\n'); + licenseText = rawLicense.substring(split + 2); + } } + if (licenseText == null) { + packageNames = [packageName]; + licenseText = rawLicense; + } + packageLicenses.putIfAbsent(licenseText, () => {}) + ..addAll(packageNames); + allPackages.addAll(packageNames); } - if (licenseText == null) { - packageNames = [packageName]; - licenseText = rawLicense; - } - packageLicenses.putIfAbsent(licenseText, () => {}) - ..addAll(packageNames); - allPackages.addAll(packageNames); } + final List combinedLicensesList = packageLicenses.keys + .map((String license) { + final List packageNames = packageLicenses[license].toList() + ..sort(); + return packageNames.join('\n') + '\n\n' + license; + }).toList(); + combinedLicensesList.sort(); + final String combinedLicenses = combinedLicensesList.join(licenseSeparator); + + return LicenseResult( + combinedLicenses: combinedLicenses, + dependencies: dependencies, + ); } +} - if (reportPackages) { - final List allPackagesList = allPackages.toList()..sort(); - globals.printStatus('Licenses were found for the following packages:'); - globals.printStatus(allPackagesList.join(', ')); - } +/// The result of processing licenses with a [LicenseCollector]. +class LicenseResult { + const LicenseResult({ + @required this.combinedLicenses, + @required this.dependencies, + }); - final List combinedLicensesList = packageLicenses.keys.map( - (String license) { - final List packageNames = packageLicenses[license].toList() - ..sort(); - return packageNames.join('\n') + '\n\n' + license; - } - ).toList(); - combinedLicensesList.sort(); + /// The raw text of the consumed licenses. + final String combinedLicenses; - final String combinedLicenses = combinedLicensesList.join(_licenseSeparator); - - return DevFSStringContent(combinedLicenses); + /// Each license file that was consumed as input. + final List dependencies; } int _byBasename(_Asset a, _Asset b) { diff --git a/packages/flutter_tools/lib/src/build_system/targets/assets.dart b/packages/flutter_tools/lib/src/build_system/targets/assets.dart index ade1722d27..e3f80153b9 100644 --- a/packages/flutter_tools/lib/src/build_system/targets/assets.dart +++ b/packages/flutter_tools/lib/src/build_system/targets/assets.dart @@ -72,7 +72,7 @@ Future copyAssets(Environment environment, Directory outputDirectory) a resource.release(); } })); - return Depfile(inputs, outputs); + return Depfile(inputs + assetBundle.additionalDependencies, outputs); } /// Copy the assets defined in the flutter manifest into a build directory. diff --git a/packages/flutter_tools/lib/src/dart/package_map.dart b/packages/flutter_tools/lib/src/dart/package_map.dart index bdda309fc8..f8bb0bd4b8 100644 --- a/packages/flutter_tools/lib/src/dart/package_map.dart +++ b/packages/flutter_tools/lib/src/dart/package_map.dart @@ -17,6 +17,11 @@ Map _parse(String packagesPath) { class PackageMap { PackageMap(this.packagesPath); + /// Create a [PackageMap] for testing. + PackageMap.test(Map input) + : packagesPath = '.packages', + _map = input; + static String get globalPackagesPath => _globalPackagesPath ?? kPackagesFileName; static set globalPackagesPath(String value) { diff --git a/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart b/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart index 1e92228541..b9563e433d 100644 --- a/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart +++ b/packages/flutter_tools/test/general.shard/build_system/targets/assets_test.dart @@ -2,35 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:file/memory.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; +import 'package:flutter_tools/src/build_system/depfile.dart'; import 'package:flutter_tools/src/build_system/targets/assets.dart'; -import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:platform/platform.dart'; import '../../../src/common.dart'; -import '../../../src/testbed.dart'; +import '../../../src/context.dart'; void main() { Environment environment; - Testbed testbed; + FileSystem fileSystem; + Platform platform; setUp(() { - testbed = Testbed(setup: () { - environment = Environment.test( - globals.fs.currentDirectory, - ); - globals.fs.file(environment.buildDir.childFile('app.dill')).createSync(recursive: true); - globals.fs.file(globals.fs.path.join('packages', 'flutter_tools', 'lib', 'src', - 'build_system', 'targets', 'assets.dart')) - ..createSync(recursive: true); - globals.fs.file(globals.fs.path.join('assets', 'foo', 'bar.png')) - ..createSync(recursive: true); - globals.fs.file(globals.fs.path.join('assets', 'wildcard', '#bar.png')) - ..createSync(recursive: true); - globals.fs.file('.packages') - ..createSync(); - globals.fs.file('pubspec.yaml') - ..createSync() - ..writeAsStringSync(''' + platform = FakePlatform(); + fileSystem = MemoryFileSystem.test(); + environment = Environment.test( + fileSystem.currentDirectory, + ); + fileSystem.file(environment.buildDir.childFile('app.dill')).createSync(recursive: true); + fileSystem.file('packages/flutter_tools/lib/src/build_system/targets/assets.dart') + ..createSync(recursive: true); + fileSystem.file('assets/foo/bar.png') + ..createSync(recursive: true); + fileSystem.file('assets/wildcard/#bar.png') + ..createSync(recursive: true); + fileSystem.file('.packages') + ..createSync(); + fileSystem.file('pubspec.yaml') + ..createSync() + ..writeAsStringSync(''' name: example flutter: @@ -38,29 +43,65 @@ flutter: - assets/foo/bar.png - assets/wildcard/ '''); - }); }); - test('Copies files to correct asset directory', () => testbed.run(() async { + testUsingContext('includes LICENSE file inputs in dependencies', () async { + fileSystem.file('.packages') + .writeAsStringSync('foo:file:///bar/lib'); + fileSystem.file('bar/LICENSE') + ..createSync(recursive: true) + ..writeAsStringSync('THIS IS A LICENSE'); + await const CopyAssets().build(environment); - expect(globals.fs.file(globals.fs.path.join(environment.buildDir.path, 'flutter_assets', 'AssetManifest.json')).existsSync(), true); - expect(globals.fs.file(globals.fs.path.join(environment.buildDir.path, 'flutter_assets', 'FontManifest.json')).existsSync(), true); - expect(globals.fs.file(globals.fs.path.join(environment.buildDir.path, 'flutter_assets', 'LICENSE')).existsSync(), true); - // See https://github.com/flutter/flutter/issues/35293 - expect(globals.fs.file(globals.fs.path.join(environment.buildDir.path, 'flutter_assets', 'assets/foo/bar.png')).existsSync(), true); - // See https://github.com/flutter/flutter/issues/46163 - expect(globals.fs.file(globals.fs.path.join(environment.buildDir.path, 'flutter_assets', 'assets/wildcard/%23bar.png')).existsSync(), true); - })); + final File depfile = environment.buildDir.childFile('flutter_assets.d'); - test('FlutterPlugins updates required files as needed', () => testbed.run(() async { - globals.fs.file('pubspec.yaml') + expect(depfile, exists); + + final DepfileService depfileService = DepfileService( + logger: null, + fileSystem: fileSystem, + platform: platform, + ); + final Depfile dependencies = depfileService.parse(depfile); + + expect( + dependencies.inputs.firstWhere((File file) => file.path == '/bar/LICENSE', orElse: () => null), + isNotNull, + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + Platform: () => platform, + }); + + testUsingContext('Copies files to correct asset directory', () async { + await const CopyAssets().build(environment); + + expect(fileSystem.file('${environment.buildDir.path}/flutter_assets/AssetManifest.json'), exists); + expect(fileSystem.file('${environment.buildDir.path}/flutter_assets/FontManifest.json'), exists); + expect(fileSystem.file('${environment.buildDir.path}/flutter_assets/LICENSE'), exists); + // See https://github.com/flutter/flutter/issues/35293 + expect(fileSystem.file('${environment.buildDir.path}/flutter_assets/assets/foo/bar.png'), exists); + // See https://github.com/flutter/flutter/issues/46163 + expect(fileSystem.file('${environment.buildDir.path}/flutter_assets/assets/wildcard/%23bar.png'), exists); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + Platform: () => platform, + }); + + testUsingContext('FlutterPlugins updates required files as needed', () async { + fileSystem.file('pubspec.yaml') ..writeAsStringSync('name: foo\ndependencies:\n foo: any\n'); await const FlutterPlugins().build(Environment.test( - globals.fs.currentDirectory, + fileSystem.currentDirectory, )); - expect(globals.fs.file('.flutter-plugins').existsSync(), true); - })); + expect(fileSystem.file('.flutter-plugins'), exists); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + }); } diff --git a/packages/flutter_tools/test/general.shard/license_collector_test.dart b/packages/flutter_tools/test/general.shard/license_collector_test.dart new file mode 100644 index 0000000000..7e886dedd6 --- /dev/null +++ b/packages/flutter_tools/test/general.shard/license_collector_test.dart @@ -0,0 +1,283 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:file/memory.dart'; +import 'package:flutter_tools/src/asset.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/dart/package_map.dart'; + +import '../src/common.dart'; + +const String _kMitLicense = r''' +MIT License + +Copyright (c) 6789 Lester + +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: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +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. +'''; + +const String _kApacheLicense = r''' + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 1234 Tester + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +'''; + +void main() { + FileSystem fileSystem; + LicenseCollector licenseCollector; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + licenseCollector = LicenseCollector(fileSystem: fileSystem); + }); + + testWithoutContext('processes dependant licenses according to instructions', () { + fileSystem.file('foo/LICENSE') + ..createSync(recursive: true) + ..writeAsStringSync(_kMitLicense); + fileSystem.file('bar/LICENSE') + ..createSync(recursive: true) + ..writeAsStringSync(_kApacheLicense); + fileSystem.file('fizz/LICENSE') + ..createSync(recursive: true) + ..writeAsStringSync(_kMitLicense); // intentionally a duplicate + + final PackageMap packageMap = PackageMap.test({ + 'foo': Uri.parse('file:///foo/lib/'), + 'bar': Uri.parse('file:///bar/lib/'), + 'fizz': Uri.parse('file:///fizz/lib/'), + }); + + final LicenseResult result = licenseCollector.obtainLicenses(packageMap); + + // All included licenses are combined in the result. + expect(result.combinedLicenses, contains(_kApacheLicense)); + expect(result.combinedLicenses, contains(_kMitLicense)); + + // Licenses are de-duplicated correctly. + expect(result.combinedLicenses.split(LicenseCollector.licenseSeparator), hasLength(2)); + + // All input licenses included in result. + final Iterable filePaths = result.dependencies.map((File file) => file.path); + expect(filePaths, unorderedEquals([ + '/foo/LICENSE', + '/bar/LICENSE', + '/fizz/LICENSE' + ])); + }); +}