From 45256983f45f5cd48ee07146161c067128a21a71 Mon Sep 17 00:00:00 2001 From: attiasas Date: Wed, 10 Jan 2024 16:04:39 +0200 Subject: [PATCH 01/12] Remove Security content --- .../commands/utils/conditionaluploadutils.go | 7 +- go.mod | 3 +- go.sum | 20 +- utils/dependencies/utils.go | 78 +- utils/dependencies/utils_test.go | 2 +- utils/python/utils_test.go | 9 +- utils/tests/test_utils.go | 17 +- utils/usage/usage.go | 2 +- {xray/utils => utils/xray}/xraymanager.go | 0 xray/commands/audit/audit.go | 193 - xray/commands/audit/auditparams.go | 99 - .../jas/applicability/applicabilitymanager.go | 195 - .../applicabilitymanager_test.go | 336 - xray/commands/audit/jas/common.go | 278 - xray/commands/audit/jas/common_test.go | 90 - xray/commands/audit/jas/commons_test.go | 129 - xray/commands/audit/jas/iac/iacscanner.go | 103 - .../commands/audit/jas/iac/iacscanner_test.go | 83 - xray/commands/audit/jas/sast/sastscanner.go | 147 - .../audit/jas/sast/sastscanner_test.go | 156 - .../audit/jas/secrets/secretsscanner.go | 121 - .../audit/jas/secrets/secretsscanner_test.go | 132 - .../jas/testdata/.jfrog/jfrog-apps-config.yml | 50 - xray/commands/audit/jasrunner.go | 60 - xray/commands/audit/jasrunner_test.go | 44 - xray/commands/audit/sca/common.go | 215 - xray/commands/audit/sca/common_test.go | 225 - xray/commands/audit/sca/go/gloang_test.go | 76 - xray/commands/audit/sca/go/golang.go | 115 - .../commands/audit/sca/java/deptreemanager.go | 132 - .../audit/sca/java/deptreemanager_test.go | 65 - xray/commands/audit/sca/java/gradle.go | 199 - xray/commands/audit/sca/java/gradle_test.go | 230 - xray/commands/audit/sca/java/mvn.go | 193 - xray/commands/audit/sca/java/mvn_test.go | 258 - .../sca/java/resources/gradle-dep-tree.jar | Bin 12152 -> 0 bytes .../sca/java/resources/maven-dep-tree.jar | Bin 13862 -> 0 bytes .../audit/sca/java/resources/settings.xml | 19 - xray/commands/audit/sca/npm/npm.go | 140 - xray/commands/audit/sca/npm/npm_test.go | 122 - xray/commands/audit/sca/nuget/nuget.go | 236 - xray/commands/audit/sca/nuget/nuget_test.go | 146 - xray/commands/audit/sca/python/python.go | 282 - xray/commands/audit/sca/python/python_test.go | 145 - xray/commands/audit/sca/yarn/yarn.go | 217 - xray/commands/audit/sca/yarn/yarn_test.go | 101 - xray/commands/audit/scarunner.go | 313 - xray/commands/audit/scarunner_test.go | 306 - xray/commands/curation/curationaudit.go | 573 - xray/commands/curation/curationaudit_test.go | 580 - xray/commands/curl/curl.go | 17 - xray/commands/offlineupdate/offlineupdate.go | 476 - .../offlineupdate/offlineupdate_test.go | 138 - xray/commands/scan/buildscan.go | 168 - xray/commands/scan/dockerscan.go | 145 - xray/commands/scan/downloadindexer.go | 193 - xray/commands/scan/downloadindexer_test.go | 59 - xray/commands/scan/scan.go | 454 - .../applicable-cve-results.sarif | 84 - .../applicability-scan/empty-results.sarif | 29 - .../no-applicable-cves-results.sarif | 121 - .../testdata/artifactory-maven-plugin/pom.xml | 327 - .../org/jfrog/buildinfo/ArtifactoryMojo.java | 174 - .../main/java/org/jfrog/buildinfo/Config.java | 57 - .../buildinfo/deployment/BuildDeployer.java | 152 - .../BuildInfoModelPropertyResolver.java | 100 - .../deployment/BuildInfoRecorder.java | 465 - .../resolution/RepositoryListener.java | 85 - .../resolution/ResolutionRepoHelper.java | 122 - .../buildinfo/types/ModuleArtifacts.java | 51 - .../utils/ArtifactoryMavenLogger.java | 50 - .../java/org/jfrog/buildinfo/utils/Utils.java | 223 - .../resources/META-INF/plexus/components.xml | 14 - .../ClassLibrary1/ClassLibrary1.csproj | 23 - .../SharedProject1/SharedProject1.projitems | 13 - .../SharedProject1/SharedProject1.shproj | 13 - .../dotnet-multi/TestApp1/TestApp1.csproj | 41 - .../dotnet-multi/TestSolution.sln | 31 - .../dotnet-projects/dotnet-single/Class1.cs | 6 - .../dotnet-single/dotnet-single.csproj | 16 - xray/commands/testdata/go-project/go.mod.txt | 7 - xray/commands/testdata/go-project/go.sum.txt | 8 - xray/commands/testdata/go-project/test.go.txt | 10 - .../.jfrog/projects/gradle.yaml | 4 - .../gradle-example-ci-server/api/build.gradle | 15 - .../main/java/org/gradle/api/PersonList.java | 38 - .../src/main/java/org/gradle/api/package.html | 19 - .../main/java/org/gradle/apiImpl/Impl.java | 26 - .../gradle-example-ci-server/build.gradle | 33 - .../gradle/wrapper/gradle-wrapper.jar | Bin 55616 -> 0 bytes .../gradle/wrapper/gradle-wrapper.properties | 5 - .../testdata/gradle-example-ci-server/gradlew | 188 - .../gradle-example-ci-server/gradlew.bat | 100 - .../services/webservice/build.gradle | 8 - .../java/org/gradle/webservice/TestTest.java | 35 - .../org/gradle/webservice/TestTestTest.java | 31 - .../gradle-example-ci-server/settings.gradle | 1 - .../main/java/org/gradle/shared/Person.java | 42 - .../java/org/gradle/shared/package-info.java | 20 - .../org/gradle/shared/main.properties | 17 - .../.jfrog/projects/gradle.yaml | 4 - .../gradle-example-publish/api/build.gradle | 15 - .../main/java/org/gradle/api/PersonList.java | 38 - .../src/main/java/org/gradle/api/package.html | 19 - .../main/java/org/gradle/apiImpl/Impl.java | 26 - .../gradle-example-publish/build.gradle | 131 - .../gradle-example-publish/gradle.properties | 3 - .../gradle/wrapper/gradle-wrapper.jar | Bin 55616 -> 0 bytes .../gradle/wrapper/gradle-wrapper.properties | 5 - .../testdata/gradle-example-publish/gradlew | 188 - .../gradle-example-publish/gradlew.bat | 100 - .../services/webservice/build.gradle | 7 - .../java/org/gradle/webservice/TestTest.java | 35 - .../org/gradle/webservice/TestTestTest.java | 31 - .../gradle-example-publish/settings.gradle | 1 - .../main/java/org/gradle/shared/Person.java | 42 - .../java/org/gradle/shared/package-info.java | 20 - .../org/gradle/shared/main.properties | 17 - .../contains-iac-violations-working-dir.sarif | 669 - .../iac-scan/contains-iac-violations.sarif | 129 - .../testdata/iac-scan/no-violations.sarif | 30 - .../.mvn/wrapper/MavenWrapperDownloader.java | 117 - .../.mvn/wrapper/maven-wrapper.jar | Bin 50710 -> 0 bytes .../.mvn/wrapper/maven-wrapper.properties | 2 - .../maven-example-with-wrapper/multi1/pom.xml | 89 - .../main/java/artifactory/test/Multi1.java | 10 - .../test/java/artifactory/test/AppTest.java | 38 - .../classes/artifactory/test/Multi1.class | Bin 556 -> 0 bytes .../compile/default-compile/createdFiles.lst | 1 - .../compile/default-compile/inputFiles.lst | 1 - .../default-testCompile/createdFiles.lst | 1 - .../default-testCompile/inputFiles.lst | 1 - .../artifactory/test/AppTest.class | Bin 611 -> 0 bytes .../maven-example-with-wrapper/multi2/pom.xml | 19 - .../src/main/java/artifactory/test/App.java | 13 - .../test/java/artifactory/test/AppTest.java | 38 - .../target/classes/artifactory/test/App.class | Bin 547 -> 0 bytes .../compile/default-compile/createdFiles.lst | 1 - .../compile/default-compile/inputFiles.lst | 1 - .../default-testCompile/createdFiles.lst | 1 - .../default-testCompile/inputFiles.lst | 1 - .../artifactory/test/AppTest.class | Bin 611 -> 0 bytes .../maven-example-with-wrapper/multi3/pom.xml | 76 - .../main/java/artifactory/test/Multi3.java | 11 - .../multi3/src/main/webapp/WEB-INF/web.xml | 9 - .../test/java/artifactory/test/AppTest.java | 38 - .../classes/artifactory/test/Multi3.class | Bin 602 -> 0 bytes .../compile/default-compile/createdFiles.lst | 1 - .../compile/default-compile/inputFiles.lst | 1 - .../default-testCompile/createdFiles.lst | 1 - .../default-testCompile/inputFiles.lst | 1 - .../artifactory/test/AppTest.class | Bin 611 -> 0 bytes .../testdata/maven-example-with-wrapper/mvnw | 310 - .../maven-example-with-wrapper/mvnw.cmd | 182 - .../maven-example-with-wrapper/pom.xml | 73 - .../maven-example/.jfrog/projects/maven.yaml | 6 - .../testdata/maven-example/multi1/pom.xml | 74 - .../testdata/maven-example/multi2/pom.xml | 19 - .../testdata/maven-example/multi3/pom.xml | 77 - xray/commands/testdata/maven-example/pom.xml | 31 - .../npm-project/.jfrog/projects/npm.yaml | 5 - .../testdata/npm-project/package-lock.json | 30 - .../testdata/npm-project/package.json | 15 - .../testdata/npm-scripts/package.json | 7 - xray/commands/testdata/npm/dependencies.json | 447 - .../commands/testdata/nuget/dependencies.json | 194 - .../commands/testdata/nuget/expectedTree.json | 92 - .../requirementsproject/requirements.txt | 1 - .../pip-project/setuppyproject/setup.py | 9 - xray/commands/testdata/pipenv-project/Pipfile | 13 - .../my_poetry_project/__init__.py | 1 - .../testdata/poetry-project/poetry.lock | 169 - .../testdata/poetry-project/pyproject.toml | 16 - .../testdata/poetry-project/tests/__init__.py | 0 .../tests/test_my_poetry_project.py | 5 - .../sast-scan/contains-sast-violations.sarif | 907 - .../testdata/sast-scan/no-violations.sarif | 28 - .../secrets-scan/contain-secrets.sarif | 234 - .../testdata/secrets-scan/no-secrets.sarif | 29 - .../.yarn/releases/yarn-1.22.21.cjs | 147513 --------------- xray/commands/testdata/yarn-project/.yarnrc | 5 - .../testdata/yarn-project/.yarnrc.yml | 3 - .../testdata/yarn-project/package.json | 10 - xray/formats/conversion.go | 196 - xray/formats/simplejsonapi.go | 123 - xray/formats/table.go | 137 - xray/scangraph/params.go | 59 - xray/scangraph/scangraph.go | 108 - xray/scangraph/scangraph_test.go | 161 - xray/utils/analyzermanager.go | 201 - xray/utils/analyzermanager_test.go | 59 - xray/utils/auditbasicparams.go | 194 - xray/utils/auditnpmparams.go | 25 - xray/utils/results.go | 100 - xray/utils/resultstable.go | 1050 - xray/utils/resultstable_test.go | 1061 - xray/utils/resultwriter.go | 571 - xray/utils/resultwriter_test.go | 379 - xray/utils/sarifutils.go | 267 - xray/utils/sarifutils_test.go | 672 - xray/utils/test_sarifutils.go | 64 - 201 files changed, 38 insertions(+), 169572 deletions(-) rename {xray/utils => utils/xray}/xraymanager.go (100%) delete mode 100644 xray/commands/audit/audit.go delete mode 100644 xray/commands/audit/auditparams.go delete mode 100644 xray/commands/audit/jas/applicability/applicabilitymanager.go delete mode 100644 xray/commands/audit/jas/applicability/applicabilitymanager_test.go delete mode 100644 xray/commands/audit/jas/common.go delete mode 100644 xray/commands/audit/jas/common_test.go delete mode 100644 xray/commands/audit/jas/commons_test.go delete mode 100644 xray/commands/audit/jas/iac/iacscanner.go delete mode 100644 xray/commands/audit/jas/iac/iacscanner_test.go delete mode 100644 xray/commands/audit/jas/sast/sastscanner.go delete mode 100644 xray/commands/audit/jas/sast/sastscanner_test.go delete mode 100644 xray/commands/audit/jas/secrets/secretsscanner.go delete mode 100644 xray/commands/audit/jas/secrets/secretsscanner_test.go delete mode 100644 xray/commands/audit/jas/testdata/.jfrog/jfrog-apps-config.yml delete mode 100644 xray/commands/audit/jasrunner.go delete mode 100644 xray/commands/audit/jasrunner_test.go delete mode 100644 xray/commands/audit/sca/common.go delete mode 100644 xray/commands/audit/sca/common_test.go delete mode 100644 xray/commands/audit/sca/go/gloang_test.go delete mode 100644 xray/commands/audit/sca/go/golang.go delete mode 100644 xray/commands/audit/sca/java/deptreemanager.go delete mode 100644 xray/commands/audit/sca/java/deptreemanager_test.go delete mode 100644 xray/commands/audit/sca/java/gradle.go delete mode 100644 xray/commands/audit/sca/java/gradle_test.go delete mode 100644 xray/commands/audit/sca/java/mvn.go delete mode 100644 xray/commands/audit/sca/java/mvn_test.go delete mode 100644 xray/commands/audit/sca/java/resources/gradle-dep-tree.jar delete mode 100644 xray/commands/audit/sca/java/resources/maven-dep-tree.jar delete mode 100644 xray/commands/audit/sca/java/resources/settings.xml delete mode 100644 xray/commands/audit/sca/npm/npm.go delete mode 100644 xray/commands/audit/sca/npm/npm_test.go delete mode 100644 xray/commands/audit/sca/nuget/nuget.go delete mode 100644 xray/commands/audit/sca/nuget/nuget_test.go delete mode 100644 xray/commands/audit/sca/python/python.go delete mode 100644 xray/commands/audit/sca/python/python_test.go delete mode 100644 xray/commands/audit/sca/yarn/yarn.go delete mode 100644 xray/commands/audit/sca/yarn/yarn_test.go delete mode 100644 xray/commands/audit/scarunner.go delete mode 100644 xray/commands/audit/scarunner_test.go delete mode 100644 xray/commands/curation/curationaudit.go delete mode 100644 xray/commands/curation/curationaudit_test.go delete mode 100644 xray/commands/curl/curl.go delete mode 100644 xray/commands/offlineupdate/offlineupdate.go delete mode 100644 xray/commands/offlineupdate/offlineupdate_test.go delete mode 100644 xray/commands/scan/buildscan.go delete mode 100644 xray/commands/scan/dockerscan.go delete mode 100644 xray/commands/scan/downloadindexer.go delete mode 100644 xray/commands/scan/downloadindexer_test.go delete mode 100644 xray/commands/scan/scan.go delete mode 100644 xray/commands/testdata/applicability-scan/applicable-cve-results.sarif delete mode 100644 xray/commands/testdata/applicability-scan/empty-results.sarif delete mode 100644 xray/commands/testdata/applicability-scan/no-applicable-cves-results.sarif delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/pom.xml delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/ArtifactoryMojo.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/Config.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildDeployer.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoModelPropertyResolver.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoRecorder.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/RepositoryListener.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/ResolutionRepoHelper.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/types/ModuleArtifacts.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/ArtifactoryMavenLogger.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/Utils.java delete mode 100644 xray/commands/testdata/artifactory-maven-plugin/src/main/resources/META-INF/plexus/components.xml delete mode 100644 xray/commands/testdata/dotnet-projects/dotnet-multi/ClassLibrary1/ClassLibrary1.csproj delete mode 100644 xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.projitems delete mode 100644 xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.shproj delete mode 100644 xray/commands/testdata/dotnet-projects/dotnet-multi/TestApp1/TestApp1.csproj delete mode 100644 xray/commands/testdata/dotnet-projects/dotnet-multi/TestSolution.sln delete mode 100644 xray/commands/testdata/dotnet-projects/dotnet-single/Class1.cs delete mode 100644 xray/commands/testdata/dotnet-projects/dotnet-single/dotnet-single.csproj delete mode 100644 xray/commands/testdata/go-project/go.mod.txt delete mode 100644 xray/commands/testdata/go-project/go.sum.txt delete mode 100644 xray/commands/testdata/go-project/test.go.txt delete mode 100644 xray/commands/testdata/gradle-example-ci-server/.jfrog/projects/gradle.yaml delete mode 100644 xray/commands/testdata/gradle-example-ci-server/api/build.gradle delete mode 100644 xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/PersonList.java delete mode 100644 xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/package.html delete mode 100644 xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/apiImpl/Impl.java delete mode 100644 xray/commands/testdata/gradle-example-ci-server/build.gradle delete mode 100644 xray/commands/testdata/gradle-example-ci-server/gradle/wrapper/gradle-wrapper.jar delete mode 100644 xray/commands/testdata/gradle-example-ci-server/gradle/wrapper/gradle-wrapper.properties delete mode 100755 xray/commands/testdata/gradle-example-ci-server/gradlew delete mode 100644 xray/commands/testdata/gradle-example-ci-server/gradlew.bat delete mode 100644 xray/commands/testdata/gradle-example-ci-server/services/webservice/build.gradle delete mode 100644 xray/commands/testdata/gradle-example-ci-server/services/webservice/src/main/java/org/gradle/webservice/TestTest.java delete mode 100644 xray/commands/testdata/gradle-example-ci-server/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java delete mode 100644 xray/commands/testdata/gradle-example-ci-server/settings.gradle delete mode 100644 xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/Person.java delete mode 100644 xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/package-info.java delete mode 100644 xray/commands/testdata/gradle-example-ci-server/shared/src/main/resources/org/gradle/shared/main.properties delete mode 100644 xray/commands/testdata/gradle-example-publish/.jfrog/projects/gradle.yaml delete mode 100644 xray/commands/testdata/gradle-example-publish/api/build.gradle delete mode 100644 xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/PersonList.java delete mode 100644 xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/package.html delete mode 100644 xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/apiImpl/Impl.java delete mode 100644 xray/commands/testdata/gradle-example-publish/build.gradle delete mode 100644 xray/commands/testdata/gradle-example-publish/gradle.properties delete mode 100644 xray/commands/testdata/gradle-example-publish/gradle/wrapper/gradle-wrapper.jar delete mode 100644 xray/commands/testdata/gradle-example-publish/gradle/wrapper/gradle-wrapper.properties delete mode 100755 xray/commands/testdata/gradle-example-publish/gradlew delete mode 100644 xray/commands/testdata/gradle-example-publish/gradlew.bat delete mode 100644 xray/commands/testdata/gradle-example-publish/services/webservice/build.gradle delete mode 100644 xray/commands/testdata/gradle-example-publish/services/webservice/src/main/java/org/gradle/webservice/TestTest.java delete mode 100644 xray/commands/testdata/gradle-example-publish/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java delete mode 100644 xray/commands/testdata/gradle-example-publish/settings.gradle delete mode 100644 xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/Person.java delete mode 100644 xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/package-info.java delete mode 100644 xray/commands/testdata/gradle-example-publish/shared/src/main/resources/org/gradle/shared/main.properties delete mode 100644 xray/commands/testdata/iac-scan/contains-iac-violations-working-dir.sarif delete mode 100644 xray/commands/testdata/iac-scan/contains-iac-violations.sarif delete mode 100644 xray/commands/testdata/iac-scan/no-violations.sarif delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/MavenWrapperDownloader.java delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/maven-wrapper.jar delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/maven-wrapper.properties delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/pom.xml delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/src/main/java/artifactory/test/Multi1.java delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/src/test/java/artifactory/test/AppTest.java delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/target/classes/artifactory/test/Multi1.class delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi1/target/test-classes/artifactory/test/AppTest.class delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/pom.xml delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/src/main/java/artifactory/test/App.java delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/src/test/java/artifactory/test/AppTest.java delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/target/classes/artifactory/test/App.class delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi2/target/test-classes/artifactory/test/AppTest.class delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/pom.xml delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/java/artifactory/test/Multi3.java delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/webapp/WEB-INF/web.xml delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/src/test/java/artifactory/test/AppTest.java delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/target/classes/artifactory/test/Multi3.class delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/multi3/target/test-classes/artifactory/test/AppTest.class delete mode 100755 xray/commands/testdata/maven-example-with-wrapper/mvnw delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/mvnw.cmd delete mode 100644 xray/commands/testdata/maven-example-with-wrapper/pom.xml delete mode 100644 xray/commands/testdata/maven-example/.jfrog/projects/maven.yaml delete mode 100644 xray/commands/testdata/maven-example/multi1/pom.xml delete mode 100644 xray/commands/testdata/maven-example/multi2/pom.xml delete mode 100644 xray/commands/testdata/maven-example/multi3/pom.xml delete mode 100644 xray/commands/testdata/maven-example/pom.xml delete mode 100644 xray/commands/testdata/npm-project/.jfrog/projects/npm.yaml delete mode 100644 xray/commands/testdata/npm-project/package-lock.json delete mode 100644 xray/commands/testdata/npm-project/package.json delete mode 100644 xray/commands/testdata/npm-scripts/package.json delete mode 100644 xray/commands/testdata/npm/dependencies.json delete mode 100644 xray/commands/testdata/nuget/dependencies.json delete mode 100644 xray/commands/testdata/nuget/expectedTree.json delete mode 100644 xray/commands/testdata/pip-project/requirementsproject/requirements.txt delete mode 100644 xray/commands/testdata/pip-project/setuppyproject/setup.py delete mode 100644 xray/commands/testdata/pipenv-project/Pipfile delete mode 100644 xray/commands/testdata/poetry-project/my_poetry_project/__init__.py delete mode 100644 xray/commands/testdata/poetry-project/poetry.lock delete mode 100644 xray/commands/testdata/poetry-project/pyproject.toml delete mode 100644 xray/commands/testdata/poetry-project/tests/__init__.py delete mode 100644 xray/commands/testdata/poetry-project/tests/test_my_poetry_project.py delete mode 100644 xray/commands/testdata/sast-scan/contains-sast-violations.sarif delete mode 100644 xray/commands/testdata/sast-scan/no-violations.sarif delete mode 100644 xray/commands/testdata/secrets-scan/contain-secrets.sarif delete mode 100644 xray/commands/testdata/secrets-scan/no-secrets.sarif delete mode 100755 xray/commands/testdata/yarn-project/.yarn/releases/yarn-1.22.21.cjs delete mode 100644 xray/commands/testdata/yarn-project/.yarnrc delete mode 100755 xray/commands/testdata/yarn-project/.yarnrc.yml delete mode 100755 xray/commands/testdata/yarn-project/package.json delete mode 100644 xray/formats/conversion.go delete mode 100644 xray/formats/simplejsonapi.go delete mode 100644 xray/formats/table.go delete mode 100644 xray/scangraph/params.go delete mode 100644 xray/scangraph/scangraph.go delete mode 100644 xray/scangraph/scangraph_test.go delete mode 100644 xray/utils/analyzermanager.go delete mode 100644 xray/utils/analyzermanager_test.go delete mode 100644 xray/utils/auditbasicparams.go delete mode 100644 xray/utils/auditnpmparams.go delete mode 100644 xray/utils/results.go delete mode 100644 xray/utils/resultstable.go delete mode 100644 xray/utils/resultstable_test.go delete mode 100644 xray/utils/resultwriter.go delete mode 100644 xray/utils/resultwriter_test.go delete mode 100644 xray/utils/sarifutils.go delete mode 100644 xray/utils/sarifutils_test.go delete mode 100644 xray/utils/test_sarifutils.go diff --git a/artifactory/commands/utils/conditionaluploadutils.go b/artifactory/commands/utils/conditionaluploadutils.go index afda088bf..fd345b71b 100644 --- a/artifactory/commands/utils/conditionaluploadutils.go +++ b/artifactory/commands/utils/conditionaluploadutils.go @@ -2,7 +2,6 @@ package utils import ( "github.com/jfrog/jfrog-cli-core/v2/common/format" - xraycommands "github.com/jfrog/jfrog-cli-core/v2/xray/commands/scan" "strings" "github.com/jfrog/jfrog-cli-core/v2/common/spec" @@ -13,7 +12,7 @@ import ( type ConditionalUploadScanFuncType func(serverDetails *config.ServerDetails, fileSpec *spec.SpecFiles, threads int, scanOutputFormat format.OutputFormat) error // Function to run as a condition to upload. If not overridden, the default scan function is used. -var ConditionalUploadScanFunc ConditionalUploadScanFuncType = conditionalUploadDefaultScanFunc +var ConditionalUploadScanFunc ConditionalUploadScanFuncType = nil // ScanDeployableArtifacts scans all files founds in the given parsed deployableArtifacts results. // If the scan passes, the function returns two file-specs ready for upload. The first one contains all the binaries @@ -49,7 +48,3 @@ func parseTargetPath(target, serverUrl string) string { } return target } - -func conditionalUploadDefaultScanFunc(serverDetails *config.ServerDetails, fileSpec *spec.SpecFiles, threads int, scanOutputFormat format.OutputFormat) error { - return xraycommands.NewScanCommand().SetServerDetails(serverDetails).SetSpec(fileSpec).SetThreads(threads).SetOutputFormat(scanOutputFormat).SetFail(true).SetPrintExtendedTable(false).Run() -} diff --git a/go.mod b/go.mod index 072b06be4..e2f328514 100644 --- a/go.mod +++ b/go.mod @@ -14,11 +14,9 @@ require ( github.com/jedib0t/go-pretty/v6 v6.5.0 github.com/jfrog/build-info-go v1.9.20 github.com/jfrog/gofrog v1.4.1 - github.com/jfrog/jfrog-apps-config v1.0.1 github.com/jfrog/jfrog-client-go v1.35.6 github.com/magiconair/properties v1.8.7 github.com/manifoldco/promptui v0.9.0 - github.com/owenrumney/go-sarif/v2 v2.3.0 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c github.com/spf13/viper v1.18.2 github.com/stretchr/testify v1.8.4 @@ -86,6 +84,7 @@ require ( github.com/subosito/gotenv v1.6.0 // indirect github.com/ulikunitz/xz v0.5.9 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect go.uber.org/atomic v1.9.0 // indirect diff --git a/go.sum b/go.sum index 06c8443ee..9473e88a5 100644 --- a/go.sum +++ b/go.sum @@ -16,7 +16,6 @@ github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat6 github.com/andybalholm/brotli v1.0.1 h1:KqhlKozYbRtJvsPrrEeXcO+N2l6NYT5A2QAFmSULpEc= github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= -github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/bradleyjkemp/cupaloy/v2 v2.8.0 h1:any4BmKE+jGIaMpnU8YgH/I2LPiLBufr6oMMlVBbn9M= github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= @@ -68,11 +67,8 @@ github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOW github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw= github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= @@ -91,8 +87,6 @@ github.com/jfrog/build-info-go v1.9.20 h1:tQF6EMjt/EEX8syTrgpL/c7FjhlBSjtv848jNv github.com/jfrog/build-info-go v1.9.20/go.mod h1:Vxv6zmx4e1NWsx40OHaDWCCYDeYAq2yXzpJ4nsDChbE= github.com/jfrog/gofrog v1.4.1 h1:jz4kXBdsvVCNRDVkGLRiZIQ+uTO6/DSxQ9LjfvmLfoY= github.com/jfrog/gofrog v1.4.1/go.mod h1:wQqagqq2VpuCWRPlq/65GbH9gsRz+7Bgc1Q+PKD4Y+k= -github.com/jfrog/jfrog-apps-config v1.0.1 h1:mtv6k7g8A8BVhlHGlSveapqf4mJfonwvXYLipdsOFMY= -github.com/jfrog/jfrog-apps-config v1.0.1/go.mod h1:8AIIr1oY9JuH5dylz2S6f8Ym2MaadPLR6noCBO4C22w= github.com/jfrog/jfrog-client-go v1.35.6 h1:nVS94x6cwSRkhtj8OM3elbUcGgQhqsK8YMPvC/gf5sk= github.com/jfrog/jfrog-client-go v1.35.6/go.mod h1:V+XKC27k6GA5OcWIAItpnxZAZnCigg8xCkpXKP905Fk= github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4= @@ -138,9 +132,6 @@ github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RR github.com/nwaples/rardecode v1.1.0 h1:vSxaY8vQhOcVr4mm5e8XllHWTiM4JF507A0Katqw7MQ= github.com/nwaples/rardecode v1.1.0/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0= github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= -github.com/owenrumney/go-sarif v1.1.1/go.mod h1:dNDiPlF04ESR/6fHlPyq7gHKmrM0sHUvAGjsoh8ZH0U= -github.com/owenrumney/go-sarif/v2 v2.3.0 h1:wP5yEpI53zr0v5cBmagXzLbHZp9Oylyo3AJDpfLBITs= -github.com/owenrumney/go-sarif/v2 v2.3.0/go.mod h1:MSqMMx9WqlBSY7pXoOZWgEsVB4FDNfhcaXDA1j6Sr+w= github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= github.com/pierrec/lz4/v4 v4.1.2 h1:qvY3YFXRQE/XB8MlLzJH7mSzBs74eA2gg52YTk6jUPM= @@ -188,7 +179,6 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= @@ -204,11 +194,10 @@ github.com/urfave/cli v1.22.14 h1:ebbhrRiGK2i4naQJr+1Xj92HXZCrK7MsyTS/ob3HnAk= github.com/urfave/cli v1.22.14/go.mod h1:X0eDS6pD6Exaclxm99NJ3FiCDRED7vIHpx2mDOHLvkA= github.com/vbauerster/mpb/v7 v7.5.3 h1:BkGfmb6nMrrBQDFECR/Q7RkKCw7ylMetCb4079CGs4w= github.com/vbauerster/mpb/v7 v7.5.3/go.mod h1:i+h4QY6lmLvBNK2ah1fSreiw3ajskRlBp9AhY/PnuOE= -github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= -github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo= @@ -216,7 +205,6 @@ github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMx github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8= github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/zclconf/go-cty v1.10.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= @@ -234,9 +222,7 @@ golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91 golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -287,9 +273,7 @@ golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/term v0.16.0 h1:m+B6fahuftsE9qjo0VWp2FW0mB3MTJvR0BaMQrq0pmE= golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= @@ -305,9 +289,7 @@ golang.org/x/tools v0.16.0 h1:GO788SKMRunPIBCXiQyo2AaexLstOrVhuAL5YwsckQM= golang.org/x/tools v0.16.0/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= diff --git a/utils/dependencies/utils.go b/utils/dependencies/utils.go index 559c9ec44..e6b25b131 100644 --- a/utils/dependencies/utils.go +++ b/utils/dependencies/utils.go @@ -3,20 +3,19 @@ package dependencies import ( "errors" "fmt" + "net/http" + "os" + "path" + biutils "github.com/jfrog/build-info-go/utils" "github.com/jfrog/jfrog-cli-core/v2/utils/config" "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" "github.com/jfrog/jfrog-client-go/http/httpclient" "github.com/jfrog/jfrog-client-go/http/jfroghttpclient" "github.com/jfrog/jfrog-client-go/utils/errorutils" "github.com/jfrog/jfrog-client-go/utils/io/fileutils" "github.com/jfrog/jfrog-client-go/utils/io/httputils" "github.com/jfrog/jfrog-client-go/utils/log" - "net/http" - "os" - "path" - "path/filepath" ) const ( @@ -37,58 +36,7 @@ func DownloadExtractor(targetPath, downloadPath string) error { return DownloadDependency(artDetails, remotePath, targetPath, false) } -// Download the latest AnalyzerManager executable if not cached locally. -// By default, the zip is downloaded directly from jfrog releases. -func DownloadAnalyzerManagerIfNeeded() error { - downloadPath, err := xrayutils.GetAnalyzerManagerDownloadPath() - if err != nil { - return err - } - artDetails, remotePath, err := getAnalyzerManagerRemoteDetails(downloadPath) - if err != nil { - return err - } - // Check if the AnalyzerManager should be downloaded. - // First get the latest AnalyzerManager checksum from Artifactory. - client, httpClientDetails, err := createHttpClient(artDetails) - if err != nil { - return err - } - downloadUrl := artDetails.ArtifactoryUrl + remotePath - remoteFileDetails, _, err := client.GetRemoteFileDetails(downloadUrl, &httpClientDetails) - if err != nil { - return fmt.Errorf("couldn't get remote file details for %s: %s", downloadUrl, err.Error()) - } - analyzerManagerDir, err := xrayutils.GetAnalyzerManagerDirAbsolutePath() - if err != nil { - return err - } - // Find current AnalyzerManager checksum. - checksumFilePath := filepath.Join(analyzerManagerDir, ChecksumFileName) - exist, err := fileutils.IsFileExists(checksumFilePath, false) - if err != nil { - return err - } - if exist { - var sha2 []byte - sha2, err = fileutils.ReadFile(checksumFilePath) - if err != nil { - return err - } - // If the checksums are identical, there's no need to download. - if remoteFileDetails.Checksum.Sha256 == string(sha2) { - return nil - } - } - // Download & unzip the analyzer manager files - log.Debug("The 'Analyzer Manager' app is not cached locally. Downloading it now...") - if err = DownloadDependency(artDetails, remotePath, filepath.Join(analyzerManagerDir, xrayutils.AnalyzerManagerZipName), true); err != nil { - return err - } - return createChecksumFile(checksumFilePath, remoteFileDetails.Checksum.Sha256) -} - -func createChecksumFile(targetPath, checksum string) (err error) { +func CreateChecksumFile(targetPath, checksum string) (err error) { out, err := os.Create(targetPath) defer func() { e := errorutils.CheckError(out.Close()) @@ -125,7 +73,7 @@ func GetExtractorsRemoteDetails(downloadPath string) (server *config.ServerDetai } func getExtractorsRemoteDetailsFromEnv(downloadPath string) (server *config.ServerDetails, remoteRepo string, err error) { - server, remoteRepo, err = getRemoteDetails(coreutils.ReleasesRemoteEnv) + server, remoteRepo, err = GetRemoteDetails(coreutils.ReleasesRemoteEnv) if remoteRepo != "" && err == nil { remoteRepo = getFullExtractorsPathInArtifactory(remoteRepo, coreutils.ReleasesRemoteEnv, downloadPath) } @@ -133,7 +81,7 @@ func getExtractorsRemoteDetailsFromEnv(downloadPath string) (server *config.Serv } func getExtractorsRemoteDetailsFromLegacyEnv(downloadPath string) (server *config.ServerDetails, remoteRepo string, err error) { - server, remoteRepo, err = getRemoteDetails(coreutils.DeprecatedExtractorsRemoteEnv) + server, remoteRepo, err = GetRemoteDetails(coreutils.DeprecatedExtractorsRemoteEnv) if remoteRepo != "" && err == nil { log.Warn(fmt.Sprintf("You are using the deprecated %q environment variable. Use %q instead.\nRead more about it at %sjfrog-cli/downloading-the-maven-and-gradle-extractor-jars", coreutils.DeprecatedExtractorsRemoteEnv, coreutils.ReleasesRemoteEnv, coreutils.JFrogHelpUrl)) @@ -142,12 +90,12 @@ func getExtractorsRemoteDetailsFromLegacyEnv(downloadPath string) (server *confi return } -// getRemoteDetails function retrieves the server details and downloads path for the build-info extractor file. +// GetRemoteDetails function retrieves the server details and downloads path for the build-info extractor file. // serverAndRepo - the server id and the remote repository that proxies releases.jfrog.io, in form of '/'. // downloadPath - specifies the path in the remote repository from which the extractors will be downloaded. // remoteEnv - the relevant environment variable that was used: releasesRemoteEnv/ExtractorsRemoteEnv. // The function returns the server that matches the given server ID, the complete path of the build-info extractor concatenated with the specified remote repository, and an error if occurred. -func getRemoteDetails(remoteEnv string) (server *config.ServerDetails, repoName string, err error) { +func GetRemoteDetails(remoteEnv string) (server *config.ServerDetails, repoName string, err error) { serverID, repoName, err := coreutils.GetServerIdAndRepo(remoteEnv) if err != nil { return @@ -185,7 +133,7 @@ func DownloadDependency(artDetails *config.ServerDetails, downloadPath, targetPa }() // Get the expected check-sum before downloading - client, httpClientDetails, err := createHttpClient(artDetails) + client, httpClientDetails, err := CreateHttpClient(artDetails) if err != nil { return err } @@ -204,7 +152,7 @@ func DownloadDependency(artDetails *config.ServerDetails, downloadPath, targetPa LocalFileName: filename, ExpectedSha1: expectedSha1, } - client, httpClientDetails, err = createHttpClient(artDetails) + client, httpClientDetails, err = CreateHttpClient(artDetails) if err != nil { return err } @@ -222,7 +170,7 @@ func DownloadDependency(artDetails *config.ServerDetails, downloadPath, targetPa return biutils.CopyDir(tempDirPath, localDir, true, nil) } -func createHttpClient(artDetails *config.ServerDetails) (rtHttpClient *jfroghttpclient.JfrogHttpClient, httpClientDetails httputils.HttpClientDetails, err error) { +func CreateHttpClient(artDetails *config.ServerDetails) (rtHttpClient *jfroghttpclient.JfrogHttpClient, httpClientDetails httputils.HttpClientDetails, err error) { auth, err := artDetails.CreateArtAuthConfig() if err != nil { return @@ -245,7 +193,7 @@ func createHttpClient(artDetails *config.ServerDetails) (rtHttpClient *jfroghttp func getAnalyzerManagerRemoteDetails(downloadPath string) (server *config.ServerDetails, fullRemotePath string, err error) { var remoteRepo string - server, remoteRepo, err = getRemoteDetails(coreutils.ReleasesRemoteEnv) + server, remoteRepo, err = GetRemoteDetails(coreutils.ReleasesRemoteEnv) if err != nil { return } diff --git a/utils/dependencies/utils_test.go b/utils/dependencies/utils_test.go index a45a44012..a6393bb72 100644 --- a/utils/dependencies/utils_test.go +++ b/utils/dependencies/utils_test.go @@ -43,7 +43,7 @@ func TestCreateHttpClient(t *testing.T) { User: "elmar", Password: "Egghead", } - httpClient, httpClientDetails, err := createHttpClient(serverDetails) + httpClient, httpClientDetails, err := CreateHttpClient(serverDetails) assert.NoError(t, err) assert.NotNil(t, httpClient) assert.NotNil(t, httpClientDetails) diff --git a/utils/python/utils_test.go b/utils/python/utils_test.go index f36b87f1f..f6520b47b 100644 --- a/utils/python/utils_test.go +++ b/utils/python/utils_test.go @@ -1,12 +1,13 @@ package utils import ( + "path/filepath" + "testing" + biutils "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" + "github.com/jfrog/jfrog-cli-core/v2/utils/tests" "github.com/jfrog/jfrog-client-go/utils/io/fileutils" "github.com/stretchr/testify/assert" - "path/filepath" - "testing" ) func TestAddRepoToPyprojectFile(t *testing.T) { @@ -28,7 +29,7 @@ func initPoetryTest(t *testing.T) (string, func()) { // Create and change directory to test workspace testAbs, err := filepath.Abs(filepath.Join("..", "..", "xray", "commands", "testdata", "poetry-project")) assert.NoError(t, err) - poetryProjectPath, cleanUp := sca.CreateTestWorkspace(t, "poetry-project") + poetryProjectPath, cleanUp := tests.CreateTestWorkspace(t, "poetry-project") assert.NoError(t, biutils.CopyDir(testAbs, poetryProjectPath, true, nil)) return poetryProjectPath, cleanUp } diff --git a/utils/tests/test_utils.go b/utils/tests/test_utils.go index 55a06b1ad..42a013b0a 100644 --- a/utils/tests/test_utils.go +++ b/utils/tests/test_utils.go @@ -8,10 +8,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - + biutils "github.com/jfrog/build-info-go/utils" "github.com/jfrog/jfrog-client-go/utils/io/fileutils" "github.com/jfrog/jfrog-client-go/utils/log" + "github.com/jfrog/jfrog-client-go/utils/tests" + "github.com/stretchr/testify/assert" ) // Prepare the .git environment for the test. Takes an existing folder and making it .git dir. @@ -90,3 +91,15 @@ func CleanUpOldItems(baseItemNames []string, getActualItems func() ([]string, er } } } + +func CreateTestWorkspace(t *testing.T, sourceDir string) (string, func()) { + tempDirPath, createTempDirCallback := CreateTempDirWithCallbackAndAssert(t) + assert.NoError(t, biutils.CopyDir(sourceDir, tempDirPath, true, nil)) + wd, err := os.Getwd() + assert.NoError(t, err, "Failed to get current dir") + chdirCallback := tests.ChangeDirWithCallback(t, wd, tempDirPath) + return tempDirPath, func() { + chdirCallback() + createTempDirCallback() + } +} diff --git a/utils/usage/usage.go b/utils/usage/usage.go index 821f619e5..500d70f3d 100644 --- a/utils/usage/usage.go +++ b/utils/usage/usage.go @@ -6,7 +6,7 @@ import ( "github.com/jfrog/jfrog-cli-core/v2/artifactory/utils" "github.com/jfrog/jfrog-cli-core/v2/utils/config" "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" + xrayutils "github.com/jfrog/jfrog-cli-core/v2/utils/xray" "github.com/jfrog/jfrog-client-go/artifactory/usage" clientutils "github.com/jfrog/jfrog-client-go/utils" "github.com/jfrog/jfrog-client-go/utils/errorutils" diff --git a/xray/utils/xraymanager.go b/utils/xray/xraymanager.go similarity index 100% rename from xray/utils/xraymanager.go rename to utils/xray/xraymanager.go diff --git a/xray/commands/audit/audit.go b/xray/commands/audit/audit.go deleted file mode 100644 index d430022fd..000000000 --- a/xray/commands/audit/audit.go +++ /dev/null @@ -1,193 +0,0 @@ -package audit - -import ( - "errors" - "os" - - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/dependencies" - "github.com/jfrog/jfrog-cli-core/v2/xray/scangraph" - clientutils "github.com/jfrog/jfrog-client-go/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/jfrog/jfrog-client-go/xray" - "github.com/jfrog/jfrog-client-go/xray/services" - "golang.org/x/sync/errgroup" - - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" -) - -type AuditCommand struct { - watches []string - projectKey string - targetRepoPath string - IncludeVulnerabilities bool - IncludeLicenses bool - Fail bool - PrintExtendedTable bool - AuditParams -} - -func NewGenericAuditCommand() *AuditCommand { - return &AuditCommand{AuditParams: *NewAuditParams()} -} - -func (auditCmd *AuditCommand) SetWatches(watches []string) *AuditCommand { - auditCmd.watches = watches - return auditCmd -} - -func (auditCmd *AuditCommand) SetProject(project string) *AuditCommand { - auditCmd.projectKey = project - return auditCmd -} - -func (auditCmd *AuditCommand) SetTargetRepoPath(repoPath string) *AuditCommand { - auditCmd.targetRepoPath = repoPath - return auditCmd -} - -func (auditCmd *AuditCommand) SetIncludeVulnerabilities(include bool) *AuditCommand { - auditCmd.IncludeVulnerabilities = include - return auditCmd -} - -func (auditCmd *AuditCommand) SetIncludeLicenses(include bool) *AuditCommand { - auditCmd.IncludeLicenses = include - return auditCmd -} - -func (auditCmd *AuditCommand) SetFail(fail bool) *AuditCommand { - auditCmd.Fail = fail - return auditCmd -} - -func (auditCmd *AuditCommand) SetPrintExtendedTable(printExtendedTable bool) *AuditCommand { - auditCmd.PrintExtendedTable = printExtendedTable - return auditCmd -} - -func (auditCmd *AuditCommand) CreateXrayGraphScanParams() *services.XrayGraphScanParams { - params := &services.XrayGraphScanParams{ - RepoPath: auditCmd.targetRepoPath, - Watches: auditCmd.watches, - ScanType: services.Dependency, - } - if auditCmd.projectKey == "" { - params.ProjectKey = os.Getenv(coreutils.Project) - } else { - params.ProjectKey = auditCmd.projectKey - } - params.IncludeVulnerabilities = auditCmd.IncludeVulnerabilities - params.IncludeLicenses = auditCmd.IncludeLicenses - return params -} - -func (auditCmd *AuditCommand) Run() (err error) { - workingDirs, err := coreutils.GetFullPathsWorkingDirs(auditCmd.workingDirs) - if err != nil { - return - } - auditParams := NewAuditParams(). - SetXrayGraphScanParams(auditCmd.CreateXrayGraphScanParams()). - SetWorkingDirs(workingDirs). - SetMinSeverityFilter(auditCmd.minSeverityFilter). - SetFixableOnly(auditCmd.fixableOnly). - SetGraphBasicParams(auditCmd.AuditBasicParams). - SetThirdPartyApplicabilityScan(auditCmd.thirdPartyApplicabilityScan). - SetExclusions(auditCmd.exclusions) - auditResults, err := RunAudit(auditParams) - if err != nil { - return - } - if auditCmd.Progress() != nil { - if err = auditCmd.Progress().Quit(); err != nil { - return - } - } - var messages []string - if !auditResults.ExtendedScanResults.EntitledForJas { - messages = []string{coreutils.PrintTitle("The ‘jf audit’ command also supports JFrog Advanced Security features, such as 'Contextual Analysis', 'Secret Detection', 'IaC Scan' and ‘SAST’.\nThis feature isn't enabled on your system. Read more - ") + coreutils.PrintLink("https://jfrog.com/xray/")} - } - // Print Scan results on all cases except if errors accrued on SCA scan and no security/license issues found. - printScanResults := !(auditResults.ScaError != nil && !auditResults.IsScaIssuesFound()) - if printScanResults { - if err = xrayutils.NewResultsWriter(auditResults). - SetIsMultipleRootProject(auditResults.IsMultipleProject()). - SetIncludeVulnerabilities(auditCmd.IncludeVulnerabilities). - SetIncludeLicenses(auditCmd.IncludeLicenses). - SetOutputFormat(auditCmd.OutputFormat()). - SetPrintExtendedTable(auditCmd.PrintExtendedTable). - SetExtraMessages(messages). - SetScanType(services.Dependency). - PrintScanResults(); err != nil { - return - } - } - if err = errors.Join(auditResults.ScaError, auditResults.JasError); err != nil { - return - } - - // Only in case Xray's context was given (!auditCmd.IncludeVulnerabilities), and the user asked to fail the build accordingly, do so. - if auditCmd.Fail && !auditCmd.IncludeVulnerabilities && xrayutils.CheckIfFailBuild(auditResults.GetScaScansXrayResults()) { - err = xrayutils.NewFailBuildError() - } - return -} - -func (auditCmd *AuditCommand) CommandName() string { - return "generic_audit" -} - -// Runs an audit scan based on the provided auditParams. -// Returns an audit Results object containing all the scan results. -// If the current server is entitled for JAS, the advanced security results will be included in the scan results. -func RunAudit(auditParams *AuditParams) (results *xrayutils.Results, err error) { - // Initialize Results struct - results = xrayutils.NewAuditResults() - - serverDetails, err := auditParams.ServerDetails() - if err != nil { - return - } - var xrayManager *xray.XrayServicesManager - if xrayManager, auditParams.xrayVersion, err = xrayutils.CreateXrayServiceManagerAndGetVersion(serverDetails); err != nil { - return - } - if err = clientutils.ValidateMinimumVersion(clientutils.Xray, auditParams.xrayVersion, scangraph.GraphScanMinXrayVersion); err != nil { - return - } - results.XrayVersion = auditParams.xrayVersion - results.ExtendedScanResults.EntitledForJas, err = isEntitledForJas(xrayManager, auditParams.xrayVersion) - if err != nil { - return - } - - errGroup := new(errgroup.Group) - if results.ExtendedScanResults.EntitledForJas { - // Download (if needed) the analyzer manager in a background routine. - errGroup.Go(dependencies.DownloadAnalyzerManagerIfNeeded) - } - - // The sca scan doesn't require the analyzer manager, so it can run separately from the analyzer manager download routine. - results.ScaError = runScaScan(auditParams, results) // runScaScan(auditParams, results) - - // Wait for the Download of the AnalyzerManager to complete. - if err = errGroup.Wait(); err != nil { - err = errors.New("failed while trying to get Analyzer Manager: " + err.Error()) - } - - // Run scanners only if the user is entitled for Advanced Security - if results.ExtendedScanResults.EntitledForJas { - results.JasError = runJasScannersAndSetResults(results, auditParams.DirectDependencies(), serverDetails, auditParams.workingDirs, auditParams.Progress(), auditParams.xrayGraphScanParams.MultiScanId, auditParams.thirdPartyApplicabilityScan) - } - return -} - -func isEntitledForJas(xrayManager *xray.XrayServicesManager, xrayVersion string) (entitled bool, err error) { - if e := clientutils.ValidateMinimumVersion(clientutils.Xray, xrayVersion, xrayutils.EntitlementsMinVersion); e != nil { - log.Debug(e) - return - } - entitled, err = xrayManager.IsEntitled(xrayutils.ApplicabilityFeatureId) - return -} diff --git a/xray/commands/audit/auditparams.go b/xray/commands/audit/auditparams.go deleted file mode 100644 index b4130a9d4..000000000 --- a/xray/commands/audit/auditparams.go +++ /dev/null @@ -1,99 +0,0 @@ -package audit - -import ( - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/xray/services" -) - -type AuditParams struct { - xrayGraphScanParams *services.XrayGraphScanParams - workingDirs []string - exclusions []string - installFunc func(tech string) error - fixableOnly bool - minSeverityFilter string - *xrayutils.AuditBasicParams - xrayVersion string - // Include third party dependencies source code in the applicability scan. - thirdPartyApplicabilityScan bool -} - -func NewAuditParams() *AuditParams { - return &AuditParams{ - xrayGraphScanParams: &services.XrayGraphScanParams{}, - AuditBasicParams: &xrayutils.AuditBasicParams{}, - } -} - -func (params *AuditParams) InstallFunc() func(tech string) error { - return params.installFunc -} - -func (params *AuditParams) XrayGraphScanParams() *services.XrayGraphScanParams { - return params.xrayGraphScanParams -} - -func (params *AuditParams) WorkingDirs() []string { - return params.workingDirs -} - -func (params *AuditParams) XrayVersion() string { - return params.xrayVersion -} - -func (params *AuditParams) Exclusions() []string { - return params.exclusions -} - -func (params *AuditParams) SetExclusions(exclusions []string) *AuditParams { - params.exclusions = exclusions - return params -} - -func (params *AuditParams) SetXrayGraphScanParams(xrayGraphScanParams *services.XrayGraphScanParams) *AuditParams { - params.xrayGraphScanParams = xrayGraphScanParams - return params -} - -func (params *AuditParams) SetGraphBasicParams(gbp *xrayutils.AuditBasicParams) *AuditParams { - params.AuditBasicParams = gbp - return params -} - -func (params *AuditParams) SetWorkingDirs(workingDirs []string) *AuditParams { - params.workingDirs = workingDirs - return params -} - -func (params *AuditParams) SetInstallFunc(installFunc func(tech string) error) *AuditParams { - params.installFunc = installFunc - return params -} - -func (params *AuditParams) FixableOnly() bool { - return params.fixableOnly -} - -func (params *AuditParams) SetFixableOnly(fixable bool) *AuditParams { - params.fixableOnly = fixable - return params -} - -func (params *AuditParams) MinSeverityFilter() string { - return params.minSeverityFilter -} - -func (params *AuditParams) SetMinSeverityFilter(minSeverityFilter string) *AuditParams { - params.minSeverityFilter = minSeverityFilter - return params -} - -func (params *AuditParams) SetThirdPartyApplicabilityScan(includeThirdPartyDeps bool) *AuditParams { - params.thirdPartyApplicabilityScan = includeThirdPartyDeps - return params -} - -func (params *AuditParams) SetDepsRepo(depsRepo string) *AuditParams { - params.AuditBasicParams.SetDepsRepo(depsRepo) - return params -} diff --git a/xray/commands/audit/jas/applicability/applicabilitymanager.go b/xray/commands/audit/jas/applicability/applicabilitymanager.go deleted file mode 100644 index 7067963ae..000000000 --- a/xray/commands/audit/jas/applicability/applicabilitymanager.go +++ /dev/null @@ -1,195 +0,0 @@ -package applicability - -import ( - "path/filepath" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - - "github.com/jfrog/gofrog/datastructures" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/jfrog/jfrog-client-go/xray/services" - "github.com/owenrumney/go-sarif/v2/sarif" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" -) - -const ( - applicabilityScanType = "analyze-applicability" - applicabilityScanCommand = "ca" - applicabilityDocsUrlSuffix = "contextual-analysis" -) - -type ApplicabilityScanManager struct { - applicabilityScanResults []*sarif.Run - directDependenciesCves []string - indirectDependenciesCves []string - xrayResults []services.ScanResponse - scanner *jas.JasScanner - thirdPartyScan bool -} - -// The getApplicabilityScanResults function runs the applicability scan flow, which includes the following steps: -// Creating an ApplicabilityScanManager object. -// Checking if the scanned project is eligible for applicability scan. -// Running the analyzer manager executable. -// Parsing the analyzer manager results. -// Return values: -// map[string]string: A map containing the applicability result of each XRAY CVE. -// bool: true if the user is entitled to the applicability scan, false otherwise. -// error: An error object (if any). -func RunApplicabilityScan(xrayResults []services.ScanResponse, directDependencies []string, - scannedTechnologies []coreutils.Technology, scanner *jas.JasScanner, thirdPartyContextualAnalysis bool) (results []*sarif.Run, err error) { - applicabilityScanManager := newApplicabilityScanManager(xrayResults, directDependencies, scanner, thirdPartyContextualAnalysis) - if !applicabilityScanManager.shouldRunApplicabilityScan(scannedTechnologies) { - log.Debug("The technologies that have been scanned are currently not supported for contextual analysis scanning, or we couldn't find any vulnerable dependencies. Skipping....") - return - } - if err = applicabilityScanManager.scanner.Run(applicabilityScanManager); err != nil { - err = utils.ParseAnalyzerManagerError(utils.Applicability, err) - return - } - results = applicabilityScanManager.applicabilityScanResults - return -} - -func newApplicabilityScanManager(xrayScanResults []services.ScanResponse, directDependencies []string, scanner *jas.JasScanner, thirdPartyScan bool) (manager *ApplicabilityScanManager) { - directDependenciesCves, indirectDependenciesCves := extractDependenciesCvesFromScan(xrayScanResults, directDependencies) - return &ApplicabilityScanManager{ - applicabilityScanResults: []*sarif.Run{}, - directDependenciesCves: directDependenciesCves, - indirectDependenciesCves: indirectDependenciesCves, - xrayResults: xrayScanResults, - scanner: scanner, - thirdPartyScan: thirdPartyScan, - } -} - -func addCvesToSet(cves []services.Cve, set *datastructures.Set[string]) { - for _, cve := range cves { - if cve.Id != "" { - set.Add(cve.Id) - } - } -} - -// This function gets a list of xray scan responses that contain direct and indirect vulnerabilities and returns separate -// lists of the direct and indirect CVEs -func extractDependenciesCvesFromScan(xrayScanResults []services.ScanResponse, directDependencies []string) (directCves []string, indirectCves []string) { - directCvesSet := datastructures.MakeSet[string]() - indirectCvesSet := datastructures.MakeSet[string]() - for _, scanResult := range xrayScanResults { - for _, vulnerability := range scanResult.Vulnerabilities { - if isDirectComponents(maps.Keys(vulnerability.Components), directDependencies) { - addCvesToSet(vulnerability.Cves, directCvesSet) - } else { - addCvesToSet(vulnerability.Cves, indirectCvesSet) - } - } - for _, violation := range scanResult.Violations { - if isDirectComponents(maps.Keys(violation.Components), directDependencies) { - addCvesToSet(violation.Cves, directCvesSet) - } else { - addCvesToSet(violation.Cves, indirectCvesSet) - } - } - } - - return directCvesSet.ToSlice(), indirectCvesSet.ToSlice() -} - -func isDirectComponents(components []string, directDependencies []string) bool { - for _, component := range components { - if slices.Contains(directDependencies, component) { - return true - } - } - return false -} - -func (asm *ApplicabilityScanManager) Run(module jfrogappsconfig.Module) (err error) { - if jas.ShouldSkipScanner(module, utils.Applicability) { - return - } - if len(asm.scanner.JFrogAppsConfig.Modules) > 1 { - log.Info("Running applicability scanning in the", module.SourceRoot, "directory...") - } else { - log.Info("Running applicability scanning...") - } - if err = asm.createConfigFile(module); err != nil { - return - } - if err = asm.runAnalyzerManager(); err != nil { - return - } - workingDirResults, err := jas.ReadJasScanRunsFromFile(asm.scanner.ResultsFileName, module.SourceRoot, applicabilityDocsUrlSuffix) - if err != nil { - return - } - asm.applicabilityScanResults = append(asm.applicabilityScanResults, workingDirResults...) - return -} - -func (asm *ApplicabilityScanManager) shouldRunApplicabilityScan(technologies []coreutils.Technology) bool { - return asm.cvesExists() && coreutils.ContainsApplicabilityScannableTech(technologies) -} - -func (asm *ApplicabilityScanManager) cvesExists() bool { - return len(asm.indirectDependenciesCves) > 0 || len(asm.directDependenciesCves) > 0 -} - -type applicabilityScanConfig struct { - Scans []scanConfiguration `yaml:"scans"` -} - -type scanConfiguration struct { - Roots []string `yaml:"roots"` - Output string `yaml:"output"` - Type string `yaml:"type"` - GrepDisable bool `yaml:"grep-disable"` - CveWhitelist []string `yaml:"cve-whitelist"` - IndirectCveWhitelist []string `yaml:"indirect-cve-whitelist"` - SkippedDirs []string `yaml:"skipped-folders"` -} - -func (asm *ApplicabilityScanManager) createConfigFile(module jfrogappsconfig.Module) error { - roots, err := jas.GetSourceRoots(module, nil) - if err != nil { - return err - } - excludePatterns := jas.GetExcludePatterns(module, nil) - if asm.thirdPartyScan { - log.Info("Including node modules folder in applicability scan") - excludePatterns = removeElementFromSlice(excludePatterns, jas.NodeModulesPattern) - } - configFileContent := applicabilityScanConfig{ - Scans: []scanConfiguration{ - { - Roots: roots, - Output: asm.scanner.ResultsFileName, - Type: applicabilityScanType, - GrepDisable: false, - CveWhitelist: asm.directDependenciesCves, - IndirectCveWhitelist: asm.indirectDependenciesCves, - SkippedDirs: excludePatterns, - }, - }, - } - return jas.CreateScannersConfigFile(asm.scanner.ConfigFileName, configFileContent, utils.Applicability) -} - -// Runs the analyzerManager app and returns a boolean to indicate whether the user is entitled for -// advance security feature -func (asm *ApplicabilityScanManager) runAnalyzerManager() error { - return asm.scanner.AnalyzerManager.Exec(asm.scanner.ConfigFileName, applicabilityScanCommand, filepath.Dir(asm.scanner.AnalyzerManager.AnalyzerManagerFullPath), asm.scanner.ServerDetails) -} - -func removeElementFromSlice(skipDirs []string, element string) []string { - deleteIndex := slices.Index(skipDirs, element) - if deleteIndex == -1 { - return skipDirs - } - return slices.Delete(skipDirs, deleteIndex, deleteIndex+1) -} diff --git a/xray/commands/audit/jas/applicability/applicabilitymanager_test.go b/xray/commands/audit/jas/applicability/applicabilitymanager_test.go deleted file mode 100644 index 78f2e239d..000000000 --- a/xray/commands/audit/jas/applicability/applicabilitymanager_test.go +++ /dev/null @@ -1,336 +0,0 @@ -package applicability - -import ( - "os" - "path/filepath" - "testing" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - "github.com/jfrog/jfrog-client-go/xray/services" - "github.com/stretchr/testify/assert" -) - -var mockDirectDependencies = []string{"issueId_2_direct_dependency", "issueId_1_direct_dependency"} -var mockMultiRootDirectDependencies = []string{"issueId_2_direct_dependency", "issueId_1_direct_dependency", "issueId_3_direct_dependency", "issueId_4_direct_dependency"} - -func TestNewApplicabilityScanManager_InputIsValid(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - // Act - applicabilityManager := newApplicabilityScanManager(jas.FakeBasicXrayResults, mockDirectDependencies, scanner, false) - - // Assert - if assert.NotNil(t, applicabilityManager) { - assert.NotEmpty(t, applicabilityManager.scanner.ConfigFileName) - assert.NotEmpty(t, applicabilityManager.scanner.ResultsFileName) - assert.Len(t, applicabilityManager.directDependenciesCves, 5) - } -} - -func TestNewApplicabilityScanManager_DependencyTreeDoesntExist(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - // Act - applicabilityManager := newApplicabilityScanManager(jas.FakeBasicXrayResults, nil, scanner, false) - - // Assert - if assert.NotNil(t, applicabilityManager) { - assert.NotNil(t, applicabilityManager.scanner.ScannerDirCleanupFunc) - assert.Len(t, applicabilityManager.scanner.JFrogAppsConfig.Modules, 1) - assert.NotEmpty(t, applicabilityManager.scanner.ConfigFileName) - assert.NotEmpty(t, applicabilityManager.scanner.ResultsFileName) - assert.Empty(t, applicabilityManager.directDependenciesCves) - } -} - -func TestNewApplicabilityScanManager_NoDirectDependenciesInScan(t *testing.T) { - // Arrange - var noDirectDependenciesResults = []services.ScanResponse{ - { - ScanId: "scanId_1", - Vulnerabilities: []services.Vulnerability{ - {IssueId: "issueId_1", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "testCve1"}, {Id: "testCve2"}, {Id: "testCve3"}}, - Components: map[string]services.Component{ - "issueId_1_non_direct_dependency": {}}}, - }, - Violations: []services.Violation{ - {IssueId: "issueId_2", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "testCve4"}, {Id: "testCve5"}}, - Components: map[string]services.Component{ - "issueId_2_non_direct_dependency": {}}}, - }, - }, - } - jas.FakeBasicXrayResults[0].Vulnerabilities[0].Components["issueId_1_non_direct_dependency"] = services.Component{} - jas.FakeBasicXrayResults[0].Violations[0].Components["issueId_2_non_direct_dependency"] = services.Component{} - - // Act - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - applicabilityManager := newApplicabilityScanManager(noDirectDependenciesResults, mockDirectDependencies, scanner, false) - assertApplicabilityScanner(t, applicabilityManager) - // ThirdPartyContextual shouldn't change anything here as this is not npm. - applicabilityManager = newApplicabilityScanManager(noDirectDependenciesResults, mockDirectDependencies, scanner, true) - assertApplicabilityScanner(t, applicabilityManager) -} - -func assertApplicabilityScanner(t *testing.T, applicabilityManager *ApplicabilityScanManager) { - if assert.NotNil(t, applicabilityManager) { - assert.NotEmpty(t, applicabilityManager.scanner.ConfigFileName) - assert.NotEmpty(t, applicabilityManager.scanner.ResultsFileName) - // Non-direct dependencies should not be added - assert.Empty(t, applicabilityManager.directDependenciesCves) - } -} - -func TestNewApplicabilityScanManager_MultipleDependencyTrees(t *testing.T) { - // Arrange - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - // Act - applicabilityManager := newApplicabilityScanManager(jas.FakeBasicXrayResults, mockMultiRootDirectDependencies, scanner, false) - - // Assert - if assert.NotNil(t, applicabilityManager) { - assert.NotEmpty(t, applicabilityManager.scanner.ConfigFileName) - assert.NotEmpty(t, applicabilityManager.scanner.ResultsFileName) - assert.Len(t, applicabilityManager.directDependenciesCves, 5) - } -} - -func TestNewApplicabilityScanManager_ViolationsDontExistInResults(t *testing.T) { - // Arrange - noViolationScanResponse := []services.ScanResponse{ - { - ScanId: "scanId_1", - Vulnerabilities: []services.Vulnerability{ - {IssueId: "issueId_1", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "test_cve_1"}, {Id: "test_cve_2"}, {Id: "test_cve_3"}}, - Components: map[string]services.Component{"issueId_1_direct_dependency": {}}}, - }, - }, - } - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - // Act - applicabilityManager := newApplicabilityScanManager(noViolationScanResponse, mockDirectDependencies, scanner, false) - - // Assert - if assert.NotNil(t, applicabilityManager) { - assert.NotEmpty(t, applicabilityManager.scanner.ConfigFileName) - assert.NotEmpty(t, applicabilityManager.scanner.ResultsFileName) - assert.Len(t, applicabilityManager.directDependenciesCves, 3) - } -} - -func TestNewApplicabilityScanManager_VulnerabilitiesDontExist(t *testing.T) { - // Arrange - noVulnerabilitiesScanResponse := []services.ScanResponse{ - { - ScanId: "scanId_1", - Violations: []services.Violation{ - {IssueId: "issueId_2", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "test_cve_3"}, {Id: "test_cve_4"}}, - Components: map[string]services.Component{"issueId_2_direct_dependency": {}}}, - }, - }, - } - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - // Act - applicabilityManager := newApplicabilityScanManager(noVulnerabilitiesScanResponse, mockDirectDependencies, scanner, false) - - // Assert - if assert.NotNil(t, applicabilityManager) { - assert.NotEmpty(t, applicabilityManager.scanner.ConfigFileName) - assert.NotEmpty(t, applicabilityManager.scanner.ResultsFileName) - assert.Len(t, applicabilityManager.directDependenciesCves, 2) - } -} - -func TestApplicabilityScanManager_ShouldRun_TechnologiesNotEligibleForScan(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - results, err := RunApplicabilityScan(jas.FakeBasicXrayResults, mockDirectDependencies, []coreutils.Technology{coreutils.Nuget, coreutils.Go}, scanner, false) - - // Assert - assert.Nil(t, results) - assert.NoError(t, err) -} - -func TestApplicabilityScanManager_ShouldRun_ScanResultsAreEmpty(t *testing.T) { - // Arrange - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - applicabilityManager := newApplicabilityScanManager(nil, mockDirectDependencies, scanner, false) - - // Assert - eligible := applicabilityManager.shouldRunApplicabilityScan([]coreutils.Technology{coreutils.Nuget}) - assert.False(t, eligible) -} - -func TestExtractXrayDirectViolations(t *testing.T) { - var xrayResponseForDirectViolationsTest = []services.ScanResponse{ - { - Violations: []services.Violation{ - {IssueId: "issueId_2", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "testCve4"}, {Id: "testCve5"}}, - Components: map[string]services.Component{"issueId_2_direct_dependency": {}}}, - }, - }, - } - tests := []struct { - directDependencies []string - directCvesCount int - indirectCvesCount int - }{ - {directDependencies: []string{"issueId_2_direct_dependency", "issueId_1_direct_dependency"}, - directCvesCount: 2, - indirectCvesCount: 0, - }, - // Vulnerability dependency, should be ignored by function - {directDependencies: []string{"issueId_1_direct_dependency"}, - directCvesCount: 0, - indirectCvesCount: 2, - }, - {directDependencies: []string{}, - directCvesCount: 0, - indirectCvesCount: 2, - }, - } - - for _, test := range tests { - directCves, indirectCves := extractDependenciesCvesFromScan(xrayResponseForDirectViolationsTest, test.directDependencies) - assert.Len(t, directCves, test.directCvesCount) - assert.Len(t, indirectCves, test.indirectCvesCount) - } -} - -func TestExtractXrayDirectVulnerabilities(t *testing.T) { - var xrayResponseForDirectVulnerabilitiesTest = []services.ScanResponse{ - { - ScanId: "scanId_1", - Vulnerabilities: []services.Vulnerability{ - { - IssueId: "issueId_1", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "testCve1"}, {Id: "testCve2"}, {Id: "testCve3"}}, - Components: map[string]services.Component{"issueId_1_direct_dependency": {}}, - }, - { - IssueId: "issueId_2", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "testCve4"}, {Id: "testCve5"}}, - Components: map[string]services.Component{"issueId_2_direct_dependency": {}}, - }, - }, - }, - } - tests := []struct { - directDependencies []string - directCvesCount int - indirectCvesCount int - }{ - { - directDependencies: []string{"issueId_1_direct_dependency"}, - directCvesCount: 3, - indirectCvesCount: 2, - }, - { - directDependencies: []string{"issueId_2_direct_dependency"}, - directCvesCount: 2, - indirectCvesCount: 3, - }, - {directDependencies: []string{}, - directCvesCount: 0, - indirectCvesCount: 5, - }, - } - - for _, test := range tests { - directCves, indirectCves := extractDependenciesCvesFromScan(xrayResponseForDirectVulnerabilitiesTest, test.directDependencies) - assert.Len(t, directCves, test.directCvesCount) - assert.Len(t, indirectCves, test.indirectCvesCount) - } -} - -func TestCreateConfigFile_VerifyFileWasCreated(t *testing.T) { - // Arrange - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - applicabilityManager := newApplicabilityScanManager(jas.FakeBasicXrayResults, []string{"issueId_1_direct_dependency", "issueId_2_direct_dependency"}, scanner, false) - - currWd, err := coreutils.GetWorkingDirectory() - assert.NoError(t, err) - err = applicabilityManager.createConfigFile(jfrogappsconfig.Module{SourceRoot: currWd}) - assert.NoError(t, err) - - defer func() { - err = os.Remove(applicabilityManager.scanner.ConfigFileName) - assert.NoError(t, err) - }() - - _, fileNotExistError := os.Stat(applicabilityManager.scanner.ConfigFileName) - assert.NoError(t, fileNotExistError) - fileContent, err := os.ReadFile(applicabilityManager.scanner.ConfigFileName) - assert.NoError(t, err) - assert.True(t, len(fileContent) > 0) -} - -func TestParseResults_EmptyResults_AllCvesShouldGetUnknown(t *testing.T) { - // Arrange - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - applicabilityManager := newApplicabilityScanManager(jas.FakeBasicXrayResults, mockDirectDependencies, scanner, false) - applicabilityManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "applicability-scan", "empty-results.sarif") - - // Act - var err error - applicabilityManager.applicabilityScanResults, err = jas.ReadJasScanRunsFromFile(applicabilityManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, applicabilityDocsUrlSuffix) - - if assert.NoError(t, err) { - assert.Len(t, applicabilityManager.applicabilityScanResults, 1) - assert.Empty(t, applicabilityManager.applicabilityScanResults[0].Results) - } -} - -func TestParseResults_ApplicableCveExist(t *testing.T) { - // Arrange - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - applicabilityManager := newApplicabilityScanManager(jas.FakeBasicXrayResults, mockDirectDependencies, scanner, false) - applicabilityManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "applicability-scan", "applicable-cve-results.sarif") - - // Act - var err error - applicabilityManager.applicabilityScanResults, err = jas.ReadJasScanRunsFromFile(applicabilityManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, applicabilityDocsUrlSuffix) - - if assert.NoError(t, err) && assert.NotNil(t, applicabilityManager.applicabilityScanResults) { - assert.Len(t, applicabilityManager.applicabilityScanResults, 1) - assert.NotEmpty(t, applicabilityManager.applicabilityScanResults[0].Results) - } -} - -func TestParseResults_AllCvesNotApplicable(t *testing.T) { - // Arrange - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - applicabilityManager := newApplicabilityScanManager(jas.FakeBasicXrayResults, mockDirectDependencies, scanner, false) - applicabilityManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "applicability-scan", "no-applicable-cves-results.sarif") - - // Act - var err error - applicabilityManager.applicabilityScanResults, err = jas.ReadJasScanRunsFromFile(applicabilityManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, applicabilityDocsUrlSuffix) - - if assert.NoError(t, err) && assert.NotNil(t, applicabilityManager.applicabilityScanResults) { - assert.Len(t, applicabilityManager.applicabilityScanResults, 1) - assert.NotEmpty(t, applicabilityManager.applicabilityScanResults[0].Results) - } -} diff --git a/xray/commands/audit/jas/common.go b/xray/commands/audit/jas/common.go deleted file mode 100644 index 3c4adf31a..000000000 --- a/xray/commands/audit/jas/common.go +++ /dev/null @@ -1,278 +0,0 @@ -package jas - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "strings" - "testing" - "unicode" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/dependencies" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/jfrog/jfrog-client-go/xray/services" - "github.com/owenrumney/go-sarif/v2/sarif" - "github.com/stretchr/testify/assert" - "golang.org/x/exp/slices" - "gopkg.in/yaml.v3" -) - -const ( - NodeModulesPattern = "**/*node_modules*/**" -) - -var ( - DefaultExcludePatterns = []string{"**/.git/**", "**/*test*/**", "**/*venv*/**", NodeModulesPattern, "**/target/**"} - - mapSeverityToScore = map[string]string{ - "": "0.0", - "unknown": "0.0", - "low": "3.9", - "medium": "6.9", - "high": "8.9", - "critical": "10", - } -) - -type JasScanner struct { - ConfigFileName string - ResultsFileName string - AnalyzerManager utils.AnalyzerManager - ServerDetails *config.ServerDetails - JFrogAppsConfig *jfrogappsconfig.JFrogAppsConfig - ScannerDirCleanupFunc func() error -} - -func NewJasScanner(workingDirs []string, serverDetails *config.ServerDetails, multiScanId string) (scanner *JasScanner, err error) { - scanner = &JasScanner{} - if scanner.AnalyzerManager.AnalyzerManagerFullPath, err = utils.GetAnalyzerManagerExecutable(); err != nil { - return - } - var tempDir string - if tempDir, err = fileutils.CreateTempDir(); err != nil { - return - } - scanner.ScannerDirCleanupFunc = func() error { - return fileutils.RemoveTempDir(tempDir) - } - scanner.ServerDetails = serverDetails - scanner.ConfigFileName = filepath.Join(tempDir, "config.yaml") - scanner.ResultsFileName = filepath.Join(tempDir, "results.sarif") - scanner.JFrogAppsConfig, err = createJFrogAppsConfig(workingDirs) - scanner.AnalyzerManager.MultiScanId = multiScanId - return -} - -func createJFrogAppsConfig(workingDirs []string) (*jfrogappsconfig.JFrogAppsConfig, error) { - if jfrogAppsConfig, err := jfrogappsconfig.LoadConfigIfExist(); err != nil { - return nil, errorutils.CheckError(err) - } else if jfrogAppsConfig != nil { - // jfrog-apps-config.yml exist in the workspace - return jfrogAppsConfig, nil - } - - // jfrog-apps-config.yml does not exist in the workspace - fullPathsWorkingDirs, err := coreutils.GetFullPathsWorkingDirs(workingDirs) - if err != nil { - return nil, err - } - jfrogAppsConfig := new(jfrogappsconfig.JFrogAppsConfig) - for _, workingDir := range fullPathsWorkingDirs { - jfrogAppsConfig.Modules = append(jfrogAppsConfig.Modules, jfrogappsconfig.Module{SourceRoot: workingDir}) - } - return jfrogAppsConfig, nil -} - -type ScannerCmd interface { - Run(module jfrogappsconfig.Module) (err error) -} - -func (a *JasScanner) Run(scannerCmd ScannerCmd) (err error) { - for _, module := range a.JFrogAppsConfig.Modules { - func() { - defer func() { - err = errors.Join(err, deleteJasProcessFiles(a.ConfigFileName, a.ResultsFileName)) - }() - if err = scannerCmd.Run(module); err != nil { - return - } - }() - } - return -} - -func deleteJasProcessFiles(configFile string, resultFile string) error { - exist, err := fileutils.IsFileExists(configFile, false) - if err != nil { - return err - } - if exist { - if err = os.Remove(configFile); err != nil { - return errorutils.CheckError(err) - } - } - exist, err = fileutils.IsFileExists(resultFile, false) - if err != nil { - return err - } - if exist { - err = os.Remove(resultFile) - } - return errorutils.CheckError(err) -} - -func ReadJasScanRunsFromFile(fileName, wd, informationUrlSuffix string) (sarifRuns []*sarif.Run, err error) { - if sarifRuns, err = utils.ReadScanRunsFromFile(fileName); err != nil { - return - } - for _, sarifRun := range sarifRuns { - // Jas reports has only one invocation - // Set the actual working directory to the invocation, not the analyzerManager directory - // Also used to calculate relative paths if needed with it - sarifRun.Invocations[0].WorkingDirectory.WithUri(wd) - // Process runs values - fillMissingRequiredDriverInformation(utils.BaseDocumentationURL+informationUrlSuffix, utils.GetAnalyzerManagerVersion(), sarifRun) - sarifRun.Results = excludeSuppressResults(sarifRun.Results) - addScoreToRunRules(sarifRun) - } - return -} - -func fillMissingRequiredDriverInformation(defaultJasInformationUri, defaultVersion string, run *sarif.Run) { - driver := run.Tool.Driver - if driver.InformationURI == nil { - driver.InformationURI = &defaultJasInformationUri - } - if driver.Version == nil || !isValidVersion(*driver.Version) { - driver.Version = &defaultVersion - } -} - -func isValidVersion(version string) bool { - if len(version) == 0 { - return false - } - firstChar := rune(version[0]) - return unicode.IsDigit(firstChar) -} - -func excludeSuppressResults(sarifResults []*sarif.Result) []*sarif.Result { - results := []*sarif.Result{} - for _, sarifResult := range sarifResults { - if len(sarifResult.Suppressions) > 0 { - // Describes a request to “suppress” a result (to exclude it from result lists) - continue - } - results = append(results, sarifResult) - } - return results -} - -func addScoreToRunRules(sarifRun *sarif.Run) { - for _, sarifResult := range sarifRun.Results { - if rule, err := sarifRun.GetRuleById(*sarifResult.RuleID); err == nil { - // Add to the rule security-severity score based on results severity - score := convertToScore(utils.GetResultSeverity(sarifResult)) - if score != utils.MissingCveScore { - if rule.Properties == nil { - rule.WithProperties(sarif.NewPropertyBag().Properties) - } - rule.Properties["security-severity"] = score - } - } - } -} - -func convertToScore(severity string) string { - if level, ok := mapSeverityToScore[strings.ToLower(severity)]; ok { - return level - } - return "" -} - -func CreateScannersConfigFile(fileName string, fileContent interface{}, scanType utils.JasScanType) error { - yamlData, err := yaml.Marshal(&fileContent) - if errorutils.CheckError(err) != nil { - return err - } - log.Debug(scanType.String() + " scanner input YAML:\n" + string(yamlData)) - err = os.WriteFile(fileName, yamlData, 0644) - return errorutils.CheckError(err) -} - -var FakeServerDetails = config.ServerDetails{ - Url: "platformUrl", - Password: "password", - User: "user", -} - -var FakeBasicXrayResults = []services.ScanResponse{ - { - ScanId: "scanId_1", - Vulnerabilities: []services.Vulnerability{ - {IssueId: "issueId_1", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "testCve1"}, {Id: "testCve2"}, {Id: "testCve3"}}, - Components: map[string]services.Component{"issueId_1_direct_dependency": {}, "issueId_3_direct_dependency": {}}}, - }, - Violations: []services.Violation{ - {IssueId: "issueId_2", Technology: coreutils.Pipenv.String(), - Cves: []services.Cve{{Id: "testCve4"}, {Id: "testCve5"}}, - Components: map[string]services.Component{"issueId_2_direct_dependency": {}, "issueId_4_direct_dependency": {}}}, - }, - }, -} - -func InitJasTest(t *testing.T, workingDirs ...string) (*JasScanner, func()) { - assert.NoError(t, dependencies.DownloadAnalyzerManagerIfNeeded()) - scanner, err := NewJasScanner(workingDirs, &FakeServerDetails, "") - assert.NoError(t, err) - return scanner, func() { - assert.NoError(t, scanner.ScannerDirCleanupFunc()) - } -} - -func GetTestDataPath() string { - return filepath.Join("..", "..", "..", "testdata") -} - -func ShouldSkipScanner(module jfrogappsconfig.Module, scanType utils.JasScanType) bool { - lowerScanType := strings.ToLower(string(scanType)) - if slices.Contains(module.ExcludeScanners, lowerScanType) { - log.Info(fmt.Sprintf("Skipping %s scanning", scanType)) - return true - } - return false -} - -func GetSourceRoots(module jfrogappsconfig.Module, scanner *jfrogappsconfig.Scanner) ([]string, error) { - root, err := filepath.Abs(module.SourceRoot) - if err != nil { - return []string{}, errorutils.CheckError(err) - } - if scanner == nil || len(scanner.WorkingDirs) == 0 { - return []string{root}, errorutils.CheckError(err) - } - var roots []string - for _, workingDir := range scanner.WorkingDirs { - roots = append(roots, filepath.Join(root, workingDir)) - } - return roots, nil -} - -func GetExcludePatterns(module jfrogappsconfig.Module, scanner *jfrogappsconfig.Scanner) []string { - excludePatterns := module.ExcludePatterns - if scanner != nil { - excludePatterns = append(excludePatterns, scanner.ExcludePatterns...) - } - if len(excludePatterns) == 0 { - return DefaultExcludePatterns - } - return excludePatterns -} diff --git a/xray/commands/audit/jas/common_test.go b/xray/commands/audit/jas/common_test.go deleted file mode 100644 index 5466039d8..000000000 --- a/xray/commands/audit/jas/common_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package jas - -import ( - "testing" - - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/owenrumney/go-sarif/v2/sarif" - "github.com/stretchr/testify/assert" -) - -func TestExcludeSuppressResults(t *testing.T) { - tests := []struct { - name string - sarifResults []*sarif.Result - expectedOutput []*sarif.Result - }{ - { - sarifResults: []*sarif.Result{ - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet1", "ruleId1", "level1"), - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet2", "ruleId2", "level2"), - }, - expectedOutput: []*sarif.Result{ - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet1", "ruleId1", "level1"), - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet2", "ruleId2", "level2"), - }, - }, - { - sarifResults: []*sarif.Result{ - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet1", "ruleId1", "level1").WithSuppression([]*sarif.Suppression{sarif.NewSuppression("")}), - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet2", "ruleId2", "level2"), - }, - expectedOutput: []*sarif.Result{ - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet2", "ruleId2", "level2"), - }, - }, - { - sarifResults: []*sarif.Result{ - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet1", "ruleId1", "level1").WithSuppression([]*sarif.Suppression{sarif.NewSuppression("")}), - utils.CreateResultWithOneLocation("", 0, 0, 0, 0, "snippet2", "ruleId2", "level2").WithSuppression([]*sarif.Suppression{sarif.NewSuppression("")}), - }, - expectedOutput: []*sarif.Result{}, - }, - } - - for _, test := range tests { - assert.Equal(t, test.expectedOutput, excludeSuppressResults(test.sarifResults)) - } -} - -func TestAddScoreToRunRules(t *testing.T) { - - tests := []struct { - name string - sarifRun *sarif.Run - expectedOutput []*sarif.ReportingDescriptor - }{ - { - sarifRun: utils.CreateRunWithDummyResults( - utils.CreateResultWithOneLocation("file1", 0, 0, 0, 0, "snippet", "rule1", "info"), - utils.CreateResultWithOneLocation("file2", 0, 0, 0, 0, "snippet", "rule1", "info"), - utils.CreateResultWithOneLocation("file", 0, 0, 0, 0, "snippet", "rule2", "warning"), - ), - expectedOutput: []*sarif.ReportingDescriptor{ - sarif.NewRule("rule1").WithProperties(sarif.Properties{"security-severity": "6.9"}), - sarif.NewRule("rule2").WithProperties(sarif.Properties{"security-severity": "6.9"}), - }, - }, - { - sarifRun: utils.CreateRunWithDummyResults( - utils.CreateResultWithOneLocation("file", 0, 0, 0, 0, "snippet", "rule1", "none"), - utils.CreateResultWithOneLocation("file", 0, 0, 0, 0, "snippet", "rule2", "note"), - utils.CreateResultWithOneLocation("file", 0, 0, 0, 0, "snippet", "rule3", "info"), - utils.CreateResultWithOneLocation("file", 0, 0, 0, 0, "snippet", "rule4", "warning"), - utils.CreateResultWithOneLocation("file", 0, 0, 0, 0, "snippet", "rule5", "error"), - ), - expectedOutput: []*sarif.ReportingDescriptor{ - sarif.NewRule("rule1").WithProperties(sarif.Properties{"security-severity": "0.0"}), - sarif.NewRule("rule2").WithProperties(sarif.Properties{"security-severity": "3.9"}), - sarif.NewRule("rule3").WithProperties(sarif.Properties{"security-severity": "6.9"}), - sarif.NewRule("rule4").WithProperties(sarif.Properties{"security-severity": "6.9"}), - sarif.NewRule("rule5").WithProperties(sarif.Properties{"security-severity": "8.9"}), - }, - }, - } - - for _, test := range tests { - addScoreToRunRules(test.sarifRun) - assert.Equal(t, test.expectedOutput, test.sarifRun.Tool.Driver.Rules) - } -} diff --git a/xray/commands/audit/jas/commons_test.go b/xray/commands/audit/jas/commons_test.go deleted file mode 100644 index c43cf94ab..000000000 --- a/xray/commands/audit/jas/commons_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package jas - -import ( - "fmt" - "os" - "path/filepath" - "testing" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - clientTestUtils "github.com/jfrog/jfrog-client-go/utils/tests" - - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/stretchr/testify/assert" -) - -var createJFrogAppsConfigCases = []struct { - workingDirs []string -}{ - {workingDirs: []string{}}, - {workingDirs: []string{"working-dir"}}, - {workingDirs: []string{"working-dir-1", "working-dir-2"}}, -} - -func TestCreateJFrogAppsConfig(t *testing.T) { - wd, err := os.Getwd() - assert.NoError(t, err) - - for _, testCase := range createJFrogAppsConfigCases { - t.Run(fmt.Sprintf("%v", testCase.workingDirs), func(t *testing.T) { - jfrogAppsConfig, err := createJFrogAppsConfig(testCase.workingDirs) - assert.NoError(t, err) - assert.NotNil(t, jfrogAppsConfig) - if len(testCase.workingDirs) == 0 { - assert.Len(t, jfrogAppsConfig.Modules, 1) - assert.Equal(t, wd, jfrogAppsConfig.Modules[0].SourceRoot) - return - } - assert.Len(t, jfrogAppsConfig.Modules, len(testCase.workingDirs)) - for i, workingDir := range testCase.workingDirs { - assert.Equal(t, filepath.Join(wd, workingDir), jfrogAppsConfig.Modules[i].SourceRoot) - } - }) - } -} - -func TestCreateJFrogAppsConfigWithConfig(t *testing.T) { - wd, err := os.Getwd() - assert.NoError(t, err) - chdirCallback := clientTestUtils.ChangeDirWithCallback(t, wd, "testdata") - defer chdirCallback() - - jfrogAppsConfig, err := createJFrogAppsConfig([]string{}) - assert.NoError(t, err) - assert.NotNil(t, jfrogAppsConfig) - assert.Equal(t, "1.0", jfrogAppsConfig.Version) - assert.Len(t, jfrogAppsConfig.Modules, 1) -} - -func TestShouldSkipScanner(t *testing.T) { - module := jfrogappsconfig.Module{} - assert.False(t, ShouldSkipScanner(module, utils.IaC)) - - module = jfrogappsconfig.Module{ExcludeScanners: []string{"sast"}} - assert.False(t, ShouldSkipScanner(module, utils.IaC)) - assert.True(t, ShouldSkipScanner(module, utils.Sast)) -} - -var getSourceRootsCases = []struct { - scanner *jfrogappsconfig.Scanner -}{ - {scanner: nil}, - {&jfrogappsconfig.Scanner{WorkingDirs: []string{"working-dir"}}}, - {&jfrogappsconfig.Scanner{WorkingDirs: []string{"working-dir-1", "working-dir-2"}}}, -} - -func TestGetSourceRoots(t *testing.T) { - testGetSourceRoots(t, "source-root") -} - -func TestGetSourceRootsEmptySourceRoot(t *testing.T) { - testGetSourceRoots(t, "") -} - -func testGetSourceRoots(t *testing.T, sourceRoot string) { - sourceRoot, err := filepath.Abs(sourceRoot) - assert.NoError(t, err) - module := jfrogappsconfig.Module{SourceRoot: sourceRoot} - for _, testCase := range getSourceRootsCases { - t.Run("", func(t *testing.T) { - scanner := testCase.scanner - actualSourceRoots, err := GetSourceRoots(module, scanner) - assert.NoError(t, err) - if scanner == nil { - assert.ElementsMatch(t, []string{module.SourceRoot}, actualSourceRoots) - return - } - expectedWorkingDirs := []string{} - for _, workingDir := range scanner.WorkingDirs { - expectedWorkingDirs = append(expectedWorkingDirs, filepath.Join(module.SourceRoot, workingDir)) - } - assert.ElementsMatch(t, actualSourceRoots, expectedWorkingDirs) - }) - } -} - -var getExcludePatternsCases = []struct { - scanner *jfrogappsconfig.Scanner -}{ - {scanner: nil}, - {&jfrogappsconfig.Scanner{WorkingDirs: []string{"exclude-dir"}}}, - {&jfrogappsconfig.Scanner{WorkingDirs: []string{"exclude-dir-1", "exclude-dir-2"}}}, -} - -func TestGetExcludePatterns(t *testing.T) { - module := jfrogappsconfig.Module{ExcludePatterns: []string{"exclude-root"}} - for _, testCase := range getExcludePatternsCases { - t.Run("", func(t *testing.T) { - scanner := testCase.scanner - actualExcludePatterns := GetExcludePatterns(module, scanner) - if scanner == nil { - assert.ElementsMatch(t, module.ExcludePatterns, actualExcludePatterns) - return - } - expectedExcludePatterns := module.ExcludePatterns - expectedExcludePatterns = append(expectedExcludePatterns, scanner.ExcludePatterns...) - assert.ElementsMatch(t, actualExcludePatterns, expectedExcludePatterns) - }) - } -} diff --git a/xray/commands/audit/jas/iac/iacscanner.go b/xray/commands/audit/jas/iac/iacscanner.go deleted file mode 100644 index 402557e3e..000000000 --- a/xray/commands/audit/jas/iac/iacscanner.go +++ /dev/null @@ -1,103 +0,0 @@ -package iac - -import ( - "path/filepath" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/owenrumney/go-sarif/v2/sarif" -) - -const ( - iacScannerType = "iac-scan-modules" - iacScanCommand = "iac" - iacDocsUrlSuffix = "infrastructure-as-code-iac" -) - -type IacScanManager struct { - iacScannerResults []*sarif.Run - scanner *jas.JasScanner -} - -// The getIacScanResults function runs the iac scan flow, which includes the following steps: -// Creating an IacScanManager object. -// Running the analyzer manager executable. -// Parsing the analyzer manager results. -// Return values: -// []utils.SourceCodeScanResult: a list of the iac violations that were found. -// bool: true if the user is entitled to iac scan, false otherwise. -// error: An error object (if any). -func RunIacScan(scanner *jas.JasScanner) (results []*sarif.Run, err error) { - iacScanManager := newIacScanManager(scanner) - log.Info("Running IaC scanning...") - if err = iacScanManager.scanner.Run(iacScanManager); err != nil { - err = utils.ParseAnalyzerManagerError(utils.IaC, err) - return - } - if len(iacScanManager.iacScannerResults) > 0 { - log.Info("Found", utils.GetResultsLocationCount(iacScanManager.iacScannerResults...), "IaC vulnerabilities") - } - results = iacScanManager.iacScannerResults - return -} - -func newIacScanManager(scanner *jas.JasScanner) (manager *IacScanManager) { - return &IacScanManager{ - iacScannerResults: []*sarif.Run{}, - scanner: scanner, - } -} - -func (iac *IacScanManager) Run(module jfrogappsconfig.Module) (err error) { - if jas.ShouldSkipScanner(module, utils.IaC) { - return - } - if err = iac.createConfigFile(module); err != nil { - return - } - if err = iac.runAnalyzerManager(); err != nil { - return - } - workingDirResults, err := jas.ReadJasScanRunsFromFile(iac.scanner.ResultsFileName, module.SourceRoot, iacDocsUrlSuffix) - if err != nil { - return - } - iac.iacScannerResults = append(iac.iacScannerResults, workingDirResults...) - return -} - -type iacScanConfig struct { - Scans []iacScanConfiguration `yaml:"scans"` -} - -type iacScanConfiguration struct { - Roots []string `yaml:"roots"` - Output string `yaml:"output"` - Type string `yaml:"type"` - SkippedDirs []string `yaml:"skipped-folders"` -} - -func (iac *IacScanManager) createConfigFile(module jfrogappsconfig.Module) error { - roots, err := jas.GetSourceRoots(module, module.Scanners.Iac) - if err != nil { - return err - } - configFileContent := iacScanConfig{ - Scans: []iacScanConfiguration{ - { - Roots: roots, - Output: iac.scanner.ResultsFileName, - Type: iacScannerType, - SkippedDirs: jas.GetExcludePatterns(module, module.Scanners.Iac), - }, - }, - } - return jas.CreateScannersConfigFile(iac.scanner.ConfigFileName, configFileContent, utils.IaC) -} - -func (iac *IacScanManager) runAnalyzerManager() error { - return iac.scanner.AnalyzerManager.Exec(iac.scanner.ConfigFileName, iacScanCommand, filepath.Dir(iac.scanner.AnalyzerManager.AnalyzerManagerFullPath), iac.scanner.ServerDetails) -} diff --git a/xray/commands/audit/jas/iac/iacscanner_test.go b/xray/commands/audit/jas/iac/iacscanner_test.go deleted file mode 100644 index 1f9482ded..000000000 --- a/xray/commands/audit/jas/iac/iacscanner_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package iac - -import ( - "os" - "path/filepath" - "testing" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/stretchr/testify/assert" -) - -func TestNewIacScanManager(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t, "currentDir") - defer cleanUp() - // Act - iacScanManager := newIacScanManager(scanner) - - // Assert - if assert.NotNil(t, iacScanManager) { - assert.NotEmpty(t, iacScanManager.scanner.ConfigFileName) - assert.NotEmpty(t, iacScanManager.scanner.ResultsFileName) - assert.NotEmpty(t, iacScanManager.scanner.JFrogAppsConfig.Modules[0].SourceRoot) - assert.Equal(t, &jas.FakeServerDetails, iacScanManager.scanner.ServerDetails) - } -} - -func TestIacScan_CreateConfigFile_VerifyFileWasCreated(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t, "currentDir") - defer cleanUp() - - iacScanManager := newIacScanManager(scanner) - - currWd, err := coreutils.GetWorkingDirectory() - assert.NoError(t, err) - err = iacScanManager.createConfigFile(jfrogappsconfig.Module{SourceRoot: currWd}) - - defer func() { - err = os.Remove(iacScanManager.scanner.ConfigFileName) - assert.NoError(t, err) - }() - - _, fileNotExistError := os.Stat(iacScanManager.scanner.ConfigFileName) - assert.NoError(t, fileNotExistError) - fileContent, err := os.ReadFile(iacScanManager.scanner.ConfigFileName) - assert.NoError(t, err) - assert.True(t, len(fileContent) > 0) -} - -func TestIacParseResults_EmptyResults(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - // Arrange - iacScanManager := newIacScanManager(scanner) - iacScanManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "iac-scan", "no-violations.sarif") - - // Act - var err error - iacScanManager.iacScannerResults, err = jas.ReadJasScanRunsFromFile(iacScanManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, iacDocsUrlSuffix) - if assert.NoError(t, err) && assert.NotNil(t, iacScanManager.iacScannerResults) { - assert.Len(t, iacScanManager.iacScannerResults, 1) - assert.Empty(t, iacScanManager.iacScannerResults[0].Results) - } -} - -func TestIacParseResults_ResultsContainIacViolations(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - // Arrange - iacScanManager := newIacScanManager(scanner) - iacScanManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "iac-scan", "contains-iac-violations.sarif") - - // Act - var err error - iacScanManager.iacScannerResults, err = jas.ReadJasScanRunsFromFile(iacScanManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, iacDocsUrlSuffix) - if assert.NoError(t, err) && assert.NotNil(t, iacScanManager.iacScannerResults) { - assert.Len(t, iacScanManager.iacScannerResults, 1) - assert.Len(t, iacScanManager.iacScannerResults[0].Results, 4) - } -} diff --git a/xray/commands/audit/jas/sast/sastscanner.go b/xray/commands/audit/jas/sast/sastscanner.go deleted file mode 100644 index 578bc6775..000000000 --- a/xray/commands/audit/jas/sast/sastscanner.go +++ /dev/null @@ -1,147 +0,0 @@ -package sast - -import ( - "fmt" - - "path/filepath" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/owenrumney/go-sarif/v2/sarif" - "golang.org/x/exp/maps" -) - -const ( - sastScannerType = "sast" - sastScanCommand = "zd" - sastDocsUrlSuffix = "sast" -) - -type SastScanManager struct { - sastScannerResults []*sarif.Run - scanner *jas.JasScanner -} - -func RunSastScan(scanner *jas.JasScanner) (results []*sarif.Run, err error) { - sastScanManager := newSastScanManager(scanner) - log.Info("Running SAST scanning...") - if err = sastScanManager.scanner.Run(sastScanManager); err != nil { - err = utils.ParseAnalyzerManagerError(utils.Sast, err) - return - } - if len(sastScanManager.sastScannerResults) > 0 { - log.Info("Found", utils.GetResultsLocationCount(sastScanManager.sastScannerResults...), "SAST vulnerabilities") - } - results = sastScanManager.sastScannerResults - return -} - -func newSastScanManager(scanner *jas.JasScanner) (manager *SastScanManager) { - return &SastScanManager{ - sastScannerResults: []*sarif.Run{}, - scanner: scanner, - } -} - -func (ssm *SastScanManager) Run(module jfrogappsconfig.Module) (err error) { - if jas.ShouldSkipScanner(module, utils.Sast) { - return - } - if err = ssm.createConfigFile(module); err != nil { - return - } - scanner := ssm.scanner - if err = ssm.runAnalyzerManager(filepath.Dir(ssm.scanner.AnalyzerManager.AnalyzerManagerFullPath)); err != nil { - return - } - workingDirRuns, err := jas.ReadJasScanRunsFromFile(scanner.ResultsFileName, module.SourceRoot, sastDocsUrlSuffix) - if err != nil { - return - } - groupResultsByLocation(workingDirRuns) - ssm.sastScannerResults = append(ssm.sastScannerResults, workingDirRuns...) - return -} - -type sastScanConfig struct { - Scans []scanConfiguration `yaml:"scans,omitempty"` -} - -type scanConfiguration struct { - Roots []string `yaml:"roots,omitempty"` - Type string `yaml:"type,omitempty"` - Language string `yaml:"language,omitempty"` - ExcludePatterns []string `yaml:"exclude_patterns,omitempty"` - ExcludedRules []string `yaml:"excluded-rules,omitempty"` -} - -func (ssm *SastScanManager) createConfigFile(module jfrogappsconfig.Module) error { - sastScanner := module.Scanners.Sast - if sastScanner == nil { - sastScanner = &jfrogappsconfig.SastScanner{} - } - roots, err := jas.GetSourceRoots(module, &sastScanner.Scanner) - if err != nil { - return err - } - configFileContent := sastScanConfig{ - Scans: []scanConfiguration{ - { - Type: sastScannerType, - Roots: roots, - Language: sastScanner.Language, - ExcludedRules: sastScanner.ExcludedRules, - ExcludePatterns: jas.GetExcludePatterns(module, &sastScanner.Scanner), - }, - }, - } - return jas.CreateScannersConfigFile(ssm.scanner.ConfigFileName, configFileContent, utils.Sast) -} - -func (ssm *SastScanManager) runAnalyzerManager(wd string) error { - return ssm.scanner.AnalyzerManager.ExecWithOutputFile(ssm.scanner.ConfigFileName, sastScanCommand, wd, ssm.scanner.ResultsFileName, ssm.scanner.ServerDetails) -} - -// In the Sast scanner, there can be multiple results with the same location. -// The only difference is that their CodeFlow values are different. -// We combine those under the same result location value -func groupResultsByLocation(sarifRuns []*sarif.Run) { - for _, sastRun := range sarifRuns { - locationToResult := map[string]*sarif.Result{} - for _, sastResult := range sastRun.Results { - resultID := getResultId(sastResult) - if result, exists := locationToResult[resultID]; exists { - result.CodeFlows = append(result.CodeFlows, sastResult.CodeFlows...) - } else { - locationToResult[resultID] = sastResult - } - } - sastRun.Results = maps.Values(locationToResult) - } -} - -func getResultLocationStr(result *sarif.Result) string { - if len(result.Locations) == 0 { - return "" - } - location := result.Locations[0] - return fmt.Sprintf("%s%d%d%d%d", - utils.GetLocationFileName(location), - utils.GetLocationStartLine(location), - utils.GetLocationStartColumn(location), - utils.GetLocationEndLine(location), - utils.GetLocationEndColumn(location)) -} - -func getResultRuleId(result *sarif.Result) string { - if result.RuleID == nil { - return "" - } - return *result.RuleID -} - -func getResultId(result *sarif.Result) string { - return getResultRuleId(result) + utils.GetResultSeverity(result) + utils.GetResultMsgText(result) + getResultLocationStr(result) -} diff --git a/xray/commands/audit/jas/sast/sastscanner_test.go b/xray/commands/audit/jas/sast/sastscanner_test.go deleted file mode 100644 index 43eedf705..000000000 --- a/xray/commands/audit/jas/sast/sastscanner_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package sast - -import ( - "path/filepath" - "testing" - - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/owenrumney/go-sarif/v2/sarif" - - "github.com/stretchr/testify/assert" -) - -func TestNewSastScanManager(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t, "currentDir") - defer cleanUp() - // Act - sastScanManager := newSastScanManager(scanner) - - // Assert - if assert.NotNil(t, sastScanManager) { - assert.NotEmpty(t, sastScanManager.scanner.ConfigFileName) - assert.NotEmpty(t, sastScanManager.scanner.ResultsFileName) - assert.NotEmpty(t, sastScanManager.scanner.JFrogAppsConfig.Modules[0].SourceRoot) - assert.Equal(t, &jas.FakeServerDetails, sastScanManager.scanner.ServerDetails) - } -} - -func TestSastParseResults_EmptyResults(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - // Arrange - sastScanManager := newSastScanManager(scanner) - sastScanManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "sast-scan", "no-violations.sarif") - - // Act - var err error - sastScanManager.sastScannerResults, err = jas.ReadJasScanRunsFromFile(sastScanManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, sastDocsUrlSuffix) - - // Assert - if assert.NoError(t, err) && assert.NotNil(t, sastScanManager.sastScannerResults) { - assert.Len(t, sastScanManager.sastScannerResults, 1) - assert.Empty(t, sastScanManager.sastScannerResults[0].Results) - groupResultsByLocation(sastScanManager.sastScannerResults) - assert.Len(t, sastScanManager.sastScannerResults, 1) - assert.Empty(t, sastScanManager.sastScannerResults[0].Results) - } -} - -func TestSastParseResults_ResultsContainIacViolations(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - // Arrange - sastScanManager := newSastScanManager(scanner) - sastScanManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "sast-scan", "contains-sast-violations.sarif") - - // Act - var err error - sastScanManager.sastScannerResults, err = jas.ReadJasScanRunsFromFile(sastScanManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, sastDocsUrlSuffix) - - // Assert - if assert.NoError(t, err) && assert.NotNil(t, sastScanManager.sastScannerResults) { - assert.Len(t, sastScanManager.sastScannerResults, 1) - assert.NotEmpty(t, sastScanManager.sastScannerResults[0].Results) - groupResultsByLocation(sastScanManager.sastScannerResults) - // File has 4 results, 2 of them at the same location different codeFlow - assert.Len(t, sastScanManager.sastScannerResults[0].Results, 3) - } -} - -func TestGroupResultsByLocation(t *testing.T) { - tests := []struct { - run *sarif.Run - expectedOutput *sarif.Run - }{ - { - run: utils.CreateRunWithDummyResults(), - expectedOutput: utils.CreateRunWithDummyResults(), - }, - { - // No similar groups at all - run: utils.CreateRunWithDummyResults( - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "info"), - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "note"), - utils.CreateResultWithOneLocation("file", 5, 6, 7, 8, "snippet", "rule1", "info"), - utils.CreateResultWithOneLocation("file2", 1, 2, 3, 4, "snippet", "rule1", "info").WithCodeFlows([]*sarif.CodeFlow{ - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other", 0, 0, 0, 0, "other-snippet"), - utils.CreateLocation("file2", 1, 2, 3, 4, "snippet"), - )), - }), - utils.CreateResultWithOneLocation("file2", 1, 2, 3, 4, "snippet", "rule2", "info").WithCodeFlows([]*sarif.CodeFlow{ - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other2", 1, 1, 1, 1, "other-snippet2"), - utils.CreateLocation("file2", 1, 2, 3, 4, "snippet"), - )), - }), - ), - expectedOutput: utils.CreateRunWithDummyResults( - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "info"), - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "note"), - utils.CreateResultWithOneLocation("file", 5, 6, 7, 8, "snippet", "rule1", "info"), - utils.CreateResultWithOneLocation("file2", 1, 2, 3, 4, "snippet", "rule1", "info").WithCodeFlows([]*sarif.CodeFlow{ - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other", 0, 0, 0, 0, "other-snippet"), - utils.CreateLocation("file2", 1, 2, 3, 4, "snippet"), - )), - }), - utils.CreateResultWithOneLocation("file2", 1, 2, 3, 4, "snippet", "rule2", "info").WithCodeFlows([]*sarif.CodeFlow{ - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other2", 1, 1, 1, 1, "other-snippet2"), - utils.CreateLocation("file2", 1, 2, 3, 4, "snippet"), - )), - }), - ), - }, - { - // With similar groups - run: utils.CreateRunWithDummyResults( - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "info").WithCodeFlows([]*sarif.CodeFlow{ - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other", 0, 0, 0, 0, "other-snippet"), - utils.CreateLocation("file", 1, 2, 3, 4, "snippet"), - )), - }), - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "info").WithCodeFlows([]*sarif.CodeFlow{ - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other2", 1, 1, 1, 1, "other-snippet"), - utils.CreateLocation("file", 1, 2, 3, 4, "snippet"), - )), - }), - utils.CreateResultWithOneLocation("file", 5, 6, 7, 8, "snippet", "rule1", "info"), - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "info"), - ), - expectedOutput: utils.CreateRunWithDummyResults( - utils.CreateResultWithOneLocation("file", 1, 2, 3, 4, "snippet", "rule1", "info").WithCodeFlows([]*sarif.CodeFlow{ - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other", 0, 0, 0, 0, "other-snippet"), - utils.CreateLocation("file", 1, 2, 3, 4, "snippet"), - )), - utils.CreateCodeFlow(utils.CreateThreadFlow( - utils.CreateLocation("other2", 1, 1, 1, 1, "other-snippet"), - utils.CreateLocation("file", 1, 2, 3, 4, "snippet"), - )), - }), - utils.CreateResultWithOneLocation("file", 5, 6, 7, 8, "snippet", "rule1", "info"), - ), - }, - } - - for _, test := range tests { - groupResultsByLocation([]*sarif.Run{test.run}) - assert.ElementsMatch(t, test.expectedOutput.Results, test.run.Results) - } -} diff --git a/xray/commands/audit/jas/secrets/secretsscanner.go b/xray/commands/audit/jas/secrets/secretsscanner.go deleted file mode 100644 index aad7fc6a6..000000000 --- a/xray/commands/audit/jas/secrets/secretsscanner.go +++ /dev/null @@ -1,121 +0,0 @@ -package secrets - -import ( - "path/filepath" - "strings" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/owenrumney/go-sarif/v2/sarif" -) - -const ( - secretsScanCommand = "sec" - secretsScannerType = "secrets-scan" - secretsDocsUrlSuffix = "secrets" -) - -type SecretScanManager struct { - secretsScannerResults []*sarif.Run - scanner *jas.JasScanner -} - -// The getSecretsScanResults function runs the secrets scan flow, which includes the following steps: -// Creating an SecretScanManager object. -// Running the analyzer manager executable. -// Parsing the analyzer manager results. -// Return values: -// []utils.IacOrSecretResult: a list of the secrets that were found. -// error: An error object (if any). -func RunSecretsScan(scanner *jas.JasScanner) (results []*sarif.Run, err error) { - secretScanManager := newSecretsScanManager(scanner) - log.Info("Running secrets scanning...") - if err = secretScanManager.scanner.Run(secretScanManager); err != nil { - err = utils.ParseAnalyzerManagerError(utils.Secrets, err) - return - } - results = secretScanManager.secretsScannerResults - if len(results) > 0 { - log.Info("Found", utils.GetResultsLocationCount(results...), "secrets") - } - return -} - -func newSecretsScanManager(scanner *jas.JasScanner) (manager *SecretScanManager) { - return &SecretScanManager{ - secretsScannerResults: []*sarif.Run{}, - scanner: scanner, - } -} - -func (ssm *SecretScanManager) Run(module jfrogappsconfig.Module) (err error) { - if jas.ShouldSkipScanner(module, utils.Secrets) { - return - } - if err = ssm.createConfigFile(module); err != nil { - return - } - if err = ssm.runAnalyzerManager(); err != nil { - return - } - workingDirRuns, err := jas.ReadJasScanRunsFromFile(ssm.scanner.ResultsFileName, module.SourceRoot, secretsDocsUrlSuffix) - if err != nil { - return - } - ssm.secretsScannerResults = append(ssm.secretsScannerResults, processSecretScanRuns(workingDirRuns)...) - return -} - -type secretsScanConfig struct { - Scans []secretsScanConfiguration `yaml:"scans"` -} - -type secretsScanConfiguration struct { - Roots []string `yaml:"roots"` - Output string `yaml:"output"` - Type string `yaml:"type"` - SkippedDirs []string `yaml:"skipped-folders"` -} - -func (s *SecretScanManager) createConfigFile(module jfrogappsconfig.Module) error { - roots, err := jas.GetSourceRoots(module, module.Scanners.Secrets) - if err != nil { - return err - } - configFileContent := secretsScanConfig{ - Scans: []secretsScanConfiguration{ - { - Roots: roots, - Output: s.scanner.ResultsFileName, - Type: secretsScannerType, - SkippedDirs: jas.GetExcludePatterns(module, module.Scanners.Secrets), - }, - }, - } - return jas.CreateScannersConfigFile(s.scanner.ConfigFileName, configFileContent, utils.Secrets) -} - -func (s *SecretScanManager) runAnalyzerManager() error { - return s.scanner.AnalyzerManager.Exec(s.scanner.ConfigFileName, secretsScanCommand, filepath.Dir(s.scanner.AnalyzerManager.AnalyzerManagerFullPath), s.scanner.ServerDetails) -} - -func maskSecret(secret string) string { - if len(secret) <= 3 { - return "***" - } - return secret[:3] + strings.Repeat("*", 12) -} - -func processSecretScanRuns(sarifRuns []*sarif.Run) []*sarif.Run { - for _, secretRun := range sarifRuns { - // Hide discovered secrets value - for _, secretResult := range secretRun.Results { - for _, location := range secretResult.Locations { - utils.SetLocationSnippet(location, maskSecret(utils.GetLocationSnippet(location))) - } - } - } - return sarifRuns -} diff --git a/xray/commands/audit/jas/secrets/secretsscanner_test.go b/xray/commands/audit/jas/secrets/secretsscanner_test.go deleted file mode 100644 index 1b2a053ec..000000000 --- a/xray/commands/audit/jas/secrets/secretsscanner_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package secrets - -import ( - "os" - "path/filepath" - "testing" - - jfrogappsconfig "github.com/jfrog/jfrog-apps-config/go" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/stretchr/testify/assert" -) - -func TestNewSecretsScanManager(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - secretScanManager := newSecretsScanManager(scanner) - - assert.NotEmpty(t, secretScanManager) - assert.NotEmpty(t, secretScanManager.scanner.ConfigFileName) - assert.NotEmpty(t, secretScanManager.scanner.ResultsFileName) - assert.Equal(t, &jas.FakeServerDetails, secretScanManager.scanner.ServerDetails) -} - -func TestSecretsScan_CreateConfigFile_VerifyFileWasCreated(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - secretScanManager := newSecretsScanManager(scanner) - - currWd, err := coreutils.GetWorkingDirectory() - assert.NoError(t, err) - err = secretScanManager.createConfigFile(jfrogappsconfig.Module{SourceRoot: currWd}) - assert.NoError(t, err) - - defer func() { - err = os.Remove(secretScanManager.scanner.ConfigFileName) - assert.NoError(t, err) - }() - - _, fileNotExistError := os.Stat(secretScanManager.scanner.ConfigFileName) - assert.NoError(t, fileNotExistError) - fileContent, err := os.ReadFile(secretScanManager.scanner.ConfigFileName) - assert.NoError(t, err) - assert.True(t, len(fileContent) > 0) -} - -func TestRunAnalyzerManager_ReturnsGeneralError(t *testing.T) { - defer func() { - os.Clearenv() - }() - - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - secretScanManager := newSecretsScanManager(scanner) - assert.Error(t, secretScanManager.runAnalyzerManager()) -} - -func TestParseResults_EmptyResults(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - // Arrange - secretScanManager := newSecretsScanManager(scanner) - secretScanManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "secrets-scan", "no-secrets.sarif") - - // Act - var err error - secretScanManager.secretsScannerResults, err = jas.ReadJasScanRunsFromFile(secretScanManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, secretsDocsUrlSuffix) - - // Assert - if assert.NoError(t, err) && assert.NotNil(t, secretScanManager.secretsScannerResults) { - assert.Len(t, secretScanManager.secretsScannerResults, 1) - assert.Empty(t, secretScanManager.secretsScannerResults[0].Results) - secretScanManager.secretsScannerResults = processSecretScanRuns(secretScanManager.secretsScannerResults) - assert.Len(t, secretScanManager.secretsScannerResults, 1) - assert.Empty(t, secretScanManager.secretsScannerResults[0].Results) - } - -} - -func TestParseResults_ResultsContainSecrets(t *testing.T) { - // Arrange - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - secretScanManager := newSecretsScanManager(scanner) - secretScanManager.scanner.ResultsFileName = filepath.Join(jas.GetTestDataPath(), "secrets-scan", "contain-secrets.sarif") - - // Act - var err error - secretScanManager.secretsScannerResults, err = jas.ReadJasScanRunsFromFile(secretScanManager.scanner.ResultsFileName, scanner.JFrogAppsConfig.Modules[0].SourceRoot, secretsDocsUrlSuffix) - - // Assert - if assert.NoError(t, err) && assert.NotNil(t, secretScanManager.secretsScannerResults) { - assert.Len(t, secretScanManager.secretsScannerResults, 1) - assert.NotEmpty(t, secretScanManager.secretsScannerResults[0].Results) - secretScanManager.secretsScannerResults = processSecretScanRuns(secretScanManager.secretsScannerResults) - assert.Len(t, secretScanManager.secretsScannerResults, 1) - assert.Len(t, secretScanManager.secretsScannerResults[0].Results, 7) - } - assert.NoError(t, err) - -} - -func TestGetSecretsScanResults_AnalyzerManagerReturnsError(t *testing.T) { - scanner, cleanUp := jas.InitJasTest(t) - defer cleanUp() - - secretsResults, err := RunSecretsScan(scanner) - - assert.Error(t, err) - assert.ErrorContains(t, err, "failed to run Secrets scan") - assert.Nil(t, secretsResults) -} - -func TestHideSecret(t *testing.T) { - tests := []struct { - secret string - expectedOutput string - }{ - {secret: "", expectedOutput: "***"}, - {secret: "12", expectedOutput: "***"}, - {secret: "123", expectedOutput: "***"}, - {secret: "123456789", expectedOutput: "123************"}, - {secret: "3478hfnkjhvd848446gghgfh", expectedOutput: "347************"}, - } - - for _, test := range tests { - assert.Equal(t, test.expectedOutput, maskSecret(test.secret)) - } -} diff --git a/xray/commands/audit/jas/testdata/.jfrog/jfrog-apps-config.yml b/xray/commands/audit/jas/testdata/.jfrog/jfrog-apps-config.yml deleted file mode 100644 index 9357059d7..000000000 --- a/xray/commands/audit/jas/testdata/.jfrog/jfrog-apps-config.yml +++ /dev/null @@ -1,50 +0,0 @@ -# [Required] JFrog Applications Config version -version: "1.0" - -modules: - # [Required] Module name - - name: FrogLeapApp - # [Optional, default: "."] Application's root directory - source_root: "src" - # [Optional] Directories to exclude from scanning across all scanners - exclude_patterns: - - "docs/" - # [Optional] Scanners to exclude from JFrog Advanced Security (Options: "secrets", "sast", "iac") - exclude_scanners: - - secrets - # [Optional] Customize scanner configurations - scanners: - # [Optional] Configuration for Static Application Security Testing (SAST) - sast: - # [Optional] Specify the programming language for SAST - language: java - # [Optional] Working directories specific to SAST (Relative to source_root) - working_dirs: - - "src/module1" - - "src/module2" - # [Optional] Additional exclude patterns for this scanner - exclude_patterns: - - "src/module1/test" - # [Optional] List of specific scan rules to exclude from the scan - excluded_rules: - - xss-injection - - # [Optional] Configuration for secrets scan - secrets: - # [Optional] Working directories specific to the secret scanner (Relative to source_root) - working_dirs: - - "src/module1" - - "src/module2" - # [Optional] Additional exclude patterns for this scanner - exclude_patterns: - - "src/module1/test" - - # [Optional] Configuration for Infrastructure as Code scan (IaC) - iac: - # [Optional] Working directories specific to IaC (Relative to source_root) - working_dirs: - - "src/module1" - - "src/module2" - # [Optional] Additional exclude patterns for this Scanner - exclude_patterns: - - "src/module1/test" \ No newline at end of file diff --git a/xray/commands/audit/jasrunner.go b/xray/commands/audit/jasrunner.go deleted file mode 100644 index b9dc0c154..000000000 --- a/xray/commands/audit/jasrunner.go +++ /dev/null @@ -1,60 +0,0 @@ -package audit - -import ( - "errors" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas/applicability" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas/iac" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas/sast" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas/secrets" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/io" - "github.com/jfrog/jfrog-client-go/utils/log" -) - -func runJasScannersAndSetResults(scanResults *utils.Results, directDependencies []string, - serverDetails *config.ServerDetails, workingDirs []string, progress io.ProgressMgr, multiScanId string, thirdPartyApplicabilityScan bool) (err error) { - if serverDetails == nil || len(serverDetails.Url) == 0 { - log.Warn("To include 'Advanced Security' scan as part of the audit output, please run the 'jf c add' command before running this command.") - return - } - scanner, err := jas.NewJasScanner(workingDirs, serverDetails, multiScanId) - if err != nil { - return - } - defer func() { - cleanup := scanner.ScannerDirCleanupFunc - err = errors.Join(err, cleanup()) - }() - if progress != nil { - progress.SetHeadlineMsg("Running applicability scanning") - } - scanResults.ExtendedScanResults.ApplicabilityScanResults, err = applicability.RunApplicabilityScan(scanResults.GetScaScansXrayResults(), directDependencies, scanResults.GetScaScannedTechnologies(), scanner, thirdPartyApplicabilityScan) - if err != nil { - return - } - // Don't execute other scanners when scanning third party dependencies. - if thirdPartyApplicabilityScan { - return - } - if progress != nil { - progress.SetHeadlineMsg("Running secrets scanning") - } - scanResults.ExtendedScanResults.SecretsScanResults, err = secrets.RunSecretsScan(scanner) - if err != nil { - return - } - if progress != nil { - progress.SetHeadlineMsg("Running IaC scanning") - } - scanResults.ExtendedScanResults.IacScanResults, err = iac.RunIacScan(scanner) - if err != nil { - return - } - if progress != nil { - progress.SetHeadlineMsg("Running SAST scanning") - } - scanResults.ExtendedScanResults.SastScanResults, err = sast.RunSastScan(scanner) - return -} diff --git a/xray/commands/audit/jasrunner_test.go b/xray/commands/audit/jasrunner_test.go deleted file mode 100644 index d77bfc6a1..000000000 --- a/xray/commands/audit/jasrunner_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package audit - -import ( - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/dependencies" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/jas" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/stretchr/testify/assert" - "os" - "testing" -) - -func TestGetExtendedScanResults_AnalyzerManagerDoesntExist(t *testing.T) { - tmpDir, err := fileutils.CreateTempDir() - defer func() { - assert.NoError(t, fileutils.RemoveTempDir(tmpDir)) - }() - assert.NoError(t, err) - assert.NoError(t, os.Setenv(coreutils.HomeDir, tmpDir)) - defer func() { - assert.NoError(t, os.Unsetenv(coreutils.HomeDir)) - }() - scanResults := &utils.Results{ScaResults: []utils.ScaScanResult{{Technology: coreutils.Yarn, XrayResults: jas.FakeBasicXrayResults}}, ExtendedScanResults: &utils.ExtendedScanResults{}} - err = runJasScannersAndSetResults(scanResults, []string{"issueId_1_direct_dependency", "issueId_2_direct_dependency"}, &jas.FakeServerDetails, nil, nil, "", false) - // Expect error: - assert.Error(t, err) -} - -func TestGetExtendedScanResults_ServerNotValid(t *testing.T) { - scanResults := &utils.Results{ScaResults: []utils.ScaScanResult{{Technology: coreutils.Pip, XrayResults: jas.FakeBasicXrayResults}}, ExtendedScanResults: &utils.ExtendedScanResults{}} - err := runJasScannersAndSetResults(scanResults, []string{"issueId_1_direct_dependency", "issueId_2_direct_dependency"}, nil, nil, nil, "", false) - assert.NoError(t, err) -} - -func TestGetExtendedScanResults_AnalyzerManagerReturnsError(t *testing.T) { - assert.NoError(t, dependencies.DownloadAnalyzerManagerIfNeeded()) - - scanResults := &utils.Results{ScaResults: []utils.ScaScanResult{{Technology: coreutils.Yarn, XrayResults: jas.FakeBasicXrayResults}}, ExtendedScanResults: &utils.ExtendedScanResults{}} - err := runJasScannersAndSetResults(scanResults, []string{"issueId_2_direct_dependency", "issueId_1_direct_dependency"}, &jas.FakeServerDetails, nil, nil, "", false) - - // Expect error: - assert.ErrorContains(t, err, "failed to run Applicability scan") -} diff --git a/xray/commands/audit/sca/common.go b/xray/commands/audit/sca/common.go deleted file mode 100644 index f945a2110..000000000 --- a/xray/commands/audit/sca/common.go +++ /dev/null @@ -1,215 +0,0 @@ -package sca - -import ( - "fmt" - biutils "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/tests" - "github.com/jfrog/jfrog-cli-core/v2/xray/scangraph" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - ioUtils "github.com/jfrog/jfrog-client-go/utils/io" - "github.com/jfrog/jfrog-client-go/utils/log" - testsutils "github.com/jfrog/jfrog-client-go/utils/tests" - "github.com/jfrog/jfrog-client-go/xray/services" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "github.com/stretchr/testify/assert" - "golang.org/x/exp/maps" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" -) - -const maxUniqueAppearances = 10 - -func BuildXrayDependencyTree(treeHelper map[string][]string, nodeId string) (*xrayUtils.GraphNode, []string) { - rootNode := &xrayUtils.GraphNode{ - Id: nodeId, - Nodes: []*xrayUtils.GraphNode{}, - } - dependencyAppearances := map[string]int8{} - populateXrayDependencyTree(rootNode, treeHelper, &dependencyAppearances) - return rootNode, maps.Keys(dependencyAppearances) -} - -func populateXrayDependencyTree(currNode *xrayUtils.GraphNode, treeHelper map[string][]string, dependencyAppearances *map[string]int8) { - (*dependencyAppearances)[currNode.Id]++ - // Recursively create & append all node's dependencies. - for _, childDepId := range treeHelper[currNode.Id] { - childNode := &xrayUtils.GraphNode{ - Id: childDepId, - Nodes: []*xrayUtils.GraphNode{}, - Parent: currNode, - } - if (*dependencyAppearances)[childDepId] >= maxUniqueAppearances || childNode.NodeHasLoop() { - continue - } - currNode.Nodes = append(currNode.Nodes, childNode) - populateXrayDependencyTree(childNode, treeHelper, dependencyAppearances) - } -} - -func RunXrayDependenciesTreeScanGraph(dependencyTree *xrayUtils.GraphNode, progress ioUtils.ProgressMgr, technology coreutils.Technology, scanGraphParams *scangraph.ScanGraphParams) (results []services.ScanResponse, err error) { - scanGraphParams.XrayGraphScanParams().DependenciesGraph = dependencyTree - xscGitInfoContext := scanGraphParams.XrayGraphScanParams().XscGitInfoContext - if xscGitInfoContext != nil { - xscGitInfoContext.Technologies = []string{technology.String()} - } - scanMessage := fmt.Sprintf("Scanning %d %s dependencies", len(dependencyTree.Nodes), technology) - if progress != nil { - progress.SetHeadlineMsg(scanMessage) - } - log.Info(scanMessage + "...") - var scanResults *services.ScanResponse - scanResults, err = scangraph.RunScanGraphAndGetResults(scanGraphParams) - if err != nil { - err = errorutils.CheckErrorf("scanning %s dependencies failed with error: %s", string(technology), err.Error()) - return - } - for i := range scanResults.Vulnerabilities { - scanResults.Vulnerabilities[i].Technology = technology.String() - } - for i := range scanResults.Violations { - scanResults.Violations[i].Technology = technology.String() - } - results = append(results, *scanResults) - return -} - -func CreateTestWorkspace(t *testing.T, sourceDir string) (string, func()) { - tempDirPath, createTempDirCallback := tests.CreateTempDirWithCallbackAndAssert(t) - assert.NoError(t, biutils.CopyDir(filepath.Join("..", "..", "..", "testdata", sourceDir), tempDirPath, true, nil)) - wd, err := os.Getwd() - assert.NoError(t, err, "Failed to get current dir") - chdirCallback := testsutils.ChangeDirWithCallback(t, wd, tempDirPath) - return tempDirPath, func() { - chdirCallback() - createTempDirCallback() - } -} - -func GetAndAssertNode(t *testing.T, modules []*xrayUtils.GraphNode, moduleId string) *xrayUtils.GraphNode { - module := GetModule(modules, moduleId) - assert.NotNil(t, module, "Module '"+moduleId+"' doesn't exist") - return module -} - -// GetModule gets a specific module from the provided modules list -func GetModule(modules []*xrayUtils.GraphNode, moduleId string) *xrayUtils.GraphNode { - for _, module := range modules { - splitIdentifier := strings.Split(module.Id, "//") - id := splitIdentifier[0] - if len(splitIdentifier) > 1 { - id = splitIdentifier[1] - } - if id == moduleId { - return module - } - } - return nil -} - -// GetExecutableVersion gets an executable version and prints to the debug log if possible. -// Only supported for package managers that use "--version". -func LogExecutableVersion(executable string) { - verBytes, err := exec.Command(executable, "--version").CombinedOutput() - if err != nil { - log.Debug(fmt.Sprintf("'%q --version' command received an error: %s", executable, err.Error())) - return - } - if len(verBytes) == 0 { - log.Debug(fmt.Sprintf("'%q --version' command received an empty response", executable)) - return - } - version := strings.TrimSpace(string(verBytes)) - log.Debug(fmt.Sprintf("Used %q version: %s", executable, version)) -} - -// BuildImpactPathsForScanResponse builds the full impact paths for each vulnerability found in the scanResult argument, using the dependencyTrees argument. -// Returns the updated services.ScanResponse slice. -func BuildImpactPathsForScanResponse(scanResult []services.ScanResponse, dependencyTree []*xrayUtils.GraphNode) []services.ScanResponse { - for _, result := range scanResult { - if len(result.Vulnerabilities) > 0 { - buildVulnerabilitiesImpactPaths(result.Vulnerabilities, dependencyTree) - } - if len(result.Violations) > 0 { - buildViolationsImpactPaths(result.Violations, dependencyTree) - } - if len(result.Licenses) > 0 { - buildLicensesImpactPaths(result.Licenses, dependencyTree) - } - } - return scanResult -} - -// Initialize a map of issues empty impact paths -func fillIssuesMapWithEmptyImpactPaths(issuesImpactPathsMap map[string][][]services.ImpactPathNode, components map[string]services.Component) { - for dependencyName := range components { - issuesImpactPathsMap[dependencyName] = [][]services.ImpactPathNode{} - } -} - -// Set the impact paths for each issue in the map -func buildImpactPaths(issuesImpactPathsMap map[string][][]services.ImpactPathNode, dependencyTrees []*xrayUtils.GraphNode) { - for _, dependency := range dependencyTrees { - setPathsForIssues(dependency, issuesImpactPathsMap, []services.ImpactPathNode{}) - } -} - -func buildVulnerabilitiesImpactPaths(vulnerabilities []services.Vulnerability, dependencyTrees []*xrayUtils.GraphNode) { - issuesMap := make(map[string][][]services.ImpactPathNode) - for _, vulnerability := range vulnerabilities { - fillIssuesMapWithEmptyImpactPaths(issuesMap, vulnerability.Components) - } - buildImpactPaths(issuesMap, dependencyTrees) - for i := range vulnerabilities { - updateComponentsWithImpactPaths(vulnerabilities[i].Components, issuesMap) - } -} - -func buildViolationsImpactPaths(violations []services.Violation, dependencyTrees []*xrayUtils.GraphNode) { - issuesMap := make(map[string][][]services.ImpactPathNode) - for _, violation := range violations { - fillIssuesMapWithEmptyImpactPaths(issuesMap, violation.Components) - } - buildImpactPaths(issuesMap, dependencyTrees) - for i := range violations { - updateComponentsWithImpactPaths(violations[i].Components, issuesMap) - } -} - -func buildLicensesImpactPaths(licenses []services.License, dependencyTrees []*xrayUtils.GraphNode) { - issuesMap := make(map[string][][]services.ImpactPathNode) - for _, license := range licenses { - fillIssuesMapWithEmptyImpactPaths(issuesMap, license.Components) - } - buildImpactPaths(issuesMap, dependencyTrees) - for i := range licenses { - updateComponentsWithImpactPaths(licenses[i].Components, issuesMap) - } -} - -func updateComponentsWithImpactPaths(components map[string]services.Component, issuesMap map[string][][]services.ImpactPathNode) { - for dependencyName := range components { - updatedComponent := services.Component{ - FixedVersions: components[dependencyName].FixedVersions, - ImpactPaths: issuesMap[dependencyName], - Cpes: components[dependencyName].Cpes, - } - components[dependencyName] = updatedComponent - } -} - -func setPathsForIssues(dependency *xrayUtils.GraphNode, issuesImpactPathsMap map[string][][]services.ImpactPathNode, pathFromRoot []services.ImpactPathNode) { - pathFromRoot = append(pathFromRoot, services.ImpactPathNode{ComponentId: dependency.Id}) - if _, exists := issuesImpactPathsMap[dependency.Id]; exists { - // Create a copy of pathFromRoot to avoid modifying the original slice - pathCopy := make([]services.ImpactPathNode, len(pathFromRoot)) - copy(pathCopy, pathFromRoot) - issuesImpactPathsMap[dependency.Id] = append(issuesImpactPathsMap[dependency.Id], pathCopy) - } - for _, depChild := range dependency.Nodes { - setPathsForIssues(depChild, issuesImpactPathsMap, pathFromRoot) - } -} diff --git a/xray/commands/audit/sca/common_test.go b/xray/commands/audit/sca/common_test.go deleted file mode 100644 index dd4bb1bab..000000000 --- a/xray/commands/audit/sca/common_test.go +++ /dev/null @@ -1,225 +0,0 @@ -package sca - -import ( - "github.com/jfrog/jfrog-cli-core/v2/utils/tests" - "github.com/jfrog/jfrog-client-go/xray/services" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "github.com/stretchr/testify/assert" - "reflect" - "testing" -) - -func TestSetPathsForIssues(t *testing.T) { - // Create a test dependency tree - rootNode := &xrayUtils.GraphNode{Id: "root"} - childNode1 := &xrayUtils.GraphNode{Id: "child1"} - childNode2 := &xrayUtils.GraphNode{Id: "child2"} - childNode3 := &xrayUtils.GraphNode{Id: "child3"} - childNode4 := &xrayUtils.GraphNode{Id: "child4"} - childNode5 := &xrayUtils.GraphNode{Id: "child5"} - rootNode.Nodes = []*xrayUtils.GraphNode{childNode1, childNode2, childNode3} - childNode2.Nodes = []*xrayUtils.GraphNode{childNode4} - childNode3.Nodes = []*xrayUtils.GraphNode{childNode5} - - // Create a test issues map - issuesMap := make(map[string][][]services.ImpactPathNode) - issuesMap["child1"] = [][]services.ImpactPathNode{} - issuesMap["child4"] = [][]services.ImpactPathNode{} - issuesMap["child5"] = [][]services.ImpactPathNode{} - - // Call setPathsForIssues with the test data - setPathsForIssues(rootNode, issuesMap, []services.ImpactPathNode{}) - - // Check the results - assert.Equal(t, issuesMap["child1"][0][0].ComponentId, "root") - assert.Equal(t, issuesMap["child1"][0][1].ComponentId, "child1") - - assert.Equal(t, issuesMap["child4"][0][0].ComponentId, "root") - assert.Equal(t, issuesMap["child4"][0][1].ComponentId, "child2") - assert.Equal(t, issuesMap["child4"][0][2].ComponentId, "child4") - - assert.Equal(t, issuesMap["child5"][0][0].ComponentId, "root") - assert.Equal(t, issuesMap["child5"][0][1].ComponentId, "child3") - assert.Equal(t, issuesMap["child5"][0][2].ComponentId, "child5") -} - -func TestUpdateVulnerableComponent(t *testing.T) { - components := map[string]services.Component{ - "dependency1": { - FixedVersions: []string{"1.0.0"}, - ImpactPaths: [][]services.ImpactPathNode{}, - }, - } - dependencyName, issuesMap := "dependency1", map[string][][]services.ImpactPathNode{ - "dependency1": {}, - } - - updateComponentsWithImpactPaths(components, issuesMap) - - // Check the result - expected := services.Component{ - FixedVersions: []string{"1.0.0"}, - ImpactPaths: issuesMap[dependencyName], - } - assert.Equal(t, expected, components[dependencyName]) -} - -func TestBuildImpactPaths(t *testing.T) { - // create sample scan result and dependency trees - scanResult := []services.ScanResponse{ - { - Vulnerabilities: []services.Vulnerability{ - { - Components: map[string]services.Component{ - "dep1": { - FixedVersions: []string{"1.2.3"}, - Cpes: []string{"cpe:/o:vendor:product:1.2.3"}, - }, - "dep2": { - FixedVersions: []string{"3.0.0"}, - }, - }, - }, - }, - Violations: []services.Violation{ - { - Components: map[string]services.Component{ - "dep2": { - FixedVersions: []string{"4.5.6"}, - Cpes: []string{"cpe:/o:vendor:product:4.5.6"}, - }, - }, - }, - }, - Licenses: []services.License{ - { - Components: map[string]services.Component{ - "dep3": { - FixedVersions: []string{"7.8.9"}, - Cpes: []string{"cpe:/o:vendor:product:7.8.9"}, - }, - }, - }, - }, - }, - } - dependencyTrees := []*xrayUtils.GraphNode{ - { - Id: "dep1", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "dep2", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "dep3", - Nodes: []*xrayUtils.GraphNode{}, - }, - }, - }, - }, - }, - { - Id: "dep7", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "dep4", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "dep2", - Nodes: []*xrayUtils.GraphNode{}, - }, - { - Id: "dep5", - Nodes: []*xrayUtils.GraphNode{}, - }, - { - Id: "dep6", - Nodes: []*xrayUtils.GraphNode{}, - }, - }, - }, - }, - }, - } - - scanResult = BuildImpactPathsForScanResponse(scanResult, dependencyTrees) - // assert that the components were updated with impact paths - expectedImpactPaths := [][]services.ImpactPathNode{{{ComponentId: "dep1"}}} - assert.Equal(t, expectedImpactPaths, scanResult[0].Vulnerabilities[0].Components["dep1"].ImpactPaths) - expectedImpactPaths = [][]services.ImpactPathNode{{{ComponentId: "dep1"}, {ComponentId: "dep2"}}} - reflect.DeepEqual(expectedImpactPaths, scanResult[0].Vulnerabilities[0].Components["dep2"].ImpactPaths[0]) - expectedImpactPaths = [][]services.ImpactPathNode{{{ComponentId: "dep7"}, {ComponentId: "dep4"}, {ComponentId: "dep2"}}} - reflect.DeepEqual(expectedImpactPaths, scanResult[0].Vulnerabilities[0].Components["dep2"].ImpactPaths[1]) - expectedImpactPaths = [][]services.ImpactPathNode{{{ComponentId: "dep1"}}} - reflect.DeepEqual(expectedImpactPaths, scanResult[0].Violations[0].Components["dep1"].ImpactPaths) - expectedImpactPaths = [][]services.ImpactPathNode{{{ComponentId: "dep1"}, {ComponentId: "dep2"}}} - reflect.DeepEqual(expectedImpactPaths, scanResult[0].Violations[0].Components["dep2"].ImpactPaths[0]) - expectedImpactPaths = [][]services.ImpactPathNode{{{ComponentId: "dep7"}, {ComponentId: "dep4"}, {ComponentId: "dep2"}}} - reflect.DeepEqual(expectedImpactPaths, scanResult[0].Violations[0].Components["dep2"].ImpactPaths[1]) - expectedImpactPaths = [][]services.ImpactPathNode{{{ComponentId: "dep7"}, {ComponentId: "dep4"}, {ComponentId: "dep2"}}} - reflect.DeepEqual(expectedImpactPaths, scanResult[0].Violations[0].Components["dep2"].ImpactPaths) - expectedImpactPaths = [][]services.ImpactPathNode{{{ComponentId: "dep1"}, {ComponentId: "dep2"}, {ComponentId: "dep3"}}} - reflect.DeepEqual(expectedImpactPaths, scanResult[0].Licenses[0].Components["dep3"].ImpactPaths) -} - -func TestBuildXrayDependencyTree(t *testing.T) { - treeHelper := make(map[string][]string) - rootDep := []string{"topDep1", "topDep2", "topDep3"} - topDep1 := []string{"midDep1", "midDep2"} - topDep2 := []string{"midDep2", "midDep3"} - midDep1 := []string{"bottomDep1"} - midDep2 := []string{"bottomDep2", "bottomDep3"} - bottomDep3 := []string{"leafDep"} - treeHelper["rootDep"] = rootDep - treeHelper["topDep1"] = topDep1 - treeHelper["topDep2"] = topDep2 - treeHelper["midDep1"] = midDep1 - treeHelper["midDep2"] = midDep2 - treeHelper["bottomDep3"] = bottomDep3 - - expectedUniqueDeps := []string{"rootDep", "topDep1", "topDep2", "topDep3", "midDep1", "midDep2", "midDep3", "bottomDep1", "bottomDep2", "bottomDep3", "leafDep"} - - // Constructing the expected tree Nodes - leafDepNode := &xrayUtils.GraphNode{Id: "leafDep", Nodes: []*xrayUtils.GraphNode{}} - bottomDep3Node := &xrayUtils.GraphNode{Id: "bottomDep3", Nodes: []*xrayUtils.GraphNode{}} - bottomDep2Node := &xrayUtils.GraphNode{Id: "bottomDep2", Nodes: []*xrayUtils.GraphNode{}} - bottomDep1Node := &xrayUtils.GraphNode{Id: "bottomDep1", Nodes: []*xrayUtils.GraphNode{}} - midDep3Node := &xrayUtils.GraphNode{Id: "midDep3", Nodes: []*xrayUtils.GraphNode{}} - midDep2Node := &xrayUtils.GraphNode{Id: "midDep2", Nodes: []*xrayUtils.GraphNode{}} - midDep1Node := &xrayUtils.GraphNode{Id: "midDep1", Nodes: []*xrayUtils.GraphNode{}} - topDep3Node := &xrayUtils.GraphNode{Id: "topDep3", Nodes: []*xrayUtils.GraphNode{}} - topDep2Node := &xrayUtils.GraphNode{Id: "topDep2", Nodes: []*xrayUtils.GraphNode{}} - topDep1Node := &xrayUtils.GraphNode{Id: "topDep1", Nodes: []*xrayUtils.GraphNode{}} - rootNode := &xrayUtils.GraphNode{Id: "rootDep", Nodes: []*xrayUtils.GraphNode{}} - - // Setting children to parents - bottomDep3Node.Nodes = append(bottomDep3Node.Nodes, leafDepNode) - midDep2Node.Nodes = append(midDep2Node.Nodes, bottomDep3Node) - midDep2Node.Nodes = append(midDep2Node.Nodes, bottomDep2Node) - midDep1Node.Nodes = append(midDep1Node.Nodes, bottomDep1Node) - topDep2Node.Nodes = append(topDep2Node.Nodes, midDep3Node) - topDep2Node.Nodes = append(topDep2Node.Nodes, midDep2Node) - topDep1Node.Nodes = append(topDep1Node.Nodes, midDep2Node) - topDep1Node.Nodes = append(topDep1Node.Nodes, midDep1Node) - rootNode.Nodes = append(rootNode.Nodes, topDep1Node) - rootNode.Nodes = append(rootNode.Nodes, topDep2Node) - rootNode.Nodes = append(rootNode.Nodes, topDep3Node) - - // Setting children to parents - leafDepNode.Parent = bottomDep3Node - bottomDep3Node.Parent = midDep2Node - bottomDep3Node.Parent = midDep2Node - bottomDep1Node.Parent = midDep1Node - midDep3Node.Parent = topDep2Node - midDep2Node.Parent = topDep2Node - midDep2Node.Parent = topDep1Node - midDep1Node.Parent = topDep1Node - topDep1Node.Parent = rootNode - topDep2Node.Parent = rootNode - topDep3Node.Parent = rootNode - - tree, uniqueDeps := BuildXrayDependencyTree(treeHelper, "rootDep") - - assert.ElementsMatch(t, expectedUniqueDeps, uniqueDeps) - assert.True(t, tests.CompareTree(tree, rootNode)) -} diff --git a/xray/commands/audit/sca/go/gloang_test.go b/xray/commands/audit/sca/go/gloang_test.go deleted file mode 100644 index ba8853a87..000000000 --- a/xray/commands/audit/sca/go/gloang_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package _go - -import ( - "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "os" - "strings" - "testing" - - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - - "github.com/stretchr/testify/assert" -) - -func TestBuildGoDependencyList(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "go-project") - defer cleanUp() - - err := removeTxtSuffix("go.mod.txt") - assert.NoError(t, err) - err = removeTxtSuffix("go.sum.txt") - assert.NoError(t, err) - err = removeTxtSuffix("test.go.txt") - assert.NoError(t, err) - - // Run getModulesDependencyTrees - server := &config.ServerDetails{ - Url: "https://api.go.here", - ArtifactoryUrl: "https://api.go.here/artifactory", - User: "user", - AccessToken: "sdsdccs2232", - } - goVersionID, err := getGoVersionAsDependency() - assert.NoError(t, err) - expectedUniqueDeps := []string{ - goPackageTypeIdentifier + "golang.org/x/text:v0.3.3", - goPackageTypeIdentifier + "rsc.io/quote:v1.5.2", - goPackageTypeIdentifier + "rsc.io/sampler:v1.3.0", - goPackageTypeIdentifier + "testGoList", - goVersionID.Id, - } - - auditBasicParams := (&xrayutils.AuditBasicParams{}).SetServerDetails(server).SetDepsRepo("test-remote") - rootNode, uniqueDeps, err := BuildDependencyTree(auditBasicParams) - assert.NoError(t, err) - assert.ElementsMatch(t, uniqueDeps, expectedUniqueDeps, "First is actual, Second is Expected") - - assert.Equal(t, "https://user:sdsdccs2232@api.go.here/artifactoryapi/go/test-remote|direct", os.Getenv("GOPROXY")) - assert.NotEmpty(t, rootNode) - - // Check root module - assert.Equal(t, rootNode[0].Id, goPackageTypeIdentifier+"testGoList") - assert.Len(t, rootNode[0].Nodes, 3) - - // Test go version node - goVersion, err := utils.GetParsedGoVersion() - assert.NoError(t, err) - sca.GetAndAssertNode(t, rootNode[0].Nodes, strings.ReplaceAll(goVersion.GetVersion(), "go", goSourceCodePrefix)) - - // Test child without sub nodes - child1 := sca.GetAndAssertNode(t, rootNode[0].Nodes, "golang.org/x/text:v0.3.3") - assert.Len(t, child1.Nodes, 0) - - // Test child with 1 sub node - child2 := sca.GetAndAssertNode(t, rootNode[0].Nodes, "rsc.io/quote:v1.5.2") - assert.Len(t, child2.Nodes, 1) - sca.GetAndAssertNode(t, child2.Nodes, "rsc.io/sampler:v1.3.0") -} - -func removeTxtSuffix(txtFileName string) error { - // go.sum.txt >> go.sum - return fileutils.MoveFile(txtFileName, strings.TrimSuffix(txtFileName, ".txt")) -} diff --git a/xray/commands/audit/sca/go/golang.go b/xray/commands/audit/sca/go/golang.go deleted file mode 100644 index 4c4757cf4..000000000 --- a/xray/commands/audit/sca/go/golang.go +++ /dev/null @@ -1,115 +0,0 @@ -package _go - -import ( - "fmt" - biutils "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/gofrog/datastructures" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - goutils "github.com/jfrog/jfrog-cli-core/v2/utils/golang" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "os" - "strings" -) - -const ( - goPackageTypeIdentifier = "go://" - goSourceCodePrefix = "github.com/golang/go:v" -) - -func BuildDependencyTree(params utils.AuditParams) (dependencyTree []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - currentDir, err := coreutils.GetWorkingDirectory() - if err != nil { - return - } - - server, err := params.ServerDetails() - if err != nil { - err = fmt.Errorf("failed while getting server details: %s", err.Error()) - return - } - - remoteGoRepo := params.DepsRepo() - if remoteGoRepo != "" { - if err = setGoProxy(server, remoteGoRepo); err != nil { - return - } - } - // Calculate go dependencies graph - dependenciesGraph, err := goutils.GetDependenciesGraph(currentDir) - if err != nil || len(dependenciesGraph) == 0 { - return - } - // Calculate go dependencies list - dependenciesList, err := goutils.GetDependenciesList(currentDir) - if err != nil { - return - } - // Get root module name - rootModuleName, err := goutils.GetModuleName(currentDir) - if err != nil { - return - } - // Parse the dependencies into Xray dependency tree format - rootNode := &xrayUtils.GraphNode{ - Id: goPackageTypeIdentifier + rootModuleName, - Nodes: []*xrayUtils.GraphNode{}, - } - uniqueDepsSet := datastructures.MakeSet[string]() - populateGoDependencyTree(rootNode, dependenciesGraph, dependenciesList, uniqueDepsSet) - - goVersionDependency, err := getGoVersionAsDependency() - if err != nil { - return - } - rootNode.Nodes = append(rootNode.Nodes, goVersionDependency) - uniqueDepsSet.Add(goVersionDependency.Id) - - dependencyTree = []*xrayUtils.GraphNode{rootNode} - uniqueDeps = uniqueDepsSet.ToSlice() - return -} - -func setGoProxy(server *config.ServerDetails, remoteGoRepo string) error { - repoUrl, err := goutils.GetArtifactoryRemoteRepoUrl(server, remoteGoRepo) - if err != nil { - return err - } - repoUrl += "|direct" - return os.Setenv("GOPROXY", repoUrl) -} - -func populateGoDependencyTree(currNode *xrayUtils.GraphNode, dependenciesGraph map[string][]string, dependenciesList map[string]bool, uniqueDepsSet *datastructures.Set[string]) { - if currNode.NodeHasLoop() { - return - } - uniqueDepsSet.Add(currNode.Id) - currDepChildren := dependenciesGraph[strings.TrimPrefix(currNode.Id, goPackageTypeIdentifier)] - // Recursively create & append all node's dependencies. - for _, childName := range currDepChildren { - if !dependenciesList[childName] { - // 'go list all' is more accurate than 'go graph' so we filter out deps that don't exist in go list - continue - } - childNode := &xrayUtils.GraphNode{ - Id: goPackageTypeIdentifier + childName, - Nodes: []*xrayUtils.GraphNode{}, - Parent: currNode, - } - currNode.Nodes = append(currNode.Nodes, childNode) - populateGoDependencyTree(childNode, dependenciesGraph, dependenciesList, uniqueDepsSet) - } -} - -func getGoVersionAsDependency() (*xrayUtils.GraphNode, error) { - goVersion, err := biutils.GetParsedGoVersion() - if err != nil { - return nil, err - } - // Convert "go1.17.3" to "github.com/golang/go:v1.17.3" - goVersionID := strings.ReplaceAll(goVersion.GetVersion(), "go", goSourceCodePrefix) - return &xrayUtils.GraphNode{ - Id: goPackageTypeIdentifier + goVersionID, - }, nil -} diff --git a/xray/commands/audit/sca/java/deptreemanager.go b/xray/commands/audit/sca/java/deptreemanager.go deleted file mode 100644 index 53cab3b77..000000000 --- a/xray/commands/audit/sca/java/deptreemanager.go +++ /dev/null @@ -1,132 +0,0 @@ -package java - -import ( - "encoding/json" - "github.com/jfrog/gofrog/datastructures" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "os" - "strings" -) - -const ( - GavPackageTypeIdentifier = "gav://" -) - -func BuildDependencyTree(params xrayutils.AuditParams, tech coreutils.Technology) ([]*xrayUtils.GraphNode, []string, error) { - serverDetails, err := params.ServerDetails() - if err != nil { - return nil, nil, err - } - depTreeParams := &DepTreeParams{ - UseWrapper: params.UseWrapper(), - Server: serverDetails, - DepsRepo: params.DepsRepo(), - } - if tech == coreutils.Maven { - return buildMavenDependencyTree(depTreeParams, params.IsMavenDepTreeInstalled()) - } - return buildGradleDependencyTree(depTreeParams) -} - -type DepTreeParams struct { - UseWrapper bool - Server *config.ServerDetails - DepsRepo string -} - -type DepTreeManager struct { - server *config.ServerDetails - depsRepo string - useWrapper bool -} - -func NewDepTreeManager(params *DepTreeParams) DepTreeManager { - return DepTreeManager{useWrapper: params.UseWrapper, depsRepo: params.DepsRepo, server: params.Server} -} - -// The structure of a dependency tree of a module in a Gradle/Maven project, as created by the gradle-dep-tree and maven-dep-tree plugins. -type moduleDepTree struct { - Root string `json:"root"` - Nodes map[string]depTreeNode `json:"nodes"` -} - -type depTreeNode struct { - Children []string `json:"children"` -} - -// Reads the output files of the gradle-dep-tree and maven-dep-tree plugins and returns them as a slice of GraphNodes. -// It takes the output of the plugin's run (which is a byte representation of a list of paths of the output files, separated by newlines) as input. -func getGraphFromDepTree(outputFilePaths string) (depsGraph []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - modules, err := parseDepTreeFiles(outputFilePaths) - if err != nil { - return - } - - allModulesUniqueDeps := datastructures.MakeSet[string]() - for _, module := range modules { - moduleTree, moduleUniqueDeps := getModuleTreeAndDependencies(module) - depsGraph = append(depsGraph, moduleTree) - for _, depToAdd := range moduleUniqueDeps { - allModulesUniqueDeps.Add(depToAdd) - } - } - uniqueDeps = allModulesUniqueDeps.ToSlice() - return -} - -func parseDepTreeFiles(jsonFilePaths string) ([]*moduleDepTree, error) { - outputFilePaths := strings.Split(strings.TrimSpace(jsonFilePaths), "\n") - var modules []*moduleDepTree - for _, path := range outputFilePaths { - results, err := parseDepTreeFile(path) - if err != nil { - return nil, err - } - modules = append(modules, results) - } - return modules, nil -} - -func parseDepTreeFile(path string) (results *moduleDepTree, err error) { - depTreeJson, err := os.ReadFile(strings.TrimSpace(path)) - if errorutils.CheckError(err) != nil { - return - } - results = &moduleDepTree{} - err = errorutils.CheckError(json.Unmarshal(depTreeJson, &results)) - return -} - -func getArtifactoryAuthFromServer(server *config.ServerDetails) (string, string, error) { - username, password, err := server.GetAuthenticationCredentials() - if err != nil { - return "", "", err - } - if username == "" { - return "", "", errorutils.CheckErrorf("a username is required for authenticating with Artifactory") - } - return username, password, nil -} - -// Returns a dependency tree and a flat list of the module's dependencies for the given module -func getModuleTreeAndDependencies(module *moduleDepTree) (*xrayUtils.GraphNode, []string) { - moduleTreeMap := make(map[string][]string) - moduleDeps := module.Nodes - for depName, dependency := range moduleDeps { - dependencyId := GavPackageTypeIdentifier + depName - var childrenList []string - for _, childName := range dependency.Children { - childId := GavPackageTypeIdentifier + childName - childrenList = append(childrenList, childId) - } - if len(childrenList) > 0 { - moduleTreeMap[dependencyId] = childrenList - } - } - return sca.BuildXrayDependencyTree(moduleTreeMap, GavPackageTypeIdentifier+module.Root) -} diff --git a/xray/commands/audit/sca/java/deptreemanager_test.go b/xray/commands/audit/sca/java/deptreemanager_test.go deleted file mode 100644 index ad54a4370..000000000 --- a/xray/commands/audit/sca/java/deptreemanager_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package java - -import ( - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "github.com/stretchr/testify/assert" - "os" - "path/filepath" - "reflect" - "strings" - "testing" -) - -func TestGetGradleGraphFromDepTree(t *testing.T) { - // Create and change directory to test workspace - tempDirPath, cleanUp := sca.CreateTestWorkspace(t, "gradle-example-ci-server") - defer cleanUp() - assert.NoError(t, os.Chmod(filepath.Join(tempDirPath, "gradlew"), 0700)) - expectedTree := map[string]map[string]string{ - "org.jfrog.example.gradle:shared:1.0": {}, - "org.jfrog.example.gradle:" + filepath.Base(tempDirPath) + ":1.0": {}, - "org.jfrog.example.gradle:services:1.0": {}, - "org.jfrog.example.gradle:webservice:1.0": { - "junit:junit:4.11": "", - "commons-io:commons-io:1.2": "", - "org.apache.wicket:wicket:1.3.7": "", - "org.jfrog.example.gradle:shared:1.0": "", - "org.jfrog.example.gradle:api:1.0": "", - "commons-lang:commons-lang:2.4": "", - "commons-collections:commons-collections:3.2": "", - }, - "org.jfrog.example.gradle:api:1.0": { - "org.apache.wicket:wicket:1.3.7": "", - "org.jfrog.example.gradle:shared:1.0": "", - "commons-lang:commons-lang:2.4": "", - }, - } - expectedUniqueDeps := []string{ - "junit:junit:4.11", - "org.jfrog.example.gradle:webservice:1.0", - "org.jfrog.example.gradle:api:1.0", - "org.jfrog.example.gradle:" + filepath.Base(tempDirPath) + ":1.0", - "commons-io:commons-io:1.2", - "org.apache.wicket:wicket:1.3.7", - "org.jfrog.example.gradle:shared:1.0", - "org.jfrog.example.gradle:api:1.0", - "commons-collections:commons-collections:3.2", - "commons-lang:commons-lang:2.4", - "org.hamcrest:hamcrest-core:1.3", - "org.slf4j:slf4j-api:1.4.2", - } - - manager := &gradleDepTreeManager{DepTreeManager{}} - outputFileContent, err := manager.runGradleDepTree() - assert.NoError(t, err) - depTree, uniqueDeps, err := getGraphFromDepTree(outputFileContent) - assert.NoError(t, err) - reflect.DeepEqual(uniqueDeps, expectedUniqueDeps) - - for _, dependency := range depTree { - dependencyId := strings.TrimPrefix(dependency.Id, GavPackageTypeIdentifier) - depChild, exists := expectedTree[dependencyId] - assert.True(t, exists) - assert.Equal(t, len(depChild), len(dependency.Nodes)) - } -} diff --git a/xray/commands/audit/sca/java/gradle.go b/xray/commands/audit/sca/java/gradle.go deleted file mode 100644 index 013a2f3a6..000000000 --- a/xray/commands/audit/sca/java/gradle.go +++ /dev/null @@ -1,199 +0,0 @@ -package java - -import ( - _ "embed" - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/jfrog/build-info-go/build" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/ioutils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" -) - -const ( - remoteDepTreePath = "artifactory/oss-release-local" - gradlew = "gradlew" - gradleDepTreeJarFile = "gradle-dep-tree.jar" - gradleDepTreeInitFile = "gradledeptree.init" - gradleDepTreeOutputFile = "gradledeptree.out" - gradleDepTreeInitScript = `initscript { - repositories { %s - mavenCentral() - } - dependencies { - classpath files('%s') - } -} - -allprojects { - repositories { %s - } - apply plugin: com.jfrog.GradleDepTree -}` - artifactoryRepository = ` - maven { - url "%s/%s" - credentials { - username = '%s' - password = '%s' - } - }` -) - -//go:embed resources/gradle-dep-tree.jar -var gradleDepTreeJar []byte - -type gradleDepTreeManager struct { - DepTreeManager -} - -func buildGradleDependencyTree(params *DepTreeParams) (dependencyTree []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - manager := &gradleDepTreeManager{DepTreeManager: NewDepTreeManager(params)} - outputFileContent, err := manager.runGradleDepTree() - if err != nil { - return - } - dependencyTree, uniqueDeps, err = getGraphFromDepTree(outputFileContent) - return -} - -func (gdt *gradleDepTreeManager) runGradleDepTree() (string, error) { - // Create the script file in the repository - depTreeDir, err := gdt.createDepTreeScriptAndGetDir() - if err != nil { - return "", err - } - defer func() { - err = errors.Join(err, fileutils.RemoveTempDir(depTreeDir)) - }() - - if gdt.useWrapper { - gdt.useWrapper, err = isGradleWrapperExist() - if err != nil { - return "", err - } - } - - output, err := gdt.execGradleDepTree(depTreeDir) - if err != nil { - return "", err - } - return string(output), nil -} - -func (gdt *gradleDepTreeManager) createDepTreeScriptAndGetDir() (tmpDir string, err error) { - tmpDir, err = fileutils.CreateTempDir() - if err != nil { - return - } - var releasesRepo string - releasesRepo, gdt.depsRepo, err = getRemoteRepos(gdt.depsRepo, gdt.server) - if err != nil { - return - } - gradleDepTreeJarPath := filepath.Join(tmpDir, gradleDepTreeJarFile) - if err = errorutils.CheckError(os.WriteFile(gradleDepTreeJarPath, gradleDepTreeJar, 0600)); err != nil { - return - } - gradleDepTreeJarPath = ioutils.DoubleWinPathSeparator(gradleDepTreeJarPath) - - depTreeInitScript := fmt.Sprintf(gradleDepTreeInitScript, releasesRepo, gradleDepTreeJarPath, gdt.depsRepo) - return tmpDir, errorutils.CheckError(os.WriteFile(filepath.Join(tmpDir, gradleDepTreeInitFile), []byte(depTreeInitScript), 0666)) -} - -// getRemoteRepos constructs the sections of Artifactory's remote repositories in the gradle-dep-tree init script. -// depsRemoteRepo - name of the remote repository that proxies the relevant registry, e.g. maven central. -// server - the Artifactory server details on which the repositories reside in. -// Returns the constructed sections. -func getRemoteRepos(depsRepo string, server *config.ServerDetails) (string, string, error) { - constructedReleasesRepo, err := constructReleasesRemoteRepo() - if err != nil { - return "", "", err - } - - constructedDepsRepo, err := getDepTreeArtifactoryRepository(depsRepo, server) - if err != nil { - return "", "", err - } - return constructedReleasesRepo, constructedDepsRepo, nil -} - -func constructReleasesRemoteRepo() (string, error) { - // Try to retrieve the serverID and remote repository that proxies https://releases.jfrog.io, from the environment variable - serverId, repoName, err := coreutils.GetServerIdAndRepo(coreutils.ReleasesRemoteEnv) - if err != nil || serverId == "" || repoName == "" { - return "", err - } - - releasesServer, err := config.GetSpecificConfig(serverId, false, true) - if err != nil { - return "", err - } - - releasesPath := fmt.Sprintf("%s/%s", repoName, remoteDepTreePath) - log.Debug("The `"+gradleDepTreeJarFile+"` will be resolved from", repoName) - return getDepTreeArtifactoryRepository(releasesPath, releasesServer) -} - -func (gdt *gradleDepTreeManager) execGradleDepTree(depTreeDir string) (outputFileContent []byte, err error) { - gradleExecPath, err := build.GetGradleExecPath(gdt.useWrapper) - if err != nil { - err = errorutils.CheckError(err) - return - } - - outputFilePath := filepath.Join(depTreeDir, gradleDepTreeOutputFile) - tasks := []string{ - "clean", - "generateDepTrees", "-I", filepath.Join(depTreeDir, gradleDepTreeInitFile), - "-q", - fmt.Sprintf("-Dcom.jfrog.depsTreeOutputFile=%s", outputFilePath), - "-Dcom.jfrog.includeAllBuildFiles=true"} - log.Info("Running gradle deps tree command:", gradleExecPath, strings.Join(tasks, " ")) - if output, err := exec.Command(gradleExecPath, tasks...).CombinedOutput(); err != nil { - return nil, errorutils.CheckErrorf("error running gradle-dep-tree: %s\n%s", err.Error(), string(output)) - } - defer func() { - err = errors.Join(err, errorutils.CheckError(os.Remove(outputFilePath))) - }() - - outputFileContent, err = os.ReadFile(outputFilePath) - err = errorutils.CheckError(err) - return -} - -func getDepTreeArtifactoryRepository(remoteRepo string, server *config.ServerDetails) (string, error) { - if remoteRepo == "" || server.IsEmpty() { - return "", nil - } - username, password, err := getArtifactoryAuthFromServer(server) - if err != nil { - return "", err - } - - log.Debug("The project dependencies will be resolved from", server.ArtifactoryUrl, "from the", remoteRepo, "repository") - return fmt.Sprintf(artifactoryRepository, - strings.TrimSuffix(server.ArtifactoryUrl, "/"), - remoteRepo, - username, - password), nil -} - -// This function assumes that the Gradle wrapper is in the root directory. -// The --project-dir option of Gradle won't work in this case. -func isGradleWrapperExist() (bool, error) { - wrapperName := gradlew - if coreutils.IsWindows() { - wrapperName += ".bat" - } - return fileutils.IsFileExists(wrapperName, false) -} diff --git a/xray/commands/audit/sca/java/gradle_test.go b/xray/commands/audit/sca/java/gradle_test.go deleted file mode 100644 index b41272aec..000000000 --- a/xray/commands/audit/sca/java/gradle_test.go +++ /dev/null @@ -1,230 +0,0 @@ -package java - -import ( - "errors" - "fmt" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "os" - "path/filepath" - "testing" - - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - testsutils "github.com/jfrog/jfrog-cli-core/v2/utils/config/tests" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/ioutils" - - "github.com/stretchr/testify/assert" -) - -// #nosec G101 -- Dummy token for tests -// jfrog-ignore -const dummyToken = "eyJ2ZXIiOiIyIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYiLCJraWQiOiJIcnU2VHctZk1yOTV3dy12TDNjV3ZBVjJ3Qm9FSHpHdGlwUEFwOE1JdDljIn0.eyJzdWIiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3XC91c2Vyc1wvYWRtaW4iLCJzY3AiOiJtZW1iZXItb2YtZ3JvdXBzOnJlYWRlcnMgYXBpOioiLCJhdWQiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3IiwiaXNzIjoiamZydEAwMWMzZ2ZmaGcyZTh3NjE0OWUzYTJxMHc5NyIsImV4cCI6MTU1NjAzNzc2NSwiaWF0IjoxNTU2MDM0MTY1LCJqdGkiOiI1M2FlMzgyMy05NGM3LTQ0OGItOGExOC1iZGVhNDBiZjFlMjAifQ.Bp3sdvppvRxysMlLgqT48nRIHXISj9sJUCXrm7pp8evJGZW1S9hFuK1olPmcSybk2HNzdzoMcwhUmdUzAssiQkQvqd_HanRcfFbrHeg5l1fUQ397ECES-r5xK18SYtG1VR7LNTVzhJqkmRd3jzqfmIK2hKWpEgPfm8DRz3j4GGtDRxhb3oaVsT2tSSi_VfT3Ry74tzmO0GcCvmBE2oh58kUZ4QfEsalgZ8IpYHTxovsgDx_M7ujOSZx_hzpz-iy268-OkrU22PQPCfBmlbEKeEUStUO9n0pj4l1ODL31AGARyJRy46w4yzhw7Fk5P336WmDMXYs5LAX2XxPFNLvNzA" - -const expectedInitScriptWithRepos = `initscript { - repositories { - mavenCentral() - } - dependencies { - classpath files('%s') - } -} - -allprojects { - repositories { - maven { - url "https://myartifactory.com/artifactory/deps-repo" - credentials { - username = 'admin' - password = '%s' - } - } - } - apply plugin: com.jfrog.GradleDepTree -}` - -func TestGradleTreesWithoutConfig(t *testing.T) { - // Create and change directory to test workspace - tempDirPath, cleanUp := sca.CreateTestWorkspace(t, "gradle-example-ci-server") - defer cleanUp() - assert.NoError(t, os.Chmod(filepath.Join(tempDirPath, "gradlew"), 0700)) - - // Run getModulesDependencyTrees - modulesDependencyTrees, uniqueDeps, err := buildGradleDependencyTree(&DepTreeParams{}) - if assert.NoError(t, err) && assert.NotNil(t, modulesDependencyTrees) { - assert.Len(t, uniqueDeps, 12) - assert.Len(t, modulesDependencyTrees, 5) - // Check module - module := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.example.gradle:webservice:1.0") - assert.Len(t, module.Nodes, 7) - - // Check direct dependency - directDependency := sca.GetAndAssertNode(t, module.Nodes, "junit:junit:4.11") - assert.Len(t, directDependency.Nodes, 1) - - // Check transitive dependency - sca.GetAndAssertNode(t, directDependency.Nodes, "org.hamcrest:hamcrest-core:1.3") - } -} - -func TestGradleTreesWithConfig(t *testing.T) { - // Create and change directory to test workspace - tempDirPath, cleanUp := sca.CreateTestWorkspace(t, "gradle-example-publish") - defer cleanUp() - assert.NoError(t, os.Chmod(filepath.Join(tempDirPath, "gradlew"), 0700)) - - // Run getModulesDependencyTrees - modulesDependencyTrees, uniqueDeps, err := buildGradleDependencyTree(&DepTreeParams{UseWrapper: true}) - if assert.NoError(t, err) && assert.NotNil(t, modulesDependencyTrees) { - assert.Len(t, modulesDependencyTrees, 5) - assert.Len(t, uniqueDeps, 11) - // Check module - module := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test.gradle.publish:api:1.0-SNAPSHOT") - assert.Len(t, module.Nodes, 4) - - // Check direct dependency - directDependency := sca.GetAndAssertNode(t, module.Nodes, "commons-lang:commons-lang:2.4") - assert.Len(t, directDependency.Nodes, 1) - - // Check transitive dependency - sca.GetAndAssertNode(t, directDependency.Nodes, "commons-io:commons-io:1.2") - } -} - -func TestIsGradleWrapperExist(t *testing.T) { - // Check Gradle wrapper doesn't exist - isWrapperExist, err := isGradleWrapperExist() - assert.False(t, isWrapperExist) - assert.NoError(t, err) - - // Check Gradle wrapper exist - _, cleanUp := sca.CreateTestWorkspace(t, "gradle-example-ci-server") - defer cleanUp() - isWrapperExist, err = isGradleWrapperExist() - assert.NoError(t, err) - assert.True(t, isWrapperExist) -} - -func TestGetDepTreeArtifactoryRepository(t *testing.T) { - tests := []struct { - name string - remoteRepo string - server *config.ServerDetails - expectedUrl string - expectedErr string - }{ - { - name: "WithAccessToken", - remoteRepo: "my-remote-repo", - server: &config.ServerDetails{ - Url: "https://myartifactory.com", - // jfrog-ignore - AccessToken: dummyToken, - }, - // jfrog-ignore - expectedUrl: "\n\t\tmaven {\n\t\t\turl \"/my-remote-repo\"\n\t\t\tcredentials {\n\t\t\t\tusername = 'admin'\n\t\t\t\tpassword = 'eyJ2ZXIiOiIyIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYiLCJraWQiOiJIcnU2VHctZk1yOTV3dy12TDNjV3ZBVjJ3Qm9FSHpHdGlwUEFwOE1JdDljIn0.eyJzdWIiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3XC91c2Vyc1wvYWRtaW4iLCJzY3AiOiJtZW1iZXItb2YtZ3JvdXBzOnJlYWRlcnMgYXBpOioiLCJhdWQiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3IiwiaXNzIjoiamZydEAwMWMzZ2ZmaGcyZTh3NjE0OWUzYTJxMHc5NyIsImV4cCI6MTU1NjAzNzc2NSwiaWF0IjoxNTU2MDM0MTY1LCJqdGkiOiI1M2FlMzgyMy05NGM3LTQ0OGItOGExOC1iZGVhNDBiZjFlMjAifQ.Bp3sdvppvRxysMlLgqT48nRIHXISj9sJUCXrm7pp8evJGZW1S9hFuK1olPmcSybk2HNzdzoMcwhUmdUzAssiQkQvqd_HanRcfFbrHeg5l1fUQ397ECES-r5xK18SYtG1VR7LNTVzhJqkmRd3jzqfmIK2hKWpEgPfm8DRz3j4GGtDRxhb3oaVsT2tSSi_VfT3Ry74tzmO0GcCvmBE2oh58kUZ4QfEsalgZ8IpYHTxovsgDx_M7ujOSZx_hzpz-iy268-OkrU22PQPCfBmlbEKeEUStUO9n0pj4l1ODL31AGARyJRy46w4yzhw7Fk5P336WmDMXYs5LAX2XxPFNLvNzA'\n\t\t\t}\n\t\t}", - expectedErr: "", - }, - { - name: "WithUsernameAndPassword", - remoteRepo: "my-remote-repo", - server: &config.ServerDetails{ - Url: "https://myartifactory.com", - User: "my-username", - Password: "my-password", - }, - expectedUrl: "\n\t\tmaven {\n\t\t\turl \"/my-remote-repo\"\n\t\t\tcredentials {\n\t\t\t\tusername = 'my-username'\n\t\t\t\tpassword = 'my-password'\n\t\t\t}\n\t\t}", - expectedErr: "", - }, - { - name: "MissingCredentials", - remoteRepo: "my-remote-repo", - server: &config.ServerDetails{ - Url: "https://myartifactory.com", - }, - expectedUrl: "", - expectedErr: "either username/password or access token must be set for https://myartifactory.com", - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - url, err := getDepTreeArtifactoryRepository(test.remoteRepo, test.server) - if err != nil { - assert.Equal(t, test.expectedErr, err.Error()) - } else { - assert.Equal(t, test.expectedUrl, url) - } - }) - } -} - -func TestCreateDepTreeScript(t *testing.T) { - manager := &gradleDepTreeManager{DepTreeManager: DepTreeManager{}} - tmpDir, err := manager.createDepTreeScriptAndGetDir() - assert.NoError(t, err) - defer func() { - assert.NoError(t, os.Remove(filepath.Join(tmpDir, gradleDepTreeInitFile))) - }() - content, err := os.ReadFile(filepath.Join(tmpDir, gradleDepTreeInitFile)) - assert.NoError(t, err) - gradleDepTreeJarPath := ioutils.DoubleWinPathSeparator(filepath.Join(tmpDir, gradleDepTreeJarFile)) - assert.Equal(t, fmt.Sprintf(gradleDepTreeInitScript, "", gradleDepTreeJarPath, ""), string(content)) -} - -func TestCreateDepTreeScriptWithRepositories(t *testing.T) { - manager := &gradleDepTreeManager{DepTreeManager: DepTreeManager{}} - manager.depsRepo = "deps-repo" - manager.server = &config.ServerDetails{ - Url: "https://myartifactory.com/", - ArtifactoryUrl: "https://myartifactory.com/artifactory", - // jfrog-ignore - AccessToken: dummyToken, - } - tmpDir, err := manager.createDepTreeScriptAndGetDir() - assert.NoError(t, err) - defer func() { - assert.NoError(t, os.Remove(filepath.Join(tmpDir, gradleDepTreeInitFile))) - }() - - content, err := os.ReadFile(filepath.Join(tmpDir, gradleDepTreeInitFile)) - assert.NoError(t, err) - gradleDepTreeJarPath := ioutils.DoubleWinPathSeparator(filepath.Join(tmpDir, gradleDepTreeJarFile)) - // jfrog-ignore - assert.Equal(t, fmt.Sprintf(expectedInitScriptWithRepos, gradleDepTreeJarPath, dummyToken), string(content)) -} - -func TestConstructReleasesRemoteRepo(t *testing.T) { - cleanUp := testsutils.CreateTempEnv(t, false) - serverDetails := &config.ServerDetails{ - ServerId: "test", - ArtifactoryUrl: "https://domain.com/artifactory", - User: "user", - Password: "pass", - } - err := config.SaveServersConf([]*config.ServerDetails{serverDetails}) - assert.NoError(t, err) - defer cleanUp() - testCases := []struct { - envVar string - expectedRepo string - expectedErr error - }{ - {envVar: "", expectedRepo: "", expectedErr: nil}, - {envVar: "test/repo1", expectedRepo: "\n\t\tmaven {\n\t\t\turl \"https://domain.com/artifactory/repo1/artifactory/oss-release-local\"\n\t\t\tcredentials {\n\t\t\t\tusername = 'user'\n\t\t\t\tpassword = 'pass'\n\t\t\t}\n\t\t}", expectedErr: nil}, - {envVar: "notexist/repo1", expectedRepo: "", expectedErr: errors.New("Server ID 'notexist' does not exist.")}, - } - - for _, tc := range testCases { - // Set the environment variable for this test case - func() { - assert.NoError(t, os.Setenv(coreutils.ReleasesRemoteEnv, tc.envVar)) - defer func() { - // Reset the environment variable after each test case - assert.NoError(t, os.Unsetenv(coreutils.ReleasesRemoteEnv)) - }() - actualRepo, actualErr := constructReleasesRemoteRepo() - assert.Equal(t, tc.expectedRepo, actualRepo) - assert.Equal(t, tc.expectedErr, actualErr) - }() - } -} diff --git a/xray/commands/audit/sca/java/mvn.go b/xray/commands/audit/sca/java/mvn.go deleted file mode 100644 index 0c3c962df..000000000 --- a/xray/commands/audit/sca/java/mvn.go +++ /dev/null @@ -1,193 +0,0 @@ -package java - -import ( - _ "embed" - "errors" - "fmt" - "github.com/jfrog/jfrog-cli-core/v2/utils/ioutils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "net/url" - "os" - "os/exec" - "path/filepath" - "strings" -) - -const ( - mavenDepTreeJarFile = "maven-dep-tree.jar" - mavenDepTreeOutputFile = "mavendeptree.out" - // Changing this version also requires a change in MAVEN_DEP_TREE_VERSION within buildscripts/download_jars.sh - mavenDepTreeVersion = "1.1.0" - settingsXmlFile = "settings.xml" -) - -var mavenConfigPath = filepath.Join(".mvn", "maven.config") - -type MavenDepTreeCmd string - -const ( - Projects MavenDepTreeCmd = "projects" - Tree MavenDepTreeCmd = "tree" -) - -//go:embed resources/settings.xml -var settingsXmlTemplate string - -//go:embed resources/maven-dep-tree.jar -var mavenDepTreeJar []byte - -type MavenDepTreeManager struct { - DepTreeManager - isInstalled bool - cmdName MavenDepTreeCmd - settingsXmlPath string -} - -func NewMavenDepTreeManager(params *DepTreeParams, cmdName MavenDepTreeCmd, isDepTreeInstalled bool) *MavenDepTreeManager { - depTreeManager := NewDepTreeManager(&DepTreeParams{ - Server: params.Server, - DepsRepo: params.DepsRepo, - }) - return &MavenDepTreeManager{ - DepTreeManager: depTreeManager, - isInstalled: isDepTreeInstalled, - cmdName: cmdName, - } -} - -func buildMavenDependencyTree(params *DepTreeParams, isDepTreeInstalled bool) (dependencyTree []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - manager := NewMavenDepTreeManager(params, Tree, isDepTreeInstalled) - outputFilePaths, err := manager.RunMavenDepTree() - if err != nil { - return - } - dependencyTree, uniqueDeps, err = getGraphFromDepTree(outputFilePaths) - return -} - -func (mdt *MavenDepTreeManager) RunMavenDepTree() (string, error) { - // Create a temp directory for all the files that are required for the maven-dep-tree run - depTreeExecDir, err := fileutils.CreateTempDir() - if err != nil { - return "", err - } - defer func() { - err = errors.Join(err, fileutils.RemoveTempDir(depTreeExecDir)) - }() - - // Create a settings.xml file that sets the dependency resolution from the given server and repository - if mdt.depsRepo != "" { - if err = mdt.createSettingsXmlWithConfiguredArtifactory(depTreeExecDir); err != nil { - return "", err - } - } - if err = mdt.installMavenDepTreePlugin(depTreeExecDir); err != nil { - return "", err - } - - depTreeOutput, err := mdt.execMavenDepTree(depTreeExecDir) - if err != nil { - return "", err - } - return depTreeOutput, nil -} - -func (mdt *MavenDepTreeManager) installMavenDepTreePlugin(depTreeExecDir string) error { - if mdt.isInstalled { - return nil - } - mavenDepTreeJarPath := filepath.Join(depTreeExecDir, mavenDepTreeJarFile) - if err := errorutils.CheckError(os.WriteFile(mavenDepTreeJarPath, mavenDepTreeJar, 0666)); err != nil { - return err - } - goals := GetMavenPluginInstallationGoals(mavenDepTreeJarPath) - _, err := mdt.RunMvnCmd(goals) - return err -} - -func GetMavenPluginInstallationGoals(pluginPath string) []string { - return []string{"org.apache.maven.plugins:maven-install-plugin:3.1.1:install-file", "-Dfile=" + pluginPath, "-B"} -} - -func (mdt *MavenDepTreeManager) execMavenDepTree(depTreeExecDir string) (string, error) { - depTreeOutputPath := filepath.Join(depTreeExecDir, mavenDepTreeOutputFile) - goals := []string{"com.jfrog:maven-dep-tree:" + mavenDepTreeVersion + ":" + string(mdt.cmdName), "-DdepsTreeOutputFile=" + depTreeOutputPath, "-B"} - return mdt.run(goals, depTreeOutputPath) -} - -func (mdt *MavenDepTreeManager) run(goals []string, depTreeOutputPath string) (string, error) { - if _, err := mdt.RunMvnCmd(goals); err != nil { - return "", err - } - mavenDepTreeOutput, err := os.ReadFile(depTreeOutputPath) - if err != nil { - return "", errorutils.CheckError(err) - } - return string(mavenDepTreeOutput), nil -} - -func (mdt *MavenDepTreeManager) RunMvnCmd(goals []string) (cmdOutput []byte, err error) { - restoreMavenConfig, err := removeMavenConfig() - if err != nil { - return - } - - defer func() { - if restoreMavenConfig != nil { - err = errors.Join(err, restoreMavenConfig()) - } - }() - - if mdt.settingsXmlPath != "" { - goals = append(goals, "-s", mdt.settingsXmlPath) - } - - //#nosec G204 - cmdOutput, err = exec.Command("mvn", goals...).CombinedOutput() - if err != nil { - if len(cmdOutput) > 0 { - log.Info(string(cmdOutput)) - } - err = fmt.Errorf("failed running command 'mvn %s': %s", strings.Join(goals, " "), err.Error()) - } - return -} - -func removeMavenConfig() (func() error, error) { - mavenConfigExists, err := fileutils.IsFileExists(mavenConfigPath, false) - if err != nil { - return nil, err - } - if !mavenConfigExists { - return nil, nil - } - restoreMavenConfig, err := ioutils.BackupFile(mavenConfigPath, "maven.config.bkp") - if err != nil { - return nil, err - } - err = os.Remove(mavenConfigPath) - if err != nil { - err = errorutils.CheckErrorf("failed to remove %s while building the maven dependencies tree. Error received:\n%s", mavenConfigPath, err.Error()) - } - return restoreMavenConfig, err -} - -// Creates a new settings.xml file configured with the provided server and repository from the current MavenDepTreeManager instance. -// The settings.xml will be written to the given path. -func (mdt *MavenDepTreeManager) createSettingsXmlWithConfiguredArtifactory(path string) error { - username, password, err := getArtifactoryAuthFromServer(mdt.server) - if err != nil { - return err - } - remoteRepositoryFullPath, err := url.JoinPath(mdt.server.ArtifactoryUrl, mdt.depsRepo) - if err != nil { - return err - } - mdt.settingsXmlPath = filepath.Join(path, settingsXmlFile) - settingsXmlContent := fmt.Sprintf(settingsXmlTemplate, username, password, remoteRepositoryFullPath) - - return errorutils.CheckError(os.WriteFile(mdt.settingsXmlPath, []byte(settingsXmlContent), 0600)) -} diff --git a/xray/commands/audit/sca/java/mvn_test.go b/xray/commands/audit/sca/java/mvn_test.go deleted file mode 100644 index 364edd407..000000000 --- a/xray/commands/audit/sca/java/mvn_test.go +++ /dev/null @@ -1,258 +0,0 @@ -package java - -import ( - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/tests" - "github.com/stretchr/testify/assert" - "os" - "path/filepath" - "strings" - "testing" -) - -const ( - //#nosec G101 - dummy token for testing - settingsXmlWithUsernameAndPassword = ` - - - - artifactory - testUser - testPass - - - - - artifactory - https://myartifactory.com/artifactory/testRepo - * - - -` - //#nosec G101 - dummy token for testing - settingsXmlWithUsernameAndToken = ` - - - - artifactory - testUser - eyJ2ZXIiOiIyIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYiLCJraWQiOiJIcnU2VHctZk1yOTV3dy12TDNjV3ZBVjJ3Qm9FSHpHdGlwUEFwOE1JdDljIn0.eyJzdWIiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3XC91c2Vyc1wvYWRtaW4iLCJzY3AiOiJtZW1iZXItb2YtZ3JvdXBzOnJlYWRlcnMgYXBpOioiLCJhdWQiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3IiwiaXNzIjoiamZydEAwMWMzZ2ZmaGcyZTh3NjE0OWUzYTJxMHc5NyIsImV4cCI6MTU1NjAzNzc2NSwiaWF0IjoxNTU2MDM0MTY1LCJqdGkiOiI1M2FlMzgyMy05NGM3LTQ0OGItOGExOC1iZGVhNDBiZjFlMjAifQ.Bp3sdvppvRxysMlLgqT48nRIHXISj9sJUCXrm7pp8evJGZW1S9hFuK1olPmcSybk2HNzdzoMcwhUmdUzAssiQkQvqd_HanRcfFbrHeg5l1fUQ397ECES-r5xK18SYtG1VR7LNTVzhJqkmRd3jzqfmIK2hKWpEgPfm8DRz3j4GGtDRxhb3oaVsT2tSSi_VfT3Ry74tzmO0GcCvmBE2oh58kUZ4QfEsalgZ8IpYHTxovsgDx_M7ujOSZx_hzpz-iy268-OkrU22PQPCfBmlbEKeEUStUO9n0pj4l1ODL31AGARyJRy46w4yzhw7Fk5P336WmDMXYs5LAX2XxPFNLvNzA - - - - - artifactory - https://myartifactory.com/artifactory/testRepo - * - - -` - //#nosec G101 - dummy token for testing - settingsXmlWithAccessToken = ` - - - - artifactory - admin - eyJ2ZXIiOiIyIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYiLCJraWQiOiJIcnU2VHctZk1yOTV3dy12TDNjV3ZBVjJ3Qm9FSHpHdGlwUEFwOE1JdDljIn0.eyJzdWIiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3XC91c2Vyc1wvYWRtaW4iLCJzY3AiOiJtZW1iZXItb2YtZ3JvdXBzOnJlYWRlcnMgYXBpOioiLCJhdWQiOiJqZnJ0QDAxYzNnZmZoZzJlOHc2MTQ5ZTNhMnEwdzk3IiwiaXNzIjoiamZydEAwMWMzZ2ZmaGcyZTh3NjE0OWUzYTJxMHc5NyIsImV4cCI6MTU1NjAzNzc2NSwiaWF0IjoxNTU2MDM0MTY1LCJqdGkiOiI1M2FlMzgyMy05NGM3LTQ0OGItOGExOC1iZGVhNDBiZjFlMjAifQ.Bp3sdvppvRxysMlLgqT48nRIHXISj9sJUCXrm7pp8evJGZW1S9hFuK1olPmcSybk2HNzdzoMcwhUmdUzAssiQkQvqd_HanRcfFbrHeg5l1fUQ397ECES-r5xK18SYtG1VR7LNTVzhJqkmRd3jzqfmIK2hKWpEgPfm8DRz3j4GGtDRxhb3oaVsT2tSSi_VfT3Ry74tzmO0GcCvmBE2oh58kUZ4QfEsalgZ8IpYHTxovsgDx_M7ujOSZx_hzpz-iy268-OkrU22PQPCfBmlbEKeEUStUO9n0pj4l1ODL31AGARyJRy46w4yzhw7Fk5P336WmDMXYs5LAX2XxPFNLvNzA - - - - - artifactory - https://myartifactory.com/artifactory/testRepo - * - - -` -) - -func TestMavenTreesMultiModule(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "maven-example") - defer cleanUp() - - expectedUniqueDeps := []string{ - GavPackageTypeIdentifier + "javax.mail:mail:1.4", - GavPackageTypeIdentifier + "org.testng:testng:5.9", - GavPackageTypeIdentifier + "javax.servlet:servlet-api:2.5", - GavPackageTypeIdentifier + "org.jfrog.test:multi:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "org.jfrog.test:multi3:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "org.jfrog.test:multi2:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "junit:junit:3.8.1", - GavPackageTypeIdentifier + "org.jfrog.test:multi1:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "commons-io:commons-io:1.4", - GavPackageTypeIdentifier + "org.apache.commons:commons-email:1.1", - GavPackageTypeIdentifier + "javax.activation:activation:1.1", - GavPackageTypeIdentifier + "hsqldb:hsqldb:1.8.0.10", - } - // Run getModulesDependencyTrees - modulesDependencyTrees, uniqueDeps, err := buildMavenDependencyTree(&DepTreeParams{}, false) - if assert.NoError(t, err) && assert.NotEmpty(t, modulesDependencyTrees) { - assert.ElementsMatch(t, uniqueDeps, expectedUniqueDeps, "First is actual, Second is Expected") - // Check root module - multi := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi:3.7-SNAPSHOT") - if assert.NotNil(t, multi) { - assert.Len(t, multi.Nodes, 1) - // Check multi1 with a transitive dependency - multi1 := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi1:3.7-SNAPSHOT") - assert.Len(t, multi1.Nodes, 4) - commonsEmail := sca.GetAndAssertNode(t, multi1.Nodes, "org.apache.commons:commons-email:1.1") - assert.Len(t, commonsEmail.Nodes, 2) - - // Check multi2 and multi3 - multi2 := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi2:3.7-SNAPSHOT") - assert.Len(t, multi2.Nodes, 1) - multi3 := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi3:3.7-SNAPSHOT") - assert.Len(t, multi3.Nodes, 4) - } - } -} - -func TestMavenWrapperTrees(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "maven-example-with-wrapper") - err := os.Chmod("mvnw", 0700) - defer cleanUp() - assert.NoError(t, err) - expectedUniqueDeps := []string{ - GavPackageTypeIdentifier + "org.jfrog.test:multi1:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "org.codehaus.plexus:plexus-utils:1.5.1", - GavPackageTypeIdentifier + "org.springframework:spring-beans:2.5.6", - GavPackageTypeIdentifier + "commons-logging:commons-logging:1.1.1", - GavPackageTypeIdentifier + "org.jfrog.test:multi3:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "org.apache.commons:commons-email:1.1", - GavPackageTypeIdentifier + "org.springframework:spring-aop:2.5.6", - GavPackageTypeIdentifier + "org.springframework:spring-core:2.5.6", - GavPackageTypeIdentifier + "org.jfrog.test:multi:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "org.jfrog.test:multi2:3.7-SNAPSHOT", - GavPackageTypeIdentifier + "org.testng:testng:5.9", - GavPackageTypeIdentifier + "hsqldb:hsqldb:1.8.0.10", - GavPackageTypeIdentifier + "junit:junit:3.8.1", - GavPackageTypeIdentifier + "javax.activation:activation:1.1", - GavPackageTypeIdentifier + "javax.mail:mail:1.4", - GavPackageTypeIdentifier + "aopalliance:aopalliance:1.0", - GavPackageTypeIdentifier + "commons-io:commons-io:1.4", - GavPackageTypeIdentifier + "javax.servlet.jsp:jsp-api:2.1", - GavPackageTypeIdentifier + "javax.servlet:servlet-api:2.5", - } - - modulesDependencyTrees, uniqueDeps, err := buildMavenDependencyTree(&DepTreeParams{}, false) - if assert.NoError(t, err) && assert.NotEmpty(t, modulesDependencyTrees) { - assert.ElementsMatch(t, uniqueDeps, expectedUniqueDeps, "First is actual, Second is Expected") - // Check root module - multi := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi:3.7-SNAPSHOT") - if assert.NotNil(t, multi) { - assert.Len(t, multi.Nodes, 1) - // Check multi1 with a transitive dependency - multi1 := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi1:3.7-SNAPSHOT") - assert.Len(t, multi1.Nodes, 7) - commonsEmail := sca.GetAndAssertNode(t, multi1.Nodes, "org.apache.commons:commons-email:1.1") - assert.Len(t, commonsEmail.Nodes, 2) - // Check multi2 and multi3 - multi2 := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi2:3.7-SNAPSHOT") - assert.Len(t, multi2.Nodes, 1) - multi3 := sca.GetAndAssertNode(t, modulesDependencyTrees, "org.jfrog.test:multi3:3.7-SNAPSHOT") - assert.Len(t, multi3.Nodes, 4) - } - } -} - -func TestGetMavenPluginInstallationArgs(t *testing.T) { - args := GetMavenPluginInstallationGoals("testPlugin") - assert.Equal(t, "org.apache.maven.plugins:maven-install-plugin:3.1.1:install-file", args[0]) - assert.Equal(t, "-Dfile=testPlugin", args[1]) -} - -func TestCreateSettingsXmlWithConfiguredArtifactory(t *testing.T) { - // Test case for successful creation of settings.xml. - mdt := MavenDepTreeManager{ - DepTreeManager: DepTreeManager{ - server: &config.ServerDetails{ - ArtifactoryUrl: "https://myartifactory.com/artifactory", - User: "testUser", - Password: "testPass", - }, - depsRepo: "testRepo", - }, - } - // Create a temporary directory for testing and settings.xml creation - tempDir := t.TempDir() - err := mdt.createSettingsXmlWithConfiguredArtifactory(tempDir) - assert.NoError(t, err) - - // Verify settings.xml file creation with username and password - settingsXmlPath := filepath.Join(tempDir, "settings.xml") - actualContent, err := os.ReadFile(settingsXmlPath) - actualContent = []byte(strings.ReplaceAll(string(actualContent), "\r\n", "\n")) - assert.NoError(t, err) - assert.Equal(t, settingsXmlWithUsernameAndPassword, string(actualContent)) - - mdt.server.Password = "" - // jfrog-ignore - mdt.server.AccessToken = dummyToken - err = mdt.createSettingsXmlWithConfiguredArtifactory(tempDir) - assert.NoError(t, err) - - // Verify settings.xml file creation with username and access token - actualContent, err = os.ReadFile(settingsXmlPath) - actualContent = []byte(strings.ReplaceAll(string(actualContent), "\r\n", "\n")) - assert.NoError(t, err) - assert.Equal(t, settingsXmlWithUsernameAndToken, string(actualContent)) - - mdt.server.User = "" - err = mdt.createSettingsXmlWithConfiguredArtifactory(tempDir) - assert.NoError(t, err) - - // Verify settings.xml file creation with access token only - actualContent, err = os.ReadFile(settingsXmlPath) - actualContent = []byte(strings.ReplaceAll(string(actualContent), "\r\n", "\n")) - assert.NoError(t, err) - assert.Equal(t, settingsXmlWithAccessToken, string(actualContent)) -} - -func TestRunProjectsCmd(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "maven-example") - defer cleanUp() - mvnDepTreeManager := NewMavenDepTreeManager(&DepTreeParams{}, Projects, false) - output, err := mvnDepTreeManager.RunMavenDepTree() - assert.NoError(t, err) - pomPathOccurrences := strings.Count(output, "pomPath") - assert.Equal(t, 4, pomPathOccurrences) -} - -func TestRemoveMavenConfig(t *testing.T) { - tmpDir := t.TempDir() - currentDir, err := os.Getwd() - assert.NoError(t, err) - restoreDir := tests.ChangeDirWithCallback(t, currentDir, tmpDir) - defer restoreDir() - - // No maven.config exists - restoreFunc, err := removeMavenConfig() - assert.Nil(t, restoreFunc) - assert.Nil(t, err) - - // Create maven.config - err = fileutils.CreateDirIfNotExist(".mvn") - assert.NoError(t, err) - file, err := os.Create(mavenConfigPath) - assert.NoError(t, err) - err = file.Close() - assert.NoError(t, err) - restoreFunc, err = removeMavenConfig() - assert.NoError(t, err) - assert.NoFileExists(t, mavenConfigPath) - err = restoreFunc() - assert.NoError(t, err) - assert.FileExists(t, mavenConfigPath) -} diff --git a/xray/commands/audit/sca/java/resources/gradle-dep-tree.jar b/xray/commands/audit/sca/java/resources/gradle-dep-tree.jar deleted file mode 100644 index b05be169487a41d066316c8c645f34634a9f3d0c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12152 zcmaiab9m&>@^zdIcVj0T+qP}nwz08o+qRu-u(561HulY4e6jc5-`n%_XXcMOr>keW z=BcVaGUC7>kN^OmJ^|cNiYo(r44_|+j{)&9B?T3DDMh7(sDS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5fVex+r@cCo zP`XO<=@16AY4+*BC5gSw-Y4kJhj$kq&;%RH2nasy%R+lhTj2w_{9UrLw8T_lmig&6 zL&ZTtE5!3h52;?7emE*OkCu2z1ekG#v8=9dA4{-5noE}JP0qLl$Xc;{@ATW(y(0T` zW33~%8Hr)rS89WyBHkzveYVq!QY#$;iyA(!Lj2oN+``l?I(+XZ1DcHJqC26_}vi!u3f4H@G(|tw>d4abpj_xXN|l> zYz}AFdsS9@wp01jaruT!isu6~DMkO4N?_AGf;%}=D9wAf9k*GikFRL|H?mTD8}R?;7b z$N?+cu%b$kjHr$=2bd5)`QSXWuO*!7oy(vE6c8k`%`GdL>U`0jt7BpQ8iE!V!YOBC zcjg30S7d-V8lRXC$wQ6|Z(IVUU)QRIGF+c|h>zSq_C%H1siny2}(9BN-FgOse$69158idAKUZ_PYQ2^DzE{olncTgKhS9BKbkRXZs&d zCbsrAwnp}jZ)9`Sv2LgU1{i=Tj}D^sUOq7!lreevVzmgj9?A;M*0Hkm_)1W z=BKke7pL7?x&fHCS`8o&3h)np{a-g1{PqO^0>H7rkGub57C*)Qy4m1&u{Ua(6E8`xj86Z{1JmF)kcq2MQQ~G2I->myz zEt$;UwIlqh@mHSnPmO|L|0j)qVm<$=@mEUhPmQ5(*~;J8_?ta{BFO#<{VOHwC$u5l zKSTc&LF-raUugzE(NB>77X1&TgFoW^aG_tTzCZCQ-|E1>xbe>#@UJkxmNtIEAd>tE z=BGpd;)%Z$I{v8Suae21N - - - - artifactory - %s - %s - - - - - artifactory - %s - * - - - \ No newline at end of file diff --git a/xray/commands/audit/sca/npm/npm.go b/xray/commands/audit/sca/npm/npm.go deleted file mode 100644 index 262c3b745..000000000 --- a/xray/commands/audit/sca/npm/npm.go +++ /dev/null @@ -1,140 +0,0 @@ -package npm - -import ( - "errors" - "fmt" - biutils "github.com/jfrog/build-info-go/build/utils" - buildinfo "github.com/jfrog/build-info-go/entities" - "github.com/jfrog/jfrog-cli-core/v2/artifactory/commands/npm" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "golang.org/x/exp/slices" -) - -const ( - ignoreScriptsFlag = "--ignore-scripts" -) - -func BuildDependencyTree(params utils.AuditParams) (dependencyTrees []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - currentDir, err := coreutils.GetWorkingDirectory() - if err != nil { - return - } - npmVersion, npmExecutablePath, err := biutils.GetNpmVersionAndExecPath(log.Logger) - if err != nil { - return - } - packageInfo, err := biutils.ReadPackageInfoFromPackageJsonIfExists(currentDir, npmVersion) - if err != nil { - return - } - - treeDepsParam := createTreeDepsParam(params) - - restoreNpmrcFunc, err := configNpmResolutionServerIfNeeded(params) - if err != nil { - err = fmt.Errorf("failed while configuring a resolution server: %s", err.Error()) - return - } - defer func() { - if restoreNpmrcFunc != nil { - err = errors.Join(err, restoreNpmrcFunc()) - } - }() - - // Calculate npm dependencies - dependenciesMap, err := biutils.CalculateDependenciesMap(npmExecutablePath, currentDir, packageInfo.BuildInfoModuleId(), treeDepsParam, log.Logger) - if err != nil { - log.Info("Used npm version:", npmVersion.GetVersion()) - return - } - var dependenciesList []buildinfo.Dependency - for _, dependency := range dependenciesMap { - dependenciesList = append(dependenciesList, dependency.Dependency) - } - // Parse the dependencies into Xray dependency tree format - dependencyTree, uniqueDeps := parseNpmDependenciesList(dependenciesList, packageInfo) - dependencyTrees = []*xrayUtils.GraphNode{dependencyTree} - return -} - -// Generates a .npmrc file to configure an Artifactory server as the resolver server. -func configNpmResolutionServerIfNeeded(params utils.AuditParams) (restoreNpmrcFunc func() error, err error) { - if params == nil { - err = fmt.Errorf("got empty params upon configuring resolution server") - return - } - serverDetails, err := params.ServerDetails() - if err != nil || serverDetails == nil { - return - } - depsRepo := params.DepsRepo() - if depsRepo == "" { - return - } - - npmCmd := npm.NewNpmCommand("install", false).SetServerDetails(serverDetails) - if err = npmCmd.PreparePrerequisites(depsRepo); err != nil { - return - } - if err = npmCmd.CreateTempNpmrc(); err != nil { - return - } - restoreNpmrcFunc = npmCmd.RestoreNpmrcFunc() - log.Info(fmt.Sprintf("Resolving dependencies from '%s' from repo '%s'", serverDetails.Url, depsRepo)) - return -} - -func createTreeDepsParam(params utils.AuditParams) biutils.NpmTreeDepListParam { - if params == nil { - return biutils.NpmTreeDepListParam{ - Args: addIgnoreScriptsFlag([]string{}), - } - } - npmTreeDepParam := biutils.NpmTreeDepListParam{ - Args: addIgnoreScriptsFlag(params.Args()), - InstallCommandArgs: params.InstallCommandArgs(), - } - if npmParams, ok := params.(utils.AuditNpmParams); ok { - npmTreeDepParam.IgnoreNodeModules = npmParams.NpmIgnoreNodeModules() - npmTreeDepParam.OverwritePackageLock = npmParams.NpmOverwritePackageLock() - } - return npmTreeDepParam -} - -// Add the --ignore-scripts to prevent execution of npm scripts during npm install. -func addIgnoreScriptsFlag(npmArgs []string) []string { - if !slices.Contains(npmArgs, ignoreScriptsFlag) { - return append(npmArgs, ignoreScriptsFlag) - } - return npmArgs -} - -// Parse the dependencies into an Xray dependency tree format -func parseNpmDependenciesList(dependencies []buildinfo.Dependency, packageInfo *biutils.PackageInfo) (*xrayUtils.GraphNode, []string) { - treeMap := make(map[string][]string) - for _, dependency := range dependencies { - dependencyId := utils.NpmPackageTypeIdentifier + dependency.Id - for _, requestedByNode := range dependency.RequestedBy { - parent := utils.NpmPackageTypeIdentifier + requestedByNode[0] - if children, ok := treeMap[parent]; ok { - treeMap[parent] = appendUniqueChild(children, dependencyId) - } else { - treeMap[parent] = []string{dependencyId} - } - } - } - return sca.BuildXrayDependencyTree(treeMap, utils.NpmPackageTypeIdentifier+packageInfo.BuildInfoModuleId()) -} - -func appendUniqueChild(children []string, candidateDependency string) []string { - for _, existingChild := range children { - if existingChild == candidateDependency { - return children - } - } - return append(children, candidateDependency) -} diff --git a/xray/commands/audit/sca/npm/npm_test.go b/xray/commands/audit/sca/npm/npm_test.go deleted file mode 100644 index ad1591238..000000000 --- a/xray/commands/audit/sca/npm/npm_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package npm - -import ( - "encoding/json" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "os" - "testing" - - biutils "github.com/jfrog/build-info-go/build/utils" - buildinfo "github.com/jfrog/build-info-go/entities" - "github.com/jfrog/jfrog-cli-core/v2/utils/tests" - "github.com/stretchr/testify/assert" -) - -func TestParseNpmDependenciesList(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "npm") - defer cleanUp() - dependenciesJson, err := os.ReadFile("dependencies.json") - assert.NoError(t, err) - var dependencies []buildinfo.Dependency - err = json.Unmarshal(dependenciesJson, &dependencies) - assert.NoError(t, err) - packageInfo := &biutils.PackageInfo{Name: "npmexmaple", Version: "0.1.0"} - looseEnvifyJsTokens := []*xrayUtils.GraphNode{{Id: "npm://loose-envify:1.4.0", Nodes: []*xrayUtils.GraphNode{{Id: "npm://js-tokens:4.0.0"}}}} - expectedTree := &xrayUtils.GraphNode{ - Id: "npm://npmexmaple:0.1.0", - Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://next-auth:4.22.1", - Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://react-dom:18.2.0", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://react:18.2.0", Nodes: looseEnvifyJsTokens}, - {Id: "npm://loose-envify:1.4.0", Nodes: []*xrayUtils.GraphNode{{Id: "npm://js-tokens:4.0.0"}}}, - {Id: "npm://scheduler:0.23.0", Nodes: looseEnvifyJsTokens}, - }}, - {Id: "npm://jose:4.14.4", Nodes: []*xrayUtils.GraphNode{}}, - {Id: "npm://react:18.2.0", Nodes: looseEnvifyJsTokens}, - {Id: "npm://uuid:8.3.2", Nodes: []*xrayUtils.GraphNode{}}, - {Id: "npm://openid-client:5.4.2", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://jose:4.14.4"}, - {Id: "npm://lru-cache:6.0.0", Nodes: []*xrayUtils.GraphNode{{Id: "npm://yallist:4.0.0"}}}, - {Id: "npm://oidc-token-hash:5.0.3", Nodes: []*xrayUtils.GraphNode{}}, - {Id: "npm://object-hash:2.2.0", Nodes: []*xrayUtils.GraphNode{}}, - }}, - {Id: "npm://next:12.0.10", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://react-dom:18.2.0", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://react:18.2.0", Nodes: looseEnvifyJsTokens}, - {Id: "npm://loose-envify:1.4.0", Nodes: []*xrayUtils.GraphNode{{Id: "npm://js-tokens:4.0.0"}}}, - {Id: "npm://scheduler:0.23.0", Nodes: looseEnvifyJsTokens}}}, - {Id: "npm://styled-jsx:5.0.0"}, - {Id: "npm://@next/swc-darwin-arm64:12.0.10"}, - {Id: "npm://react:18.2.0", Nodes: looseEnvifyJsTokens}, - {Id: "npm://@next/env:12.0.10"}, - {Id: "npm://caniuse-lite:1.0.30001486"}, - {Id: "npm://postcss:8.4.5", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://picocolors:1.0.0"}, - {Id: "npm://source-map-js:1.0.2"}, - {Id: "npm://nanoid:3.3.6"}, - }}, - {Id: "npm://use-subscription:1.5.1", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://object-assign:4.1.1"}, - }}, - }}, - {Id: "npm://@panva/hkdf:1.1.1"}, - {Id: "npm://preact-render-to-string:5.2.6", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://pretty-format:3.8.0"}, - {Id: "npm://preact:10.13.2"}, - }}, - {Id: "npm://preact:10.13.2"}, - {Id: "npm://@babel/runtime:7.21.5", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://regenerator-runtime:0.13.11"}, - }}, - {Id: "npm://cookie:0.5.0"}, - {Id: "npm://oauth:0.9.15"}, - }}, - {Id: "npm://next:12.0.10", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://react-dom:18.2.0", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://react:18.2.0"}, - {Id: "npm://scheduler:0.23.0"}}}, - {Id: "npm://styled-jsx:5.0.0"}, - {Id: "npm://@next/swc-darwin-arm64:12.0.10"}, - {Id: "npm://react:18.2.0"}, - {Id: "npm://@next/env:12.0.10"}, - {Id: "npm://caniuse-lite:1.0.30001486"}, - {Id: "npm://postcss:8.4.5", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://picocolors:1.0.0"}, - {Id: "npm://source-map-js:1.0.2"}, - {Id: "npm://nanoid:3.3.6"}, - }}, - {Id: "npm://use-subscription:1.5.1", Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://object-assign:4.1.1"}, - }}, - }}, - }, - } - - xrayDependenciesTree, uniqueDeps := parseNpmDependenciesList(dependencies, packageInfo) - equals := tests.CompareTree(expectedTree, xrayDependenciesTree) - if !equals { - t.Error("expected:", expectedTree.Nodes, "got:", xrayDependenciesTree.Nodes) - } - expectedUniqueDeps := []string{xrayDependenciesTree.Id} - for _, dep := range dependencies { - expectedUniqueDeps = append(expectedUniqueDeps, utils.NpmPackageTypeIdentifier+dep.Id) - } - assert.ElementsMatch(t, uniqueDeps, expectedUniqueDeps, "First is actual, Second is Expected") - -} - -func TestIgnoreScripts(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "npm-scripts") - defer cleanUp() - - // The package.json file contain a postinstall script running an "exit 1" command. - // Without the "--ignore-scripts" flag, the test will fail. - params := &utils.AuditBasicParams{} - _, _, err := BuildDependencyTree(params) - assert.NoError(t, err) -} diff --git a/xray/commands/audit/sca/nuget/nuget.go b/xray/commands/audit/sca/nuget/nuget.go deleted file mode 100644 index d7841cb28..000000000 --- a/xray/commands/audit/sca/nuget/nuget.go +++ /dev/null @@ -1,236 +0,0 @@ -package nuget - -import ( - "errors" - "fmt" - bidotnet "github.com/jfrog/build-info-go/build/utils/dotnet" - "github.com/jfrog/build-info-go/build/utils/dotnet/solution" - "github.com/jfrog/build-info-go/entities" - biutils "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/gofrog/datastructures" - "github.com/jfrog/jfrog-cli-core/v2/artifactory/commands/dotnet" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "io/fs" - "os" - "os/exec" - "path/filepath" - "strings" -) - -const ( - nugetPackageTypeIdentifier = "nuget://" - csprojFileSuffix = ".csproj" - packageReferenceSyntax = "PackageReference" - packagesConfigFileName = "packages.config" - installCommandName = "restore" - dotnetToolType = "dotnet" - nugetToolType = "nuget" - globalPackagesNotFoundErrorMessage = "could not find global packages path at:" -) - -func BuildDependencyTree(params utils.AuditParams) (dependencyTree []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - wd, err := os.Getwd() - if err != nil { - return - } - sol, err := solution.Load(wd, "", log.Logger) - if err != nil && !strings.Contains(err.Error(), globalPackagesNotFoundErrorMessage) { - // In older NuGet projects that utilize NuGet Cli and package.config, if the project is not installed, the solution.Load function raises an error because it cannot find global package paths. - // This issue is resolved by executing the 'nuget restore' command followed by running solution.Load again. Therefore, in this scenario, we need to proceed with this process. - return - } - - if isInstallRequired(params, sol) { - log.Info("Dependencies sources were not detected nor 'install' command provided. Running 'restore' command") - sol, err = runDotnetRestoreAndLoadSolution(params, wd) - if err != nil { - return - } - } - - buildInfo, err := sol.BuildInfo("", log.Logger) - if err != nil { - return - } - dependencyTree, uniqueDeps = parseNugetDependencyTree(buildInfo) - return -} - -// Verifies whether the execution of an 'install' command is necessary, either because the project isn't installed or because the user has specified an 'install' command -func isInstallRequired(params utils.AuditParams, sol solution.Solution) bool { - // If the user has specified an 'install' command, we proceed with executing the 'restore' command even if the project is already installed - // Additionally, if dependency sources were not identified during the construction of the Solution struct, the project will necessitate an 'install' - solDependencySourcesExists := len(sol.GetDependenciesSources()) > 0 - solProjectsExists := len(sol.GetProjects()) > 0 - return len(params.InstallCommandArgs()) > 0 || !solDependencySourcesExists || !solProjectsExists -} - -// Generates a temporary duplicate of the project to execute the 'install' command without impacting the original directory and establishing the JFrog configuration file for Artifactory resolution -// Additionally, re-loads the project's Solution so the dependencies sources will be identified -func runDotnetRestoreAndLoadSolution(params utils.AuditParams, originalWd string) (sol solution.Solution, err error) { - // Creating a temporary copy of the project in order to run 'install' command without effecting the original directory + creating the jfrog config for artifactory resolution - tmpWd, err := fileutils.CreateTempDir() - if err != nil { - err = fmt.Errorf("failed to create a temporary dir: %w", err) - return - } - defer func() { - err = errors.Join(err, fileutils.RemoveTempDir(tmpWd)) - }() - - err = biutils.CopyDir(originalWd, tmpWd, true, nil) - if err != nil { - err = fmt.Errorf("failed copying project to temp dir: %w", err) - return - } - - toolName := params.InstallCommandName() - if toolName == "" { - // Determine if the project is a NuGet or .NET project - toolName, err = getProjectToolName(originalWd) - if err != nil { - err = fmt.Errorf("failed while checking for the porject's tool type: %s", err.Error()) - return - } - } - - toolType := bidotnet.ConvertNameToToolType(toolName) - - var installCommandArgs []string - // Set up an Artifactory server as a resolution server if needed - depsRepo := params.DepsRepo() - if depsRepo != "" { - var serverDetails *config.ServerDetails - serverDetails, err = params.ServerDetails() - if err != nil { - err = fmt.Errorf("failed to get server details: %s", err.Error()) - return - } - - log.Info(fmt.Sprintf("Resolving dependencies from '%s' from repo '%s'", serverDetails.Url, depsRepo)) - - var configFile *os.File - configFile, err = dotnet.InitNewConfig(tmpWd, depsRepo, serverDetails, false) - if err != nil { - err = fmt.Errorf("failed while attempting to generate a configuration file for setting up Artifactory as a resolution server") - return - } - installCommandArgs = append(installCommandArgs, toolType.GetTypeFlagPrefix()+"configfile", configFile.Name()) - } - - err = runDotnetRestore(tmpWd, params, toolType, installCommandArgs) - if err != nil { - return - } - sol, err = solution.Load(tmpWd, "", log.Logger) - return -} - -// Detects if the project is utilizing either .NET CLI or NuGet CLI, prioritizing .NET CLI. -// Note: For multi-module projects, only one of these tools can be identified and will be uniformly applied across all modules. -func getProjectToolName(wd string) (toolName string, err error) { - projectConfigFilesPaths, err := getProjectConfigurationFilesPaths(wd) - if err != nil { - err = fmt.Errorf("failed while retrieving list of files in '%s': %s", wd, err.Error()) - return - } - - var packagesConfigFiles []string - for _, configFilePath := range projectConfigFilesPaths { - if strings.HasSuffix(configFilePath, csprojFileSuffix) { - var fileData []byte - fileData, err = os.ReadFile(configFilePath) - if err != nil { - err = fmt.Errorf("failed to read file '%s': %s", configFilePath, err.Error()) - return - } - - // If the .csproj file contains the syntax, it signifies the usage of .NET CLI as the tool type - if strings.Contains(string(fileData), packageReferenceSyntax) { - toolName = dotnetToolType - return - } - } else { - packagesConfigFiles = append(packagesConfigFiles, configFilePath) - } - } - - // If the syntax isn't found in any .csproj file but a packages.config file is present, it indicates that the tool type being used is the NuGet CLI - if len(packagesConfigFiles) > 0 { - toolName = nugetToolType - return - } - - err = errorutils.CheckErrorf("the project's tool type (.NET/NuGet CLI) couldn't be detected. Please execute the 'restore' command.\nNote: Certain entry points allow providing an 'install' command instead of manually executing it") - return -} - -// Returns a slice of absolute paths for the project's configuration files, strictly limited to .csproj files and packages.config files. -func getProjectConfigurationFilesPaths(wd string) (projectConfigFilesPaths []string, err error) { - err = filepath.WalkDir(wd, func(path string, d fs.DirEntry, innerErr error) error { - if innerErr != nil { - return fmt.Errorf("error has occured when trying to access or traverse the files system: %s", err.Error()) - } - - if strings.HasSuffix(path, csprojFileSuffix) || strings.HasSuffix(path, packagesConfigFileName) { - var absFilePath string - absFilePath, innerErr = filepath.Abs(path) - if innerErr != nil { - return fmt.Errorf("couldn't retrieve file's absolute path for './%s':%s", path, innerErr.Error()) - } - projectConfigFilesPaths = append(projectConfigFilesPaths, absFilePath) - } - return nil - }) - return -} - -func runDotnetRestore(wd string, params utils.AuditParams, toolType bidotnet.ToolchainType, commandExtraArgs []string) (err error) { - var completeCommandArgs []string - if len(params.InstallCommandArgs()) > 0 { - // If the user has specified an 'install' command, we execute the command that has been provided. - completeCommandArgs = append(completeCommandArgs, params.InstallCommandName()) - completeCommandArgs = append(completeCommandArgs, params.InstallCommandArgs()...) - } else { - completeCommandArgs = append(completeCommandArgs, toolType.String(), installCommandName) - } - - // We include the flag that allows resolution from an Artifactory server, if it exists. - completeCommandArgs = append(completeCommandArgs, commandExtraArgs...) - command := exec.Command(completeCommandArgs[0], completeCommandArgs[1:]...) - command.Dir = wd - output, err := command.CombinedOutput() - if err != nil { - err = errorutils.CheckErrorf("'dotnet restore' command failed: %s - %s", err.Error(), output) - } - return -} - -func parseNugetDependencyTree(buildInfo *entities.BuildInfo) (nodes []*xrayUtils.GraphNode, allUniqueDeps []string) { - uniqueDepsSet := datastructures.MakeSet[string]() - for _, module := range buildInfo.Modules { - treeMap := make(map[string][]string) - for _, dependency := range module.Dependencies { - dependencyId := nugetPackageTypeIdentifier + dependency.Id - parent := nugetPackageTypeIdentifier + dependency.RequestedBy[0][0] - if children, ok := treeMap[parent]; ok { - treeMap[parent] = append(children, dependencyId) - } else { - treeMap[parent] = []string{dependencyId} - } - } - dependencyTree, uniqueDeps := sca.BuildXrayDependencyTree(treeMap, nugetPackageTypeIdentifier+module.Id) - nodes = append(nodes, dependencyTree) - for _, uniqueDep := range uniqueDeps { - uniqueDepsSet.Add(uniqueDep) - } - } - allUniqueDeps = uniqueDepsSet.ToSlice() - return -} diff --git a/xray/commands/audit/sca/nuget/nuget_test.go b/xray/commands/audit/sca/nuget/nuget_test.go deleted file mode 100644 index c4b604a07..000000000 --- a/xray/commands/audit/sca/nuget/nuget_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package nuget - -import ( - "encoding/json" - "github.com/jfrog/build-info-go/build/utils/dotnet/solution" - "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - xrayUtils2 "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "os" - "path/filepath" - "testing" - - "github.com/jfrog/build-info-go/entities" - "github.com/jfrog/jfrog-cli-core/v2/utils/tests" - "github.com/stretchr/testify/assert" -) - -func TestBuildNugetDependencyTree(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "nuget") - defer cleanUp() - dependenciesJson, err := os.ReadFile("dependencies.json") - assert.NoError(t, err) - - var dependencies *entities.BuildInfo - err = json.Unmarshal(dependenciesJson, &dependencies) - assert.NoError(t, err) - expectedUniqueDeps := []string{ - nugetPackageTypeIdentifier + "Microsoft.Net.Http:2.2.29", - nugetPackageTypeIdentifier + "Microsoft.Bcl:1.1.10", - nugetPackageTypeIdentifier + "Microsoft.Bcl.Build:1.0.14", - nugetPackageTypeIdentifier + "Newtonsoft.Json:11.0.2", - nugetPackageTypeIdentifier + "NUnit:3.10.1", - nugetPackageTypeIdentifier + "bootstrap:4.1.1", - nugetPackageTypeIdentifier + "popper.js:1.14.0", - nugetPackageTypeIdentifier + "jQuery:3.0.0", - nugetPackageTypeIdentifier + "MsbuildExample", - nugetPackageTypeIdentifier + "MsbuildLibrary", - } - xrayDependenciesTree, uniqueDeps := parseNugetDependencyTree(dependencies) - assert.ElementsMatch(t, uniqueDeps, expectedUniqueDeps, "First is actual, Second is Expected") - expectedTreeJson, err := os.ReadFile("expectedTree.json") - assert.NoError(t, err) - - var expectedTrees *[]xrayUtils.GraphNode - err = json.Unmarshal(expectedTreeJson, &expectedTrees) - assert.NoError(t, err) - - for i := range *expectedTrees { - expectedTree := &(*expectedTrees)[i] - assert.True(t, tests.CompareTree(expectedTree, xrayDependenciesTree[i]), "expected:", expectedTree.Nodes, "got:", xrayDependenciesTree[i].Nodes) - } -} - -func TestGetProjectToolName(t *testing.T) { - testCases := []struct { - testProjectName string - expectedOutput string - }{ - {testProjectName: "dotnet-single", expectedOutput: "dotnet"}, - {testProjectName: "dotnet-single", expectedOutput: "nuget"}, - {testProjectName: "dotnet-multi", expectedOutput: "dotnet"}, - } - - for _, testcase := range testCases { - tempDirPath, createTempDirCallback := tests.CreateTempDirWithCallbackAndAssert(t) - defer createTempDirCallback() - dotnetProjectPath := filepath.Join("..", "..", "..", "testdata", "dotnet-projects", testcase.testProjectName) - assert.NoError(t, utils.CopyDir(dotnetProjectPath, tempDirPath, true, nil)) - - // This phase designates the project as an 'old NuGet project' utilizing packages.config instead of for dependency definition - if testcase.expectedOutput == "nuget" { - assert.NoError(t, os.Remove(filepath.Join(tempDirPath, testcase.testProjectName+".csproj"))) - tempFile, err := os.Create(filepath.Join(tempDirPath, "packages.config")) - assert.NoError(t, err) - defer func() { - assert.NoError(t, tempFile.Close()) - }() - } - - toolName, err := getProjectToolName(tempDirPath) - assert.NoError(t, err) - assert.Equal(t, testcase.expectedOutput, toolName) - } - - // Verifies for errors if neither .csproj files nor packages.config files were detected - emptyProject, createTempDirCallback := tests.CreateTempDirWithCallbackAndAssert(t) - defer createTempDirCallback() - toolName, err := getProjectToolName(emptyProject) - assert.Empty(t, toolName) - assert.Error(t, err) -} - -func TestGetProjectConfigurationFilesPaths(t *testing.T) { - dotnetProjectPath, err := filepath.Abs(filepath.Join("..", "..", "..", "testdata", "dotnet-projects")) - assert.NoError(t, err) - - testCases := []struct { - testProjectPath string - expectedOutput []string - }{ - { - testProjectPath: filepath.Join(dotnetProjectPath, "dotnet-single"), - expectedOutput: []string{ - filepath.Join(dotnetProjectPath, "dotnet-single", "dotnet-single.csproj"), - }, - }, - { - testProjectPath: filepath.Join(dotnetProjectPath, "dotnet-multi"), - expectedOutput: []string{ - filepath.Join(dotnetProjectPath, "dotnet-multi", "ClassLibrary1", "ClassLibrary1.csproj"), - filepath.Join(dotnetProjectPath, "dotnet-multi", "TestApp1", "TestApp1.csproj"), - }, - }, - } - - for _, testcase := range testCases { - var projectFiles []string - projectFiles, err = getProjectConfigurationFilesPaths(testcase.testProjectPath) - assert.NoError(t, err) - assert.Equal(t, testcase.expectedOutput, projectFiles) - } -} - -func TestRunDotnetRestoreAndLoadSolution(t *testing.T) { - projectsToCheck := []string{"dotnet-single", "dotnet-multi"} - for _, projectName := range projectsToCheck { - tempDirPath, createTempDirCallback := tests.CreateTempDirWithCallbackAndAssert(t) - defer createTempDirCallback() - dotnetProjectPath := filepath.Join("..", "..", "..", "testdata", "dotnet-projects", projectName) - assert.NoError(t, utils.CopyDir(dotnetProjectPath, tempDirPath, true, nil)) - - sol, err := solution.Load(tempDirPath, "", log.Logger) - assert.NoError(t, err) - assert.Empty(t, sol.GetProjects()) - assert.Empty(t, sol.GetDependenciesSources()) - - params := &xrayUtils2.AuditBasicParams{} - sol, err = runDotnetRestoreAndLoadSolution(params, tempDirPath) - assert.NoError(t, err) - assert.NotEmpty(t, sol.GetProjects()) - assert.NotEmpty(t, sol.GetDependenciesSources()) - } -} diff --git a/xray/commands/audit/sca/python/python.go b/xray/commands/audit/sca/python/python.go deleted file mode 100644 index 1663ba0c0..000000000 --- a/xray/commands/audit/sca/python/python.go +++ /dev/null @@ -1,282 +0,0 @@ -package python - -import ( - "errors" - "fmt" - biutils "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/build-info-go/utils/pythonutils" - "github.com/jfrog/gofrog/datastructures" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - utils "github.com/jfrog/jfrog-cli-core/v2/utils/python" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" -) - -const ( - pythonPackageTypeIdentifier = "pypi://" -) - -type AuditPython struct { - Server *config.ServerDetails - Tool pythonutils.PythonTool - RemotePypiRepo string - PipRequirementsFile string -} - -func BuildDependencyTree(auditPython *AuditPython) (dependencyTree []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - dependenciesGraph, directDependenciesList, err := getDependencies(auditPython) - if err != nil { - return - } - directDependencies := []*xrayUtils.GraphNode{} - uniqueDepsSet := datastructures.MakeSet[string]() - for _, rootDep := range directDependenciesList { - directDependency := &xrayUtils.GraphNode{ - Id: pythonPackageTypeIdentifier + rootDep, - Nodes: []*xrayUtils.GraphNode{}, - } - populatePythonDependencyTree(directDependency, dependenciesGraph, uniqueDepsSet) - directDependencies = append(directDependencies, directDependency) - } - root := &xrayUtils.GraphNode{ - Id: "root", - Nodes: directDependencies, - } - dependencyTree = []*xrayUtils.GraphNode{root} - uniqueDeps = uniqueDepsSet.ToSlice() - return -} - -func getDependencies(auditPython *AuditPython) (dependenciesGraph map[string][]string, directDependencies []string, err error) { - wd, err := os.Getwd() - if errorutils.CheckError(err) != nil { - return - } - - // Create temp dir to run all work outside users working directory - tempDirPath, err := fileutils.CreateTempDir() - if err != nil { - return - } - - err = os.Chdir(tempDirPath) - if errorutils.CheckError(err) != nil { - return - } - - defer func() { - err = errors.Join( - err, - errorutils.CheckError(os.Chdir(wd)), - fileutils.RemoveTempDir(tempDirPath), - ) - }() - - err = biutils.CopyDir(wd, tempDirPath, true, nil) - if err != nil { - return - } - - restoreEnv, err := runPythonInstall(auditPython) - defer func() { - err = errors.Join(err, restoreEnv()) - }() - if err != nil { - return - } - - localDependenciesPath, err := config.GetJfrogDependenciesPath() - if err != nil { - return - } - dependenciesGraph, directDependencies, err = pythonutils.GetPythonDependencies(auditPython.Tool, tempDirPath, localDependenciesPath) - if err != nil { - sca.LogExecutableVersion("python") - sca.LogExecutableVersion(string(auditPython.Tool)) - } - return -} - -func runPythonInstall(auditPython *AuditPython) (restoreEnv func() error, err error) { - switch auditPython.Tool { - case pythonutils.Pip: - return installPipDeps(auditPython) - case pythonutils.Pipenv: - return installPipenvDeps(auditPython) - case pythonutils.Poetry: - return installPoetryDeps(auditPython) - } - return -} - -func installPoetryDeps(auditPython *AuditPython) (restoreEnv func() error, err error) { - restoreEnv = func() error { - return nil - } - if auditPython.RemotePypiRepo != "" { - rtUrl, username, password, err := utils.GetPypiRepoUrlWithCredentials(auditPython.Server, auditPython.RemotePypiRepo) - if err != nil { - return restoreEnv, err - } - if password != "" { - err = utils.ConfigPoetryRepo(rtUrl.Scheme+"://"+rtUrl.Host+rtUrl.Path, username, password, auditPython.RemotePypiRepo) - if err != nil { - return restoreEnv, err - } - } - } - // Run 'poetry install' - return restoreEnv, executeCommand("poetry", "install") -} - -func installPipenvDeps(auditPython *AuditPython) (restoreEnv func() error, err error) { - // Set virtualenv path to venv dir - err = os.Setenv("WORKON_HOME", ".jfrog") - if err != nil { - return - } - restoreEnv = func() error { - return os.Unsetenv("WORKON_HOME") - } - if auditPython.RemotePypiRepo != "" { - return restoreEnv, runPipenvInstallFromRemoteRegistry(auditPython.Server, auditPython.RemotePypiRepo) - } - // Run 'pipenv install -d' - return restoreEnv, executeCommand("pipenv", "install", "-d") -} - -func installPipDeps(auditPython *AuditPython) (restoreEnv func() error, err error) { - restoreEnv, err = SetPipVirtualEnvPath() - if err != nil { - return - } - - remoteUrl := "" - if auditPython.RemotePypiRepo != "" { - remoteUrl, err = utils.GetPypiRepoUrl(auditPython.Server, auditPython.RemotePypiRepo) - if err != nil { - return - } - } - pipInstallArgs := getPipInstallArgs(auditPython.PipRequirementsFile, remoteUrl) - err = executeCommand("python", pipInstallArgs...) - if err != nil && auditPython.PipRequirementsFile == "" { - pipInstallArgs = getPipInstallArgs("requirements.txt", remoteUrl) - reqErr := executeCommand("python", pipInstallArgs...) - if reqErr != nil { - // Return Pip install error and log the requirements fallback error. - log.Debug(reqErr.Error()) - } else { - err = nil - } - } - return -} - -func executeCommand(executable string, args ...string) error { - installCmd := exec.Command(executable, args...) - maskedCmdString := coreutils.GetMaskedCommandString(installCmd) - log.Debug("Running", maskedCmdString) - output, err := installCmd.CombinedOutput() - if err != nil { - sca.LogExecutableVersion(executable) - return errorutils.CheckErrorf("%q command failed: %s - %s", maskedCmdString, err.Error(), output) - } - return nil -} - -func getPipInstallArgs(requirementsFile, remoteUrl string) []string { - args := []string{"-m", "pip", "install"} - if requirementsFile == "" { - // Run 'pip install .' - args = append(args, ".") - } else { - // Run pip 'install -r requirements ' - args = append(args, "-r", requirementsFile) - } - if remoteUrl != "" { - args = append(args, utils.GetPypiRemoteRegistryFlag(pythonutils.Pip), remoteUrl) - } - return args -} - -func runPipenvInstallFromRemoteRegistry(server *config.ServerDetails, depsRepoName string) (err error) { - rtUrl, err := utils.GetPypiRepoUrl(server, depsRepoName) - if err != nil { - return err - } - args := []string{"install", "-d", utils.GetPypiRemoteRegistryFlag(pythonutils.Pipenv), rtUrl} - return executeCommand("pipenv", args...) -} - -// Execute virtualenv command: "virtualenv venvdir" / "python3 -m venv venvdir" and set path -func SetPipVirtualEnvPath() (restoreEnv func() error, err error) { - restoreEnv = func() error { - return nil - } - venvdirName := "venvdir" - var cmdArgs []string - pythonPath, windowsPyArg := pythonutils.GetPython3Executable() - if windowsPyArg != "" { - // Add '-3' arg for windows 'py -3' command - cmdArgs = append(cmdArgs, windowsPyArg) - } - cmdArgs = append(cmdArgs, "-m", "venv", venvdirName) - err = executeCommand(pythonPath, cmdArgs...) - if err != nil { - // Failed running 'python -m venv', trying to run 'virtualenv' - log.Debug("Failed running python venv:", err.Error()) - err = executeCommand("virtualenv", "-p", pythonPath, venvdirName) - if err != nil { - return - } - } - - // Keep original value of 'PATH'. - origPathValue := os.Getenv("PATH") - venvPath, err := filepath.Abs(venvdirName) - if err != nil { - return - } - var venvBinPath string - if runtime.GOOS == "windows" { - venvBinPath = filepath.Join(venvPath, "Scripts") - } else { - venvBinPath = filepath.Join(venvPath, "bin") - } - err = os.Setenv("PATH", fmt.Sprintf("%s%c%s", venvBinPath, os.PathListSeparator, origPathValue)) - if err != nil { - return - } - restoreEnv = func() error { - return os.Setenv("PATH", origPathValue) - } - return -} - -func populatePythonDependencyTree(currNode *xrayUtils.GraphNode, dependenciesGraph map[string][]string, uniqueDepsSet *datastructures.Set[string]) { - if currNode.NodeHasLoop() { - return - } - uniqueDepsSet.Add(currNode.Id) - currDepChildren := dependenciesGraph[strings.TrimPrefix(currNode.Id, pythonPackageTypeIdentifier)] - // Recursively create & append all node's dependencies. - for _, dependency := range currDepChildren { - childNode := &xrayUtils.GraphNode{ - Id: pythonPackageTypeIdentifier + dependency, - Nodes: []*xrayUtils.GraphNode{}, - Parent: currNode, - } - currNode.Nodes = append(currNode.Nodes, childNode) - populatePythonDependencyTree(childNode, dependenciesGraph, uniqueDepsSet) - } -} diff --git a/xray/commands/audit/sca/python/python_test.go b/xray/commands/audit/sca/python/python_test.go deleted file mode 100644 index b5bc99fa8..000000000 --- a/xray/commands/audit/sca/python/python_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package python - -import ( - "path/filepath" - "testing" - - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - - "github.com/jfrog/build-info-go/utils/pythonutils" - "github.com/stretchr/testify/assert" -) - -func TestBuildPipDependencyListSetuppy(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, filepath.Join("pip-project", "setuppyproject")) - defer cleanUp() - // Run getModulesDependencyTrees - rootNode, uniqueDeps, err := BuildDependencyTree(&AuditPython{Tool: pythonutils.Pip}) - assert.NoError(t, err) - assert.Contains(t, uniqueDeps, pythonPackageTypeIdentifier+"pexpect:4.8.0") - assert.Contains(t, uniqueDeps, pythonPackageTypeIdentifier+"ptyprocess:0.7.0") - assert.Contains(t, uniqueDeps, pythonPackageTypeIdentifier+"pip-example:1.2.3") - assert.Len(t, rootNode, 1) - if len(rootNode) > 0 { - assert.NotEmpty(t, rootNode[0].Nodes) - if rootNode[0].Nodes != nil { - // Test direct dependency - directDepNode := sca.GetAndAssertNode(t, rootNode[0].Nodes, "pip-example:1.2.3") - // Test child module - childNode := sca.GetAndAssertNode(t, directDepNode.Nodes, "pexpect:4.8.0") - // Test sub child module - sca.GetAndAssertNode(t, childNode.Nodes, "ptyprocess:0.7.0") - } - } -} - -func TestPipDependencyListRequirementsFallback(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, filepath.Join("pip-project", "requirementsproject")) - defer cleanUp() - // No requirements file field specified, expect the command to use the fallback 'pip install -r requirements.txt' command - rootNode, uniqueDeps, err := BuildDependencyTree(&AuditPython{Tool: pythonutils.Pip}) - assert.NoError(t, err) - assert.Contains(t, uniqueDeps, pythonPackageTypeIdentifier+"pexpect:4.7.0") - assert.Contains(t, uniqueDeps, pythonPackageTypeIdentifier+"ptyprocess:0.7.0") - assert.Len(t, rootNode, 1) - if assert.GreaterOrEqual(t, len(rootNode[0].Nodes), 2) { - childNode := sca.GetAndAssertNode(t, rootNode[0].Nodes, "pexpect:4.7.0") - if childNode != nil { - // Test child module - sca.GetAndAssertNode(t, childNode.Nodes, "ptyprocess:0.7.0") - } - } -} - -func TestBuildPipDependencyListRequirements(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, filepath.Join("pip-project", "requirementsproject")) - defer cleanUp() - // Run getModulesDependencyTrees - rootNode, uniqueDeps, err := BuildDependencyTree(&AuditPython{Tool: pythonutils.Pip, PipRequirementsFile: "requirements.txt"}) - assert.NoError(t, err) - assert.Contains(t, uniqueDeps, pythonPackageTypeIdentifier+"pexpect:4.7.0") - assert.Contains(t, uniqueDeps, pythonPackageTypeIdentifier+"ptyprocess:0.7.0") - assert.Len(t, rootNode, 1) - if len(rootNode) > 0 { - assert.NotEmpty(t, rootNode[0].Nodes) - if rootNode[0].Nodes != nil { - // Test root module - directDepNode := sca.GetAndAssertNode(t, rootNode[0].Nodes, "pexpect:4.7.0") - // Test child module - sca.GetAndAssertNode(t, directDepNode.Nodes, "ptyprocess:0.7.0") - } - } -} - -func TestBuildPipenvDependencyList(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "pipenv-project") - defer cleanUp() - expectedPipenvUniqueDeps := []string{ - pythonPackageTypeIdentifier + "toml:0.10.2", - pythonPackageTypeIdentifier + "pexpect:4.8.0", - pythonPackageTypeIdentifier + "ptyprocess:0.7.0", - } - // Run getModulesDependencyTrees - rootNode, uniqueDeps, err := BuildDependencyTree(&AuditPython{Tool: pythonutils.Pipenv}) - if err != nil { - t.Fatal(err) - } - assert.ElementsMatch(t, uniqueDeps, expectedPipenvUniqueDeps, "First is actual, Second is Expected") - assert.Len(t, rootNode, 1) - if len(rootNode) > 0 { - assert.NotEmpty(t, rootNode[0].Nodes) - // Test child module - childNode := sca.GetAndAssertNode(t, rootNode[0].Nodes, "pexpect:4.8.0") - // Test sub child module - if assert.NotNil(t, childNode) { - sca.GetAndAssertNode(t, childNode.Nodes, "ptyprocess:0.7.0") - } - } -} - -func TestBuildPoetryDependencyList(t *testing.T) { - // Create and change directory to test workspace - _, cleanUp := sca.CreateTestWorkspace(t, "poetry-project") - defer cleanUp() - expectedPoetryUniqueDeps := []string{ - pythonPackageTypeIdentifier + "wcwidth:0.2.8", - pythonPackageTypeIdentifier + "colorama:0.4.6", - pythonPackageTypeIdentifier + "packaging:23.2", - pythonPackageTypeIdentifier + "python:", - pythonPackageTypeIdentifier + "pluggy:0.13.1", - pythonPackageTypeIdentifier + "py:1.11.0", - pythonPackageTypeIdentifier + "atomicwrites:1.4.1", - pythonPackageTypeIdentifier + "attrs:23.1.0", - pythonPackageTypeIdentifier + "more-itertools:10.1.0", - pythonPackageTypeIdentifier + "numpy:1.26.1", - pythonPackageTypeIdentifier + "pytest:5.4.3", - } - // Run getModulesDependencyTrees - rootNode, uniqueDeps, err := BuildDependencyTree(&AuditPython{Tool: pythonutils.Poetry}) - if err != nil { - t.Fatal(err) - } - assert.ElementsMatch(t, uniqueDeps, expectedPoetryUniqueDeps, "First is actual, Second is Expected") - assert.Len(t, rootNode, 1) - if len(rootNode) > 0 { - assert.NotEmpty(t, rootNode[0].Nodes) - // Test child module - childNode := sca.GetAndAssertNode(t, rootNode[0].Nodes, "pytest:5.4.3") - // Test sub child module - if assert.NotNil(t, childNode) { - sca.GetAndAssertNode(t, childNode.Nodes, "packaging:23.2") - } - } -} - -func TestGetPipInstallArgs(t *testing.T) { - assert.Equal(t, []string{"-m", "pip", "install", "."}, getPipInstallArgs("", "")) - assert.Equal(t, []string{"-m", "pip", "install", "-r", "requirements.txt"}, getPipInstallArgs("requirements.txt", "")) - - assert.Equal(t, []string{"-m", "pip", "install", ".", "-i", "https://user@pass:remote.url/repo"}, getPipInstallArgs("", "https://user@pass:remote.url/repo")) - assert.Equal(t, []string{"-m", "pip", "install", "-r", "requirements.txt", "-i", "https://user@pass:remote.url/repo"}, getPipInstallArgs("requirements.txt", "https://user@pass:remote.url/repo")) -} diff --git a/xray/commands/audit/sca/yarn/yarn.go b/xray/commands/audit/sca/yarn/yarn.go deleted file mode 100644 index 57bb24d18..000000000 --- a/xray/commands/audit/sca/yarn/yarn.go +++ /dev/null @@ -1,217 +0,0 @@ -package yarn - -import ( - "errors" - "fmt" - "github.com/jfrog/build-info-go/build" - biutils "github.com/jfrog/build-info-go/build/utils" - "github.com/jfrog/gofrog/version" - "github.com/jfrog/jfrog-cli-core/v2/artifactory/commands/yarn" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/ioutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "path/filepath" -) - -const ( - // Do not execute any scripts defined in the project package.json and its dependencies. - v1IgnoreScriptsFlag = "--ignore-scripts" - // Run yarn install without printing installation log. - v1SilentFlag = "--silent" - // Disable interactive prompts, like when there’s an invalid version of a dependency. - v1NonInteractiveFlag = "--non-interactive" - // Ignores any build scripts - v2SkipBuildFlag = "--skip-builds" - // Skips linking and fetch only packages that are missing from yarn.lock file - v3UpdateLockfileFlag = "--mode=update-lockfile" - // Ignores any build scripts - v3SkipBuildFlag = "--mode=skip-build" - yarnV2Version = "2.0.0" - yarnV3Version = "3.0.0" - yarnV4Version = "4.0.0" - nodeModulesRepoName = "node_modules" -) - -func BuildDependencyTree(params utils.AuditParams) (dependencyTrees []*xrayUtils.GraphNode, uniqueDeps []string, err error) { - currentDir, err := coreutils.GetWorkingDirectory() - if err != nil { - return - } - executablePath, err := biutils.GetYarnExecutable() - if errorutils.CheckError(err) != nil { - return - } - - packageInfo, err := biutils.ReadPackageInfoFromPackageJsonIfExists(currentDir, nil) - if errorutils.CheckError(err) != nil { - return - } - - installRequired, err := isInstallRequired(currentDir, params.InstallCommandArgs()) - if err != nil { - return - } - - if installRequired { - err = configureYarnResolutionServerAndRunInstall(params, currentDir, executablePath) - if err != nil { - err = fmt.Errorf("failed to configure an Artifactory resolution server or running and install command: %s", err.Error()) - return - } - } - - // Calculate Yarn dependencies - dependenciesMap, root, err := biutils.GetYarnDependencies(executablePath, currentDir, packageInfo, log.Logger) - if err != nil { - return - } - // Parse the dependencies into Xray dependency tree format - dependencyTree, uniqueDeps := parseYarnDependenciesMap(dependenciesMap, getXrayDependencyId(root)) - dependencyTrees = []*xrayUtils.GraphNode{dependencyTree} - return -} - -// Sets up Artifactory server configurations for dependency resolution, if such were provided by the user. -// Executes the user's 'install' command or a default 'install' command if none was specified. -func configureYarnResolutionServerAndRunInstall(params utils.AuditParams, curWd, yarnExecPath string) (err error) { - depsRepo := params.DepsRepo() - if depsRepo == "" { - // Run install without configuring an Artifactory server - return runYarnInstallAccordingToVersion(curWd, yarnExecPath, params.InstallCommandArgs()) - } - - executableYarnVersion, err := biutils.GetVersion(yarnExecPath, curWd) - if err != nil { - return - } - // Checking if the current yarn version is Yarn V1 ro Yarn v4, and if so - abort. Resolving dependencies from artifactory is currently not supported for Yarn V1 and V4 - yarnVersion := version.NewVersion(executableYarnVersion) - if yarnVersion.Compare(yarnV2Version) > 0 || yarnVersion.Compare(yarnV4Version) <= 0 { - err = errors.New("resolving Yarn dependencies from Artifactory is currently not supported for Yarn V1 and Yarn V4. The current Yarn version is: " + executableYarnVersion) - return - } - - var serverDetails *config.ServerDetails - serverDetails, err = params.ServerDetails() - if err != nil { - err = fmt.Errorf("failed to get server details while building yarn dependency tree: %s", err.Error()) - return - } - - // If an Artifactory resolution repository was provided we first configure to resolve from it and only then run the 'install' command - restoreYarnrcFunc, err := ioutils.BackupFile(filepath.Join(curWd, yarn.YarnrcFileName), yarn.YarnrcBackupFileName) - if err != nil { - return - } - - registry, repoAuthIdent, err := yarn.GetYarnAuthDetails(serverDetails, depsRepo) - if err != nil { - err = errors.Join(err, restoreYarnrcFunc()) - return - } - - backupEnvMap, err := yarn.ModifyYarnConfigurations(yarnExecPath, registry, repoAuthIdent) - if err != nil { - if len(backupEnvMap) > 0 { - err = errors.Join(err, yarn.RestoreConfigurationsFromBackup(backupEnvMap, restoreYarnrcFunc)) - } else { - err = errors.Join(err, restoreYarnrcFunc()) - } - return - } - defer func() { - err = errors.Join(err, yarn.RestoreConfigurationsFromBackup(backupEnvMap, restoreYarnrcFunc)) - }() - - log.Info(fmt.Sprintf("Resolving dependencies from '%s' from repo '%s'", serverDetails.Url, depsRepo)) - return runYarnInstallAccordingToVersion(curWd, yarnExecPath, params.InstallCommandArgs()) -} - -func isInstallRequired(currentDir string, installCommandArgs []string) (installRequired bool, err error) { - yarnLockExits, err := fileutils.IsFileExists(filepath.Join(currentDir, yarn.YarnLockFileName), false) - if err != nil { - err = fmt.Errorf("failed to check the existence of '%s' file: %s", filepath.Join(currentDir, yarn.YarnLockFileName), err.Error()) - return - } - - // We verify the project's installation status by examining the presence of the yarn.lock file and the presence of an installation command provided by the user. - // Notice!: If alterations are made manually in the package.json file, it necessitates a manual update to the yarn.lock file as well. - if len(installCommandArgs) > 0 || !yarnLockExits { - installRequired = true - } - return -} - -// Executes the user-defined 'install' command; if absent, defaults to running an 'install' command with specific flags suited to the current yarn version. -func runYarnInstallAccordingToVersion(curWd, yarnExecPath string, installCommandArgs []string) (err error) { - // If the installCommandArgs in the params is not empty, it signifies that the user has provided it, and 'install' is already included as one of the arguments - installCommandProvidedFromUser := len(installCommandArgs) != 0 - - // Upon receiving a user-provided 'install' command, we execute the command exactly as provided - if installCommandProvidedFromUser { - return build.RunYarnCommand(yarnExecPath, curWd, installCommandArgs...) - } - - installCommandArgs = []string{"install"} - executableVersionStr, err := biutils.GetVersion(yarnExecPath, curWd) - if err != nil { - return - } - - yarnVersion := version.NewVersion(executableVersionStr) - isYarnV1 := yarnVersion.Compare(yarnV2Version) > 0 - - if isYarnV1 { - // When executing 'yarn install...', the node_modules directory is automatically generated. - // If it did not exist prior to the 'install' command, we aim to remove it. - nodeModulesFullPath := filepath.Join(curWd, nodeModulesRepoName) - var nodeModulesDirExists bool - nodeModulesDirExists, err = fileutils.IsDirExists(nodeModulesFullPath, false) - if err != nil { - err = fmt.Errorf("failed while checking for existence of node_modules directory: %s", err.Error()) - return - } - if !nodeModulesDirExists { - defer func() { - err = errors.Join(err, fileutils.RemoveTempDir(nodeModulesFullPath)) - }() - } - - installCommandArgs = append(installCommandArgs, v1IgnoreScriptsFlag, v1SilentFlag, v1NonInteractiveFlag) - } else { - // Checks if the version is V2 or V3 to insert the correct flags - if yarnVersion.Compare(yarnV3Version) > 0 { - installCommandArgs = append(installCommandArgs, v2SkipBuildFlag) - } else { - installCommandArgs = append(installCommandArgs, v3UpdateLockfileFlag, v3SkipBuildFlag) - } - } - err = build.RunYarnCommand(yarnExecPath, curWd, installCommandArgs...) - return -} - -// Parse the dependencies into a Xray dependency tree format -func parseYarnDependenciesMap(dependencies map[string]*biutils.YarnDependency, rootXrayId string) (*xrayUtils.GraphNode, []string) { - treeMap := make(map[string][]string) - for _, dependency := range dependencies { - xrayDepId := getXrayDependencyId(dependency) - var subDeps []string - for _, subDepPtr := range dependency.Details.Dependencies { - subDeps = append(subDeps, getXrayDependencyId(dependencies[biutils.GetYarnDependencyKeyFromLocator(subDepPtr.Locator)])) - } - if len(subDeps) > 0 { - treeMap[xrayDepId] = subDeps - } - } - return sca.BuildXrayDependencyTree(treeMap, rootXrayId) -} - -func getXrayDependencyId(yarnDependency *biutils.YarnDependency) string { - return utils.NpmPackageTypeIdentifier + yarnDependency.Name() + ":" + yarnDependency.Details.Version -} diff --git a/xray/commands/audit/sca/yarn/yarn_test.go b/xray/commands/audit/sca/yarn/yarn_test.go deleted file mode 100644 index f1a696b38..000000000 --- a/xray/commands/audit/sca/yarn/yarn_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package yarn - -import ( - "github.com/jfrog/build-info-go/build" - biutils "github.com/jfrog/build-info-go/build/utils" - utils2 "github.com/jfrog/build-info-go/utils" - "github.com/jfrog/jfrog-cli-core/v2/utils/tests" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "github.com/stretchr/testify/assert" - "path/filepath" - "testing" -) - -func TestParseYarnDependenciesList(t *testing.T) { - yarnDependencies := map[string]*biutils.YarnDependency{ - "pack1@npm:1.0.0": {Value: "pack1@npm:1.0.0", Details: biutils.YarnDepDetails{Version: "1.0.0", Dependencies: []biutils.YarnDependencyPointer{{Locator: "pack4@npm:4.0.0"}}}}, - "pack2@npm:2.0.0": {Value: "pack2@npm:2.0.0", Details: biutils.YarnDepDetails{Version: "2.0.0", Dependencies: []biutils.YarnDependencyPointer{{Locator: "pack4@npm:4.0.0"}, {Locator: "pack5@npm:5.0.0"}}}}, - "@jfrog/pack3@npm:3.0.0": {Value: "@jfrog/pack3@npm:3.0.0", Details: biutils.YarnDepDetails{Version: "3.0.0", Dependencies: []biutils.YarnDependencyPointer{{Locator: "pack1@virtual:c192f6b3b32cd5d11a443144e162ec3bc#npm:1.0.0"}, {Locator: "pack2@npm:2.0.0"}}}}, - "pack4@npm:4.0.0": {Value: "pack4@npm:4.0.0", Details: biutils.YarnDepDetails{Version: "4.0.0"}}, - "pack5@npm:5.0.0": {Value: "pack5@npm:5.0.0", Details: biutils.YarnDepDetails{Version: "5.0.0", Dependencies: []biutils.YarnDependencyPointer{{Locator: "pack2@npm:2.0.0"}}}}, - } - - rootXrayId := utils.NpmPackageTypeIdentifier + "@jfrog/pack3:3.0.0" - expectedTree := &xrayUtils.GraphNode{ - Id: rootXrayId, - Nodes: []*xrayUtils.GraphNode{ - {Id: utils.NpmPackageTypeIdentifier + "pack1:1.0.0", - Nodes: []*xrayUtils.GraphNode{ - {Id: utils.NpmPackageTypeIdentifier + "pack4:4.0.0", - Nodes: []*xrayUtils.GraphNode{}}, - }}, - {Id: utils.NpmPackageTypeIdentifier + "pack2:2.0.0", - Nodes: []*xrayUtils.GraphNode{ - {Id: utils.NpmPackageTypeIdentifier + "pack4:4.0.0", - Nodes: []*xrayUtils.GraphNode{}}, - {Id: utils.NpmPackageTypeIdentifier + "pack5:5.0.0", - Nodes: []*xrayUtils.GraphNode{}}, - }}, - }, - } - expectedUniqueDeps := []string{ - utils.NpmPackageTypeIdentifier + "pack1:1.0.0", - utils.NpmPackageTypeIdentifier + "pack2:2.0.0", - utils.NpmPackageTypeIdentifier + "pack4:4.0.0", - utils.NpmPackageTypeIdentifier + "pack5:5.0.0", - utils.NpmPackageTypeIdentifier + "@jfrog/pack3:3.0.0", - } - - xrayDependenciesTree, uniqueDeps := parseYarnDependenciesMap(yarnDependencies, rootXrayId) - assert.ElementsMatch(t, uniqueDeps, expectedUniqueDeps, "First is actual, Second is Expected") - assert.True(t, tests.CompareTree(expectedTree, xrayDependenciesTree), "expected:", expectedTree.Nodes, "got:", xrayDependenciesTree.Nodes) -} - -func TestIsInstallRequired(t *testing.T) { - tempDirPath, createTempDirCallback := tests.CreateTempDirWithCallbackAndAssert(t) - defer createTempDirCallback() - yarnProjectPath := filepath.Join("..", "..", "..", "testdata", "yarn-project") - assert.NoError(t, utils2.CopyDir(yarnProjectPath, tempDirPath, true, nil)) - installRequired, err := isInstallRequired(tempDirPath, []string{}) - assert.NoError(t, err) - assert.True(t, installRequired) - executablePath, err := biutils.GetYarnExecutable() - assert.NoError(t, err) - - // We provide a user defined 'install' command and expect to get 'true' as an answer - installRequired, err = isInstallRequired(tempDirPath, []string{"yarn", "install"}) - assert.NoError(t, err) - assert.True(t, installRequired) - - // We install the project so yarn.lock will be created and expect to get 'false' as an answer - assert.NoError(t, build.RunYarnCommand(executablePath, tempDirPath, "install")) - installRequired, err = isInstallRequired(tempDirPath, []string{}) - assert.NoError(t, err) - assert.False(t, installRequired) -} - -func TestRunYarnInstallAccordingToVersion(t *testing.T) { - // Testing default 'install' command - executeRunYarnInstallAccordingToVersionAndVerifyInstallation(t, []string{}) - // Testing user provided 'install' command - executeRunYarnInstallAccordingToVersionAndVerifyInstallation(t, []string{"install", v1IgnoreScriptsFlag}) -} - -func executeRunYarnInstallAccordingToVersionAndVerifyInstallation(t *testing.T, params []string) { - tempDirPath, createTempDirCallback := tests.CreateTempDirWithCallbackAndAssert(t) - defer createTempDirCallback() - yarnProjectPath := filepath.Join("..", "..", "..", "testdata", "yarn-project") - assert.NoError(t, utils2.CopyDir(yarnProjectPath, tempDirPath, true, nil)) - - executablePath, err := biutils.GetYarnExecutable() - assert.NoError(t, err) - - err = runYarnInstallAccordingToVersion(tempDirPath, executablePath, params) - assert.NoError(t, err) - - // Checking the installation worked - we expect to get a 'false' answer when checking whether the project is installed - installRequired, err := isInstallRequired(tempDirPath, []string{}) - assert.NoError(t, err) - assert.False(t, installRequired) -} diff --git a/xray/commands/audit/scarunner.go b/xray/commands/audit/scarunner.go deleted file mode 100644 index 3fff76f23..000000000 --- a/xray/commands/audit/scarunner.go +++ /dev/null @@ -1,313 +0,0 @@ -package audit - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "time" - - "github.com/jfrog/build-info-go/utils/pythonutils" - "github.com/jfrog/gofrog/datastructures" - "github.com/jfrog/jfrog-cli-core/v2/common/project" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca" - _go "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca/go" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca/java" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca/npm" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca/nuget" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca/python" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit/sca/yarn" - "github.com/jfrog/jfrog-cli-core/v2/xray/scangraph" - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/artifactory/services/fspatterns" - clientutils "github.com/jfrog/jfrog-client-go/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/jfrog/jfrog-client-go/xray/services" - xrayCmdUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" -) - -var DefaultExcludePatterns = []string{"*.git*", "*node_modules*", "*target*", "*venv*", "*test*"} - -func runScaScan(params *AuditParams, results *xrayutils.Results) (err error) { - // Prepare - currentWorkingDir, err := os.Getwd() - if errorutils.CheckError(err) != nil { - return - } - serverDetails, err := params.ServerDetails() - if err != nil { - return - } - - scans := getScaScansToPreform(currentWorkingDir, params) - if len(scans) == 0 { - log.Info("Couldn't determine a package manager or build tool used by this project. Skipping the SCA scan...") - return - } - scanInfo, err := coreutils.GetJsonIndent(scans) - if err != nil { - return - } - log.Info(fmt.Sprintf("Preforming %d SCA scans:\n%s", len(scans), scanInfo)) - - defer func() { - // Make sure to return to the original working directory, executeScaScan may change it - err = errors.Join(err, os.Chdir(currentWorkingDir)) - }() - for _, scan := range scans { - // Run the scan - log.Info("Running SCA scan for", scan.Technology, "vulnerable dependencies in", scan.WorkingDirectory, "directory...") - if wdScanErr := executeScaScan(serverDetails, params, scan); wdScanErr != nil { - err = errors.Join(err, fmt.Errorf("audit command in '%s' failed:\n%s", scan.WorkingDirectory, wdScanErr.Error())) - continue - } - // Add the scan to the results - results.ScaResults = append(results.ScaResults, *scan) - } - return -} - -// Calculate the scans to preform -func getScaScansToPreform(currentWorkingDir string, params *AuditParams) (scansToPreform []*xrayutils.ScaScanResult) { - requestedDirectories, isRecursive := getRequestedDirectoriesToScan(currentWorkingDir, params) - for _, requestedDirectory := range requestedDirectories { - // Detect descriptors and technologies in the requested directory. - techToWorkingDirs, err := coreutils.DetectTechnologiesDescriptors(requestedDirectory, isRecursive, params.Technologies(), getRequestedDescriptors(params), getExcludePattern(params, isRecursive)) - if err != nil { - log.Warn("Couldn't detect technologies in", requestedDirectory, "directory.", err.Error()) - continue - } - // Create scans to preform - for tech, workingDirs := range techToWorkingDirs { - if tech == coreutils.Dotnet { - // We detect Dotnet and Nuget the same way, if one detected so does the other. - // We don't need to scan for both and get duplicate results. - continue - } - if len(workingDirs) == 0 { - // Requested technology (from params) descriptors/indicators was not found, scan only requested directory for this technology. - scansToPreform = append(scansToPreform, &xrayutils.ScaScanResult{WorkingDirectory: requestedDirectory, Technology: tech}) - } - for workingDir, descriptors := range workingDirs { - // Add scan for each detected working directory. - scansToPreform = append(scansToPreform, &xrayutils.ScaScanResult{WorkingDirectory: workingDir, Technology: tech, Descriptors: descriptors}) - } - } - } - return -} - -func getRequestedDescriptors(params *AuditParams) map[coreutils.Technology][]string { - requestedDescriptors := map[coreutils.Technology][]string{} - if params.PipRequirementsFile() != "" { - requestedDescriptors[coreutils.Pip] = []string{params.PipRequirementsFile()} - } - return requestedDescriptors -} - -func getExcludePattern(params *AuditParams, recursive bool) string { - exclusions := params.Exclusions() - if len(exclusions) == 0 { - exclusions = append(exclusions, DefaultExcludePatterns...) - } - return fspatterns.PrepareExcludePathPattern(exclusions, clientutils.WildCardPattern, recursive) -} - -// Get the directories to scan base on the given parameters. -// If no working directories were specified, the current working directory will be returned with recursive mode. -// If working directories were specified, the recursive mode will be false. -func getRequestedDirectoriesToScan(currentWorkingDir string, params *AuditParams) ([]string, bool) { - workingDirs := datastructures.MakeSet[string]() - for _, wd := range params.workingDirs { - workingDirs.Add(wd) - } - if len(params.workingDirs) == 0 { - return []string{currentWorkingDir}, true - } - return workingDirs.ToSlice(), false -} - -// Preform the SCA scan for the given scan information. -// This method will change the working directory to the scan's working directory. -func executeScaScan(serverDetails *config.ServerDetails, params *AuditParams, scan *xrayutils.ScaScanResult) (err error) { - // Get the dependency tree for the technology in the working directory. - if err = os.Chdir(scan.WorkingDirectory); err != nil { - return errorutils.CheckError(err) - } - flattenTree, fullDependencyTrees, techErr := GetTechDependencyTree(params.AuditBasicParams, scan.Technology) - if techErr != nil { - return fmt.Errorf("failed while building '%s' dependency tree:\n%s", scan.Technology, techErr.Error()) - } - if flattenTree == nil || len(flattenTree.Nodes) == 0 { - return errorutils.CheckErrorf("no dependencies were found. Please try to build your project and re-run the audit command") - } - // Scan the dependency tree. - scanResults, xrayErr := runScaWithTech(scan.Technology, params, serverDetails, flattenTree, fullDependencyTrees) - if xrayErr != nil { - return fmt.Errorf("'%s' Xray dependency tree scan request failed:\n%s", scan.Technology, xrayErr.Error()) - } - scan.IsMultipleRootProject = clientutils.Pointer(len(fullDependencyTrees) > 1) - addThirdPartyDependenciesToParams(params, scan.Technology, flattenTree, fullDependencyTrees) - scan.XrayResults = append(scan.XrayResults, scanResults...) - return -} - -func runScaWithTech(tech coreutils.Technology, params *AuditParams, serverDetails *config.ServerDetails, flatTree *xrayCmdUtils.GraphNode, fullDependencyTrees []*xrayCmdUtils.GraphNode) (techResults []services.ScanResponse, err error) { - scanGraphParams := scangraph.NewScanGraphParams(). - SetServerDetails(serverDetails). - SetXrayGraphScanParams(params.xrayGraphScanParams). - SetXrayVersion(params.xrayVersion). - SetFixableOnly(params.fixableOnly). - SetSeverityLevel(params.minSeverityFilter) - techResults, err = sca.RunXrayDependenciesTreeScanGraph(flatTree, params.Progress(), tech, scanGraphParams) - if err != nil { - return - } - techResults = sca.BuildImpactPathsForScanResponse(techResults, fullDependencyTrees) - return -} - -func addThirdPartyDependenciesToParams(params *AuditParams, tech coreutils.Technology, flatTree *xrayCmdUtils.GraphNode, fullDependencyTrees []*xrayCmdUtils.GraphNode) { - var dependenciesForApplicabilityScan []string - if shouldUseAllDependencies(params.thirdPartyApplicabilityScan, tech) { - dependenciesForApplicabilityScan = getDirectDependenciesFromTree([]*xrayCmdUtils.GraphNode{flatTree}) - } else { - dependenciesForApplicabilityScan = getDirectDependenciesFromTree(fullDependencyTrees) - } - params.AppendDependenciesForApplicabilityScan(dependenciesForApplicabilityScan) -} - -// When building pip dependency tree using pipdeptree, some of the direct dependencies are recognized as transitive and missed by the CA scanner. -// Our solution for this case is to send all dependencies to the CA scanner. -// When thirdPartyApplicabilityScan is true, use flatten graph to include all the dependencies in applicability scanning. -// Only npm is supported for this flag. -func shouldUseAllDependencies(thirdPartyApplicabilityScan bool, tech coreutils.Technology) bool { - return tech == coreutils.Pip || (thirdPartyApplicabilityScan && tech == coreutils.Npm) -} - -// This function retrieves the dependency trees of the scanned project and extracts a set that contains only the direct dependencies. -func getDirectDependenciesFromTree(dependencyTrees []*xrayCmdUtils.GraphNode) []string { - directDependencies := datastructures.MakeSet[string]() - for _, tree := range dependencyTrees { - for _, node := range tree.Nodes { - directDependencies.Add(node.Id) - } - } - return directDependencies.ToSlice() -} - -func GetTechDependencyTree(params xrayutils.AuditParams, tech coreutils.Technology) (flatTree *xrayCmdUtils.GraphNode, fullDependencyTrees []*xrayCmdUtils.GraphNode, err error) { - logMessage := fmt.Sprintf("Calculating %s dependencies", tech.ToFormal()) - log.Info(logMessage + "...") - if params.Progress() != nil { - params.Progress().SetHeadlineMsg(logMessage) - } - serverDetails, err := params.ServerDetails() - if err != nil { - return - } - err = SetResolutionRepoIfExists(params, tech) - if err != nil { - return - } - var uniqueDeps []string - startTime := time.Now() - switch tech { - case coreutils.Maven, coreutils.Gradle: - fullDependencyTrees, uniqueDeps, err = java.BuildDependencyTree(params, tech) - case coreutils.Npm: - fullDependencyTrees, uniqueDeps, err = npm.BuildDependencyTree(params) - case coreutils.Yarn: - fullDependencyTrees, uniqueDeps, err = yarn.BuildDependencyTree(params) - case coreutils.Go: - fullDependencyTrees, uniqueDeps, err = _go.BuildDependencyTree(params) - case coreutils.Pipenv, coreutils.Pip, coreutils.Poetry: - fullDependencyTrees, uniqueDeps, err = python.BuildDependencyTree(&python.AuditPython{ - Server: serverDetails, - Tool: pythonutils.PythonTool(tech), - RemotePypiRepo: params.DepsRepo(), - PipRequirementsFile: params.PipRequirementsFile()}) - case coreutils.Nuget: - fullDependencyTrees, uniqueDeps, err = nuget.BuildDependencyTree(params) - default: - err = errorutils.CheckErrorf("%s is currently not supported", string(tech)) - } - if err != nil || len(uniqueDeps) == 0 { - return - } - log.Debug(fmt.Sprintf("Created '%s' dependency tree with %d nodes. Elapsed time: %.1f seconds.", tech.ToFormal(), len(uniqueDeps), time.Since(startTime).Seconds())) - flatTree, err = createFlatTree(uniqueDeps) - return -} - -// Associates a technology with another of a different type in the structure. -// Docker is not present, as there is no docker-config command and, consequently, no docker.yaml file we need to operate on. -var techType = map[coreutils.Technology]project.ProjectType{ - coreutils.Maven: project.Maven, coreutils.Gradle: project.Gradle, coreutils.Npm: project.Npm, coreutils.Yarn: project.Yarn, coreutils.Go: project.Go, coreutils.Pip: project.Pip, - coreutils.Pipenv: project.Pipenv, coreutils.Poetry: project.Poetry, coreutils.Nuget: project.Nuget, coreutils.Dotnet: project.Dotnet, -} - -// Verifies the existence of depsRepo. If it doesn't exist, it searches for a configuration file based on the technology type. If found, it assigns depsRepo in the AuditParams. -func SetResolutionRepoIfExists(params xrayutils.AuditParams, tech coreutils.Technology) (err error) { - if params.DepsRepo() != "" || params.IgnoreConfigFile() { - return - } - - configFilePath, exists, err := project.GetProjectConfFilePath(techType[tech]) - if err != nil { - err = fmt.Errorf("failed while searching for %s.yaml config file: %s", tech.String(), err.Error()) - return - } - if !exists { - // Nuget and Dotnet are identified similarly in the detection process. To prevent redundancy, Dotnet is filtered out earlier in the process, focusing solely on detecting Nuget. - // Consequently, it becomes necessary to verify the presence of dotnet.yaml when Nuget detection occurs. - if tech == coreutils.Nuget { - configFilePath, exists, err = project.GetProjectConfFilePath(techType[coreutils.Dotnet]) - if err != nil { - err = fmt.Errorf("failed while searching for %s.yaml config file: %s", tech.String(), err.Error()) - return - } - if !exists { - log.Debug(fmt.Sprintf("No %s.yaml nor %s.yaml configuration file was found. Resolving dependencies from %s default registry", coreutils.Nuget.String(), coreutils.Dotnet.String(), tech.String())) - return - } - } else { - log.Debug(fmt.Sprintf("No %s.yaml configuration file was found. Resolving dependencies from %s default registry", tech.String(), tech.String())) - return - } - } - - log.Debug("Using resolver config from", configFilePath) - repoConfig, err := project.ReadResolutionOnlyConfiguration(configFilePath) - if err != nil { - err = fmt.Errorf("failed while reading %s.yaml config file: %s", tech.String(), err.Error()) - return - } - details, err := repoConfig.ServerDetails() - if err != nil { - err = fmt.Errorf("failed getting server details: %s", err.Error()) - return - } - params.SetServerDetails(details) - params.SetDepsRepo(repoConfig.TargetRepo()) - return -} - -func createFlatTree(uniqueDeps []string) (*xrayCmdUtils.GraphNode, error) { - if log.GetLogger().GetLogLevel() == log.DEBUG { - // Avoid printing and marshaling if not on DEBUG mode. - jsonList, err := json.Marshal(uniqueDeps) - if errorutils.CheckError(err) != nil { - return nil, err - } - log.Debug("Unique dependencies list:\n" + clientutils.IndentJsonArray(jsonList)) - } - uniqueNodes := []*xrayCmdUtils.GraphNode{} - for _, uniqueDep := range uniqueDeps { - uniqueNodes = append(uniqueNodes, &xrayCmdUtils.GraphNode{Id: uniqueDep}) - } - return &xrayCmdUtils.GraphNode{Id: "root", Nodes: uniqueNodes}, nil -} diff --git a/xray/commands/audit/scarunner_test.go b/xray/commands/audit/scarunner_test.go deleted file mode 100644 index 876df5005..000000000 --- a/xray/commands/audit/scarunner_test.go +++ /dev/null @@ -1,306 +0,0 @@ -package audit - -import ( - "os" - "path/filepath" - "sort" - "testing" - - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "github.com/stretchr/testify/assert" -) - -func TestGetDirectDependenciesList(t *testing.T) { - tests := []struct { - dependenciesTrees []*xrayUtils.GraphNode - expectedResult []string - }{ - { - dependenciesTrees: nil, - expectedResult: []string{}, - }, - { - dependenciesTrees: []*xrayUtils.GraphNode{ - {Id: "parent_node_id", Nodes: []*xrayUtils.GraphNode{ - {Id: "issueId_1_direct_dependency", Nodes: []*xrayUtils.GraphNode{{Id: "issueId_1_non_direct_dependency"}}}, - {Id: "issueId_2_direct_dependency", Nodes: nil}, - }, - }, - }, - expectedResult: []string{"issueId_1_direct_dependency", "issueId_2_direct_dependency"}, - }, - { - dependenciesTrees: []*xrayUtils.GraphNode{ - {Id: "parent_node_id", Nodes: []*xrayUtils.GraphNode{ - {Id: "issueId_1_direct_dependency", Nodes: nil}, - {Id: "issueId_2_direct_dependency", Nodes: nil}, - }, - }, - }, - expectedResult: []string{"issueId_1_direct_dependency", "issueId_2_direct_dependency"}, - }, - } - - for _, test := range tests { - result := getDirectDependenciesFromTree(test.dependenciesTrees) - assert.ElementsMatch(t, test.expectedResult, result) - } -} - -func createTestDir(t *testing.T) (directory string, cleanUp func()) { - tmpDir, err := fileutils.CreateTempDir() - assert.NoError(t, err) - - // Temp dir structure: - // tempDir - // ├── dir - // │ ├── maven - // │ │ ├── maven-sub - // │ │ └── maven-sub - // │ ├── npm - // │ └── go - // ├── yarn - // │ ├── Pip - // │ └── Pipenv - // └── Nuget - // ├── Nuget-sub - - dir := createEmptyDir(t, filepath.Join(tmpDir, "dir")) - // Maven - maven := createEmptyDir(t, filepath.Join(dir, "maven")) - createEmptyFile(t, filepath.Join(maven, "pom.xml")) - mavenSub := createEmptyDir(t, filepath.Join(maven, "maven-sub")) - createEmptyFile(t, filepath.Join(mavenSub, "pom.xml")) - mavenSub2 := createEmptyDir(t, filepath.Join(maven, "maven-sub2")) - createEmptyFile(t, filepath.Join(mavenSub2, "pom.xml")) - // Npm - npm := createEmptyDir(t, filepath.Join(dir, "npm")) - createEmptyFile(t, filepath.Join(npm, "package.json")) - createEmptyFile(t, filepath.Join(npm, "package-lock.json")) - // Go - goDir := createEmptyDir(t, filepath.Join(dir, "go")) - createEmptyFile(t, filepath.Join(goDir, "go.mod")) - // Yarn - yarn := createEmptyDir(t, filepath.Join(tmpDir, "yarn")) - createEmptyFile(t, filepath.Join(yarn, "package.json")) - createEmptyFile(t, filepath.Join(yarn, "yarn.lock")) - // Pip - pip := createEmptyDir(t, filepath.Join(yarn, "Pip")) - createEmptyFile(t, filepath.Join(pip, "requirements.txt")) - // Pipenv - pipenv := createEmptyDir(t, filepath.Join(yarn, "Pipenv")) - createEmptyFile(t, filepath.Join(pipenv, "Pipfile")) - createEmptyFile(t, filepath.Join(pipenv, "Pipfile.lock")) - // Nuget - nuget := createEmptyDir(t, filepath.Join(tmpDir, "Nuget")) - createEmptyFile(t, filepath.Join(nuget, "project.sln")) - nugetSub := createEmptyDir(t, filepath.Join(nuget, "Nuget-sub")) - createEmptyFile(t, filepath.Join(nugetSub, "project.csproj")) - - return tmpDir, func() { - assert.NoError(t, fileutils.RemoveTempDir(tmpDir), "Couldn't removeAll: "+tmpDir) - } -} - -func createEmptyDir(t *testing.T, path string) string { - assert.NoError(t, fileutils.CreateDirIfNotExist(path)) - return path -} - -func createEmptyFile(t *testing.T, path string) { - file, err := os.Create(path) - assert.NoError(t, err) - assert.NoError(t, file.Close()) -} - -func TestGetExcludePattern(t *testing.T) { - tests := []struct { - name string - params func() *AuditParams - recursive bool - expected string - }{ - { - name: "Test exclude pattern recursive", - params: func() *AuditParams { - param := NewAuditParams() - param.SetExclusions([]string{"exclude1", "exclude2"}) - return param - }, - recursive: true, - expected: "(^exclude1$)|(^exclude2$)", - }, - { - name: "Test no exclude pattern recursive", - params: NewAuditParams, - recursive: true, - expected: "(^.*\\.git.*$)|(^.*node_modules.*$)|(^.*target.*$)|(^.*venv.*$)|(^.*test.*$)", - }, - { - name: "Test exclude pattern not recursive", - params: func() *AuditParams { - param := NewAuditParams() - param.SetExclusions([]string{"exclude1", "exclude2"}) - return param - }, - recursive: false, - expected: "(^exclude1$)|(^exclude2$)", - }, - { - name: "Test no exclude pattern", - params: NewAuditParams, - recursive: false, - expected: "(^.*\\.git.*$)|(^.*node_modules.*$)|(^.*target.*$)|(^.*venv.*$)|(^.*test.*$)", - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - result := getExcludePattern(test.params(), test.recursive) - assert.Equal(t, test.expected, result) - }) - } -} - -func TestGetRequestedDirectoriesToScan(t *testing.T) { - tests := []struct { - name string - cwd string - params func() *AuditParams - expectedRecursive bool - expectedDirs []string - }{ - { - name: "Test specific directories", - cwd: "tmp", - params: func() *AuditParams { - param := NewAuditParams() - param.SetWorkingDirs([]string{filepath.Join("tmp", "dir1"), filepath.Join("tmp", "dir2")}) - return param - }, - expectedRecursive: false, - expectedDirs: []string{filepath.Join("tmp", "dir1"), filepath.Join("tmp", "dir2")}, - }, - { - name: "Test recursive", - cwd: "tmp", - params: NewAuditParams, - expectedRecursive: true, - expectedDirs: []string{"tmp"}, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - dirs, recursive := getRequestedDirectoriesToScan(test.cwd, test.params()) - assert.ElementsMatch(t, test.expectedDirs, dirs) - assert.Equal(t, test.expectedRecursive, recursive) - }) - } -} - -func TestGetScaScansToPreform(t *testing.T) { - - dir, cleanUp := createTestDir(t) - - tests := []struct { - name string - wd string - params func() *AuditParams - expected []*xrayutils.ScaScanResult - }{ - { - name: "Test specific technologies", - wd: dir, - params: func() *AuditParams { - param := NewAuditParams() - param.SetTechnologies([]string{"maven", "npm", "go"}) - return param - }, - expected: []*xrayutils.ScaScanResult{ - { - Technology: coreutils.Maven, - WorkingDirectory: filepath.Join(dir, "dir", "maven"), - Descriptors: []string{ - filepath.Join(dir, "dir", "maven", "pom.xml"), - filepath.Join(dir, "dir", "maven", "maven-sub", "pom.xml"), - filepath.Join(dir, "dir", "maven", "maven-sub2", "pom.xml"), - }, - }, - { - Technology: coreutils.Npm, - WorkingDirectory: filepath.Join(dir, "dir", "npm"), - Descriptors: []string{filepath.Join(dir, "dir", "npm", "package.json")}, - }, - { - Technology: coreutils.Go, - WorkingDirectory: filepath.Join(dir, "dir", "go"), - Descriptors: []string{filepath.Join(dir, "dir", "go", "go.mod")}, - }, - }, - }, - { - name: "Test all", - wd: dir, - params: NewAuditParams, - expected: []*xrayutils.ScaScanResult{ - { - Technology: coreutils.Maven, - WorkingDirectory: filepath.Join(dir, "dir", "maven"), - Descriptors: []string{ - filepath.Join(dir, "dir", "maven", "pom.xml"), - filepath.Join(dir, "dir", "maven", "maven-sub", "pom.xml"), - filepath.Join(dir, "dir", "maven", "maven-sub2", "pom.xml"), - }, - }, - { - Technology: coreutils.Npm, - WorkingDirectory: filepath.Join(dir, "dir", "npm"), - Descriptors: []string{filepath.Join(dir, "dir", "npm", "package.json")}, - }, - { - Technology: coreutils.Go, - WorkingDirectory: filepath.Join(dir, "dir", "go"), - Descriptors: []string{filepath.Join(dir, "dir", "go", "go.mod")}, - }, - { - Technology: coreutils.Yarn, - WorkingDirectory: filepath.Join(dir, "yarn"), - Descriptors: []string{filepath.Join(dir, "yarn", "package.json")}, - }, - { - Technology: coreutils.Pip, - WorkingDirectory: filepath.Join(dir, "yarn", "Pip"), - Descriptors: []string{filepath.Join(dir, "yarn", "Pip", "requirements.txt")}, - }, - { - Technology: coreutils.Pipenv, - WorkingDirectory: filepath.Join(dir, "yarn", "Pipenv"), - Descriptors: []string{filepath.Join(dir, "yarn", "Pipenv", "Pipfile")}, - }, - { - Technology: coreutils.Nuget, - WorkingDirectory: filepath.Join(dir, "Nuget"), - Descriptors: []string{filepath.Join(dir, "Nuget", "project.sln"), filepath.Join(dir, "Nuget", "Nuget-sub", "project.csproj")}, - }, - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - result := getScaScansToPreform(test.wd, test.params()) - for i := range result { - sort.Strings(result[i].Descriptors) - sort.Strings(test.expected[i].Descriptors) - } - assert.ElementsMatch(t, test.expected, result) - }) - } - - cleanUp() -} diff --git a/xray/commands/curation/curationaudit.go b/xray/commands/curation/curationaudit.go deleted file mode 100644 index 4dd7677e7..000000000 --- a/xray/commands/curation/curationaudit.go +++ /dev/null @@ -1,573 +0,0 @@ -package curation - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "os" - "path/filepath" - "regexp" - "sort" - "strings" - "sync" - - "github.com/jfrog/gofrog/datastructures" - "github.com/jfrog/gofrog/parallel" - rtUtils "github.com/jfrog/jfrog-cli-core/v2/artifactory/utils" - outFormat "github.com/jfrog/jfrog-cli-core/v2/common/format" - "github.com/jfrog/jfrog-cli-core/v2/common/project" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/commands/audit" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/artifactory" - "github.com/jfrog/jfrog-client-go/auth" - clientutils "github.com/jfrog/jfrog-client-go/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/httputils" - "github.com/jfrog/jfrog-client-go/utils/log" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" -) - -const ( - // The "blocked" represents the unapproved status that can be returned by the Curation Service for dependencies.. - blocked = "blocked" - BlockingReasonPolicy = "Policy violations" - BlockingReasonNotFound = "Package pending update" - - directRelation = "direct" - indirectRelation = "indirect" - - BlockMessageKey = "jfrog packages curation" - NotBeingFoundKey = "not being found" - - extractPoliciesRegexTemplate = "({.*?})" - - errorTemplateHeadRequest = "failed sending HEAD request to %s for package '%s:%s'. Status-code: %v. Cause: %v" - - errorTemplateUnsupportedTech = "It looks like this project uses '%s' to download its dependencies. " + - "This package manager however isn't supported by this command." - - TotalConcurrentRequests = 10 -) - -var CurationOutputFormats = []string{string(outFormat.Table), string(outFormat.Json)} - -var supportedTech = map[coreutils.Technology]struct{}{ - coreutils.Npm: {}, -} - -type ErrorsResp struct { - Errors []ErrorResp `json:"errors"` -} - -type ErrorResp struct { - Status int `json:"status"` - Message string `json:"message"` -} - -type PackageStatus struct { - Action string `json:"action"` - ParentName string `json:"direct_dependency_package_name"` - ParentVersion string `json:"direct_dependency_package_version"` - BlockedPackageUrl string `json:"blocked_package_url,omitempty"` - PackageName string `json:"blocked_package_name"` - PackageVersion string `json:"blocked_package_version"` - BlockingReason string `json:"blocking_reason"` - DepRelation string `json:"dependency_relation"` - PkgType string `json:"type"` - Policy []Policy `json:"policies,omitempty"` -} - -type Policy struct { - Policy string `json:"policy"` - Condition string `json:"condition"` - Explanation string `json:"explanation"` - Recommendation string `json:"recommendation"` -} - -type PackageStatusTable struct { - ParentName string `col-name:"Direct\nDependency\nPackage\nName" auto-merge:"true"` - ParentVersion string `col-name:"Direct\nDependency\nPackage\nVersion" auto-merge:"true"` - PackageName string `col-name:"Blocked\nPackage\nName" auto-merge:"true"` - PackageVersion string `col-name:"Blocked\nPackage\nVersion" auto-merge:"true"` - BlockingReason string `col-name:"Blocking Reason" auto-merge:"true"` - PkgType string `col-name:"Package\nType" auto-merge:"true"` - Policy string `col-name:"Violated\nPolicy\nName"` - Condition string `col-name:"Violated Condition\nName"` - Explanation string `col-name:"Explanation"` - Recommendation string `col-name:"Recommendation"` -} - -type treeAnalyzer struct { - rtManager artifactory.ArtifactoryServicesManager - extractPoliciesRegex *regexp.Regexp - rtAuth auth.ServiceDetails - httpClientDetails httputils.HttpClientDetails - url string - repo string - tech coreutils.Technology - parallelRequests int -} - -type CurationAuditCommand struct { - PackageManagerConfig *project.RepositoryConfig - extractPoliciesRegex *regexp.Regexp - workingDirs []string - OriginPath string - parallelRequests int - utils.AuditParams -} - -func NewCurationAuditCommand() *CurationAuditCommand { - return &CurationAuditCommand{ - extractPoliciesRegex: regexp.MustCompile(extractPoliciesRegexTemplate), - AuditParams: &utils.AuditBasicParams{}, - } -} - -func (ca *CurationAuditCommand) setPackageManagerConfig(pkgMangerConfig *project.RepositoryConfig) *CurationAuditCommand { - ca.PackageManagerConfig = pkgMangerConfig - return ca -} - -func (ca *CurationAuditCommand) SetWorkingDirs(dirs []string) *CurationAuditCommand { - ca.workingDirs = dirs - return ca -} - -func (ca *CurationAuditCommand) SetParallelRequests(threads int) *CurationAuditCommand { - ca.parallelRequests = threads - return ca -} - -func (ca *CurationAuditCommand) Run() (err error) { - rootDir, err := os.Getwd() - if err != nil { - return errorutils.CheckError(err) - } - if len(ca.workingDirs) > 0 { - defer func() { - if e := errorutils.CheckError(os.Chdir(rootDir)); err == nil { - err = e - } - }() - } else { - ca.workingDirs = append(ca.workingDirs, rootDir) - } - results := map[string][]*PackageStatus{} - for _, workDir := range ca.workingDirs { - var absWd string - absWd, err = filepath.Abs(workDir) - if err != nil { - return errorutils.CheckError(err) - } - log.Info("Running curation audit on project:", absWd) - if absWd != rootDir { - if err = os.Chdir(absWd); err != nil { - return errorutils.CheckError(err) - } - } - // If error returned, continue to print results(if any), and return error at the end. - if e := ca.doCurateAudit(results); e != nil { - err = errors.Join(err, e) - } - } - if ca.Progress() != nil { - err = errors.Join(err, ca.Progress().Quit()) - } - - for projectPath, packagesStatus := range results { - err = errors.Join(err, printResult(ca.OutputFormat(), projectPath, packagesStatus)) - } - return -} - -func (ca *CurationAuditCommand) doCurateAudit(results map[string][]*PackageStatus) error { - techs := coreutils.DetectedTechnologiesList() - for _, tech := range techs { - if _, ok := supportedTech[coreutils.Technology(tech)]; !ok { - log.Info(fmt.Sprintf(errorTemplateUnsupportedTech, tech)) - continue - } - if err := ca.auditTree(coreutils.Technology(tech), results); err != nil { - return err - } - } - return nil -} - -func (ca *CurationAuditCommand) getAuditParamsByTech(tech coreutils.Technology) utils.AuditParams { - if tech == coreutils.Npm { - return utils.AuditNpmParams{AuditParams: ca.AuditParams}. - SetNpmIgnoreNodeModules(true). - SetNpmOverwritePackageLock(true) - } - return ca.AuditParams -} - -func (ca *CurationAuditCommand) auditTree(tech coreutils.Technology, results map[string][]*PackageStatus) error { - flattenGraph, fullDependenciesTree, err := audit.GetTechDependencyTree(ca.getAuditParamsByTech(tech), tech) - if err != nil { - return err - } - // Validate the graph isn't empty. - if len(fullDependenciesTree) == 0 { - return errorutils.CheckErrorf("found no dependencies for the audited project using '%v' as the package manager", tech.String()) - } - if err = ca.SetRepo(tech); err != nil { - return err - } - // Resolve the dependencies of the project. - serverDetails, err := ca.PackageManagerConfig.ServerDetails() - if err != nil { - return err - } - rtManager, err := rtUtils.CreateServiceManager(serverDetails, 2, 0, false) - if err != nil { - return err - } - rtAuth, err := serverDetails.CreateArtAuthConfig() - if err != nil { - return err - } - rootNode := fullDependenciesTree[0] - _, projectName, projectScope, projectVersion := getUrlNameAndVersionByTech(tech, rootNode.Id, "", "") - if ca.Progress() != nil { - ca.Progress().SetHeadlineMsg(fmt.Sprintf("Fetch curation status for %s graph with %v nodes project name: %s:%s", tech.ToFormal(), len(flattenGraph.Nodes)-1, projectName, projectVersion)) - } - if projectScope != "" { - projectName = projectScope + "/" + projectName - } - if ca.parallelRequests == 0 { - ca.parallelRequests = TotalConcurrentRequests - } - var packagesStatus []*PackageStatus - analyzer := treeAnalyzer{ - rtManager: rtManager, - extractPoliciesRegex: ca.extractPoliciesRegex, - rtAuth: rtAuth, - httpClientDetails: rtAuth.CreateHttpClientDetails(), - url: rtAuth.GetUrl(), - repo: ca.PackageManagerConfig.TargetRepo(), - tech: tech, - parallelRequests: ca.parallelRequests, - } - packagesStatusMap := sync.Map{} - // Fetch status for each node from a flatten graph which, has no duplicate nodes. - err = analyzer.fetchNodesStatus(flattenGraph, &packagesStatusMap, rootNode.Id) - analyzer.fillGraphRelations(rootNode, &packagesStatusMap, - &packagesStatus, "", "", datastructures.MakeSet[string](), true) - sort.Slice(packagesStatus, func(i, j int) bool { - return packagesStatus[i].ParentName < packagesStatus[j].ParentName - }) - results[fmt.Sprintf("%s:%s", projectName, projectVersion)] = packagesStatus - return err -} - -func printResult(format outFormat.OutputFormat, projectPath string, packagesStatus []*PackageStatus) error { - if format == "" { - format = outFormat.Table - } - log.Output(fmt.Sprintf("Found %v blocked packages for project %s", len(packagesStatus), projectPath)) - switch format { - case outFormat.Json: - if len(packagesStatus) > 0 { - err := utils.PrintJson(packagesStatus) - if err != nil { - return err - } - } - case outFormat.Table: - pkgStatusTable := convertToPackageStatusTable(packagesStatus) - err := coreutils.PrintTable(pkgStatusTable, "Curation", "Found 0 blocked packages", true) - if err != nil { - return err - } - } - log.Output("\n") - return nil -} - -func convertToPackageStatusTable(packagesStatus []*PackageStatus) []PackageStatusTable { - var pkgStatusTable []PackageStatusTable - for index, pkgStatus := range packagesStatus { - // We use auto-merge supported by the 'go-pretty' library. It doesn't have an option to merge lines by a group of unique fields. - // In order to so, we make each group merge only with itself by adding or not adding space. This way, it won't be merged with the next group. - uniqLineSep := "" - if index%2 == 0 { - uniqLineSep = " " - } - pkgTable := PackageStatusTable{ - ParentName: pkgStatus.ParentName + uniqLineSep, - ParentVersion: pkgStatus.ParentVersion + uniqLineSep, - PackageName: pkgStatus.PackageName + uniqLineSep, - PackageVersion: pkgStatus.PackageVersion + uniqLineSep, - BlockingReason: pkgStatus.BlockingReason + uniqLineSep, - PkgType: pkgStatus.PkgType + uniqLineSep, - } - if len(pkgStatus.Policy) == 0 { - pkgStatusTable = append(pkgStatusTable, pkgTable) - continue - } - for _, policyCond := range pkgStatus.Policy { - pkgTable.Policy = policyCond.Policy - pkgTable.Explanation = policyCond.Explanation - pkgTable.Recommendation = policyCond.Recommendation - pkgTable.Condition = policyCond.Condition - pkgStatusTable = append(pkgStatusTable, pkgTable) - } - } - - return pkgStatusTable -} - -func (ca *CurationAuditCommand) CommandName() string { - return "curation_audit" -} - -func (ca *CurationAuditCommand) SetRepo(tech coreutils.Technology) error { - switch tech { - case coreutils.Npm: - configFilePath, exists, err := project.GetProjectConfFilePath(project.Npm) - if err != nil { - return err - } - if !exists { - return errorutils.CheckErrorf("no config file was found! Before running the npm command on a " + - "project for the first time, the project should be configured using the 'jf npmc' command") - } - vConfig, err := project.ReadConfigFile(configFilePath, project.YAML) - if err != nil { - return err - } - resolverParams, err := project.GetRepoConfigByPrefix(configFilePath, project.ProjectConfigResolverPrefix, vConfig) - if err != nil { - return err - } - ca.setPackageManagerConfig(resolverParams) - default: - return errorutils.CheckErrorf(errorTemplateUnsupportedTech, tech.String()) - } - return nil -} - -func (nc *treeAnalyzer) fillGraphRelations(node *xrayUtils.GraphNode, preProcessMap *sync.Map, - packagesStatus *[]*PackageStatus, parent, parentVersion string, visited *datastructures.Set[string], isRoot bool) { - for _, child := range node.Nodes { - packageUrl, name, scope, version := getUrlNameAndVersionByTech(nc.tech, child.Id, nc.url, nc.repo) - if isRoot { - parent = name - parentVersion = version - if scope != "" { - parent = scope + "/" + parent - } - } - if visited.Exists(scope + name + version + "-" + parent + parentVersion) { - continue - } - - visited.Add(scope + name + version + "-" + parent + parentVersion) - if pkgStatus, exist := preProcessMap.Load(packageUrl); exist { - relation := indirectRelation - if isRoot { - relation = directRelation - } - pkgStatusCast, isPkgStatus := pkgStatus.(*PackageStatus) - if isPkgStatus { - pkgStatusClone := *pkgStatusCast - pkgStatusClone.DepRelation = relation - pkgStatusClone.ParentName = parent - pkgStatusClone.ParentVersion = parentVersion - *packagesStatus = append(*packagesStatus, &pkgStatusClone) - } - } - nc.fillGraphRelations(child, preProcessMap, packagesStatus, parent, parentVersion, visited, false) - } -} -func (nc *treeAnalyzer) fetchNodesStatus(graph *xrayUtils.GraphNode, p *sync.Map, rootNodeId string) error { - var multiErrors error - consumerProducer := parallel.NewBounedRunner(nc.parallelRequests, false) - errorsQueue := clientutils.NewErrorsQueue(1) - go func() { - defer consumerProducer.Done() - for _, node := range graph.Nodes { - if node.Id == rootNodeId { - continue - } - getTask := func(node xrayUtils.GraphNode) func(threadId int) error { - return func(threadId int) (err error) { - return nc.fetchNodeStatus(node, p) - } - } - if _, err := consumerProducer.AddTaskWithError(getTask(*node), errorsQueue.AddError); err != nil { - multiErrors = errors.Join(err, multiErrors) - } - } - }() - consumerProducer.Run() - if err := errorsQueue.GetError(); err != nil { - multiErrors = errors.Join(err, multiErrors) - } - return multiErrors -} - -func (nc *treeAnalyzer) fetchNodeStatus(node xrayUtils.GraphNode, p *sync.Map) error { - packageUrl, name, scope, version := getUrlNameAndVersionByTech(nc.tech, node.Id, nc.url, nc.repo) - if scope != "" { - name = scope + "/" + name - } - resp, _, err := nc.rtManager.Client().SendHead(packageUrl, &nc.httpClientDetails) - if err != nil { - if resp != nil && resp.StatusCode >= 400 { - return errorutils.CheckErrorf(errorTemplateHeadRequest, packageUrl, name, version, resp.StatusCode, err) - } - if resp == nil || resp.StatusCode != http.StatusForbidden { - return err - } - } - if resp != nil && resp.StatusCode >= 400 && resp.StatusCode != http.StatusForbidden { - return errorutils.CheckErrorf(errorTemplateHeadRequest, packageUrl, name, version, resp.StatusCode, err) - } - if resp.StatusCode == http.StatusForbidden { - pkStatus, err := nc.getBlockedPackageDetails(packageUrl, name, version) - if err != nil { - return err - } - if pkStatus != nil { - p.Store(pkStatus.BlockedPackageUrl, pkStatus) - } - } - return nil -} - -// We try to collect curation details from GET response after HEAD request got forbidden status code. -func (nc *treeAnalyzer) getBlockedPackageDetails(packageUrl string, name string, version string) (*PackageStatus, error) { - getResp, respBody, _, err := nc.rtManager.Client().SendGet(packageUrl, true, &nc.httpClientDetails) - if err != nil { - if getResp == nil { - return nil, err - } - if getResp.StatusCode != http.StatusForbidden { - return nil, errorutils.CheckErrorf(errorTemplateHeadRequest, packageUrl, name, version, getResp.StatusCode, err) - } - } - if getResp.StatusCode == http.StatusForbidden { - respError := &ErrorsResp{} - if err := json.Unmarshal(respBody, respError); err != nil { - return nil, errorutils.CheckError(err) - } - if len(respError.Errors) == 0 { - return nil, errorutils.CheckErrorf("received 403 for unknown reason, no curation status will be presented for this package. "+ - "package name: %s, version: %s, download url: %s ", name, version, packageUrl) - } - // if the error message contains the curation string key, then we can be sure it got blocked by Curation service. - if strings.Contains(strings.ToLower(respError.Errors[0].Message), BlockMessageKey) { - blockingReason := BlockingReasonPolicy - if strings.Contains(strings.ToLower(respError.Errors[0].Message), NotBeingFoundKey) { - blockingReason = BlockingReasonNotFound - } - policies := nc.extractPoliciesFromMsg(respError) - return &PackageStatus{ - PackageName: name, - PackageVersion: version, - BlockedPackageUrl: packageUrl, - Action: blocked, - Policy: policies, - BlockingReason: blockingReason, - PkgType: string(nc.tech), - }, nil - } - } - return nil, nil -} - -// Return policies and conditions names from the FORBIDDEN HTTP error message. -// Message structure: Package %s:%s download was blocked by JFrog Packages Curation service due to the following policies violated {%s, %s, %s, %s},{%s, %s, %s, %s}. -func (nc *treeAnalyzer) extractPoliciesFromMsg(respError *ErrorsResp) []Policy { - var policies []Policy - msg := respError.Errors[0].Message - allMatches := nc.extractPoliciesRegex.FindAllString(msg, -1) - for _, match := range allMatches { - match = strings.TrimSuffix(strings.TrimPrefix(match, "{"), "}") - polCond := strings.Split(match, ",") - if len(polCond) >= 2 { - pol := polCond[0] - cond := polCond[1] - - if len(polCond) == 4 { - exp, rec := makeLegiblePolicyDetails(polCond[2], polCond[3]) - policies = append(policies, Policy{Policy: strings.TrimSpace(pol), - Condition: strings.TrimSpace(cond), Explanation: strings.TrimSpace(exp), Recommendation: strings.TrimSpace(rec)}) - continue - } - policies = append(policies, Policy{Policy: strings.TrimSpace(pol), Condition: strings.TrimSpace(cond)}) - } - } - return policies -} - -// Adding a new line after the headline and replace every "|" with a new line. -func makeLegiblePolicyDetails(explanation, recommendation string) (string, string) { - explanation = strings.ReplaceAll(strings.Replace(explanation, ": ", ":\n", 1), " | ", "\n") - recommendation = strings.ReplaceAll(strings.Replace(recommendation, ": ", ":\n", 1), " | ", "\n") - return explanation, recommendation -} - -func getUrlNameAndVersionByTech(tech coreutils.Technology, nodeId, artiUrl, repo string) (downloadUrl string, name string, scope string, version string) { - if tech == coreutils.Npm { - return getNpmNameScopeAndVersion(nodeId, artiUrl, repo, coreutils.Npm.String()) - } - return -} - -// The graph holds, for each node, the component ID (xray representation) -// from which we extract the package name, version, and construct the Artifactory download URL. -func getNpmNameScopeAndVersion(id, artiUrl, repo, tech string) (downloadUrl, name, scope, version string) { - id = strings.TrimPrefix(id, tech+"://") - - nameVersion := strings.Split(id, ":") - name = nameVersion[0] - if len(nameVersion) > 1 { - version = nameVersion[1] - } - scopeSplit := strings.Split(name, "/") - if len(scopeSplit) > 1 { - scope = scopeSplit[0] - name = scopeSplit[1] - } - return buildNpmDownloadUrl(artiUrl, repo, name, scope, version), name, scope, version -} - -func buildNpmDownloadUrl(url, repo, name, scope, version string) string { - var packageUrl string - if scope != "" { - packageUrl = fmt.Sprintf("%s/api/npm/%s/%s/%s/-/%s-%s.tgz", strings.TrimSuffix(url, "/"), repo, scope, name, name, version) - } else { - packageUrl = fmt.Sprintf("%s/api/npm/%s/%s/-/%s-%s.tgz", strings.TrimSuffix(url, "/"), repo, name, name, version) - } - return packageUrl -} - -func DetectNumOfThreads(threadsCount int) (int, error) { - if threadsCount > TotalConcurrentRequests { - return 0, errorutils.CheckErrorf("number of threads crossed the maximum, the maximum threads allowed is %v", TotalConcurrentRequests) - } - return threadsCount, nil -} - -func GetCurationOutputFormat(formatFlagVal string) (format outFormat.OutputFormat, err error) { - // Default print format is table. - format = outFormat.Table - if formatFlagVal != "" { - switch strings.ToLower(formatFlagVal) { - case string(outFormat.Table): - format = outFormat.Table - case string(outFormat.Json): - format = outFormat.Json - default: - err = errorutils.CheckErrorf("only the following output formats are supported: " + coreutils.ListToText(CurationOutputFormats)) - } - } - return -} diff --git a/xray/commands/curation/curationaudit_test.go b/xray/commands/curation/curationaudit_test.go deleted file mode 100644 index 1f942be17..000000000 --- a/xray/commands/curation/curationaudit_test.go +++ /dev/null @@ -1,580 +0,0 @@ -package curation - -import ( - "encoding/json" - "fmt" - "github.com/jfrog/gofrog/datastructures" - coretests "github.com/jfrog/jfrog-cli-core/v2/common/tests" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - clienttestutils "github.com/jfrog/jfrog-client-go/utils/tests" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - "github.com/stretchr/testify/assert" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "testing" -) - -func TestExtractPoliciesFromMsg(t *testing.T) { - var err error - extractPoliciesRegex := regexp.MustCompile(extractPoliciesRegexTemplate) - assert.NoError(t, err) - tests := getTestCasesForExtractPoliciesFromMsg() - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ta := treeAnalyzer{extractPoliciesRegex: extractPoliciesRegex} - got := ta.extractPoliciesFromMsg(tt.errResp) - assert.Equal(t, tt.expect, got) - }) - } -} - -func getTestCasesForExtractPoliciesFromMsg() []struct { - name string - errResp *ErrorsResp - expect []Policy -} { - tests := []struct { - name string - errResp *ErrorsResp - expect []Policy - }{ - { - name: "one policy", - errResp: &ErrorsResp{ - Errors: []ErrorResp{ - { - Status: 403, - Message: "Package test:1.0.0 download was blocked by JFrog Packages Curation service due to the following policies violated {policy1, condition1}.", - }, - }, - }, - expect: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - }, - { - name: "one policy", - errResp: &ErrorsResp{ - Errors: []ErrorResp{ - { - Status: 403, - Message: "Package test:1.0.0 download was blocked by JFrog Packages Curation service due to the following policies violated {policy1, condition1, Package is 3339 days old, Upgrade to version 0.2.4 (latest)}.", - }, - }, - }, - expect: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - Explanation: "Package is 3339 days old", - Recommendation: "Upgrade to version 0.2.4 (latest)", - }, - }, - }, - { - name: "two policies", - errResp: &ErrorsResp{ - Errors: []ErrorResp{ - { - Status: 403, - Message: "Package test:1.0.0 download was blocked by JFrog Packages Curation service due to" + - " the following policies violated {policy1, condition1}, {policy2, condition2}.", - }, - }, - }, - expect: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - { - Policy: "policy2", - Condition: "condition2", - }, - }, - }, - { - name: "no policies", - errResp: &ErrorsResp{ - Errors: []ErrorResp{ - { - Status: 403, - Message: "not the expected message format.", - }, - }, - }, - expect: nil, - }, - } - return tests -} - -func TestGetNameScopeAndVersion(t *testing.T) { - tests := []struct { - name string - componentId string - artiUrl string - repo string - tech string - wantDownloadUrl string - wantName string - wantVersion string - wantScope string - }{ - { - name: "npm component", - componentId: "npm://test:1.0.0", - artiUrl: "http://localhost:8000/artifactory", - repo: "npm", - tech: coreutils.Npm.String(), - wantDownloadUrl: "http://localhost:8000/artifactory/api/npm/npm/test/-/test-1.0.0.tgz", - wantName: "test", - wantVersion: "1.0.0", - }, - { - name: "npm component with scope", - componentId: "npm://dev/test:1.0.0", - artiUrl: "http://localhost:8000/artifactory", - repo: "npm", - tech: coreutils.Npm.String(), - wantDownloadUrl: "http://localhost:8000/artifactory/api/npm/npm/dev/test/-/test-1.0.0.tgz", - wantName: "test", - wantVersion: "1.0.0", - wantScope: "dev", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - gotDownloadUrl, gotName, gotScope, gotVersion := getNpmNameScopeAndVersion(tt.componentId, tt.artiUrl, tt.repo, tt.repo) - assert.Equal(t, tt.wantDownloadUrl, gotDownloadUrl, "getNameScopeAndVersion() gotDownloadUrl = %v, want %v", gotDownloadUrl, tt.wantDownloadUrl) - assert.Equal(t, tt.wantName, gotName, "getNpmNameScopeAndVersion() gotName = %v, want %v", gotName, tt.wantName) - assert.Equal(t, tt.wantScope, gotScope, "getNpmNameScopeAndVersion() gotScope = %v, want %v", gotScope, tt.wantScope) - assert.Equal(t, tt.wantVersion, gotVersion, "getNpmNameScopeAndVersion() gotVersion = %v, want %v", gotVersion, tt.wantVersion) - }) - } -} - -func TestTreeAnalyzerFillGraphRelations(t *testing.T) { - tests := getTestCasesForFillGraphRelations() - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - nc := &treeAnalyzer{ - url: "http://localhost:8046/artifactory", - repo: "npm-repo", - tech: "npm", - } - var packageStatus []*PackageStatus - preProcessedMap := fillSyncedMap(tt.givenMap) - nc.fillGraphRelations(tt.givenGraph, preProcessedMap, &packageStatus, "", "", datastructures.MakeSet[string](), true) - sort.Slice(packageStatus, func(i, j int) bool { - if packageStatus[i].BlockedPackageUrl == packageStatus[j].BlockedPackageUrl { - return packageStatus[i].ParentName < packageStatus[j].ParentName - } - return packageStatus[i].BlockedPackageUrl < packageStatus[j].BlockedPackageUrl - }) - sort.Slice(tt.expectedPackagesStatus, func(i, j int) bool { - if tt.expectedPackagesStatus[i].BlockedPackageUrl == tt.expectedPackagesStatus[j].BlockedPackageUrl { - return tt.expectedPackagesStatus[i].ParentName < tt.expectedPackagesStatus[j].ParentName - } - return tt.expectedPackagesStatus[i].BlockedPackageUrl < tt.expectedPackagesStatus[j].BlockedPackageUrl - }) - assert.Equal(t, tt.expectedPackagesStatus, packageStatus) - }) - } -} - -func getTestCasesForFillGraphRelations() []struct { - name string - givenGraph *xrayUtils.GraphNode - givenMap []*PackageStatus - expectedPackagesStatus []*PackageStatus -} { - tests := []struct { - name string - givenGraph *xrayUtils.GraphNode - givenMap []*PackageStatus - expectedPackagesStatus []*PackageStatus - }{ - { - name: "block indirect", - givenGraph: &xrayUtils.GraphNode{ - Id: "npm://root-test", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "npm://test-parent:1.0.0", - Nodes: []*xrayUtils.GraphNode{ - {Id: "npm://test-child:2.0.0"}, - }, - }, - }, - }, - givenMap: []*PackageStatus{ - { - Action: "blocked", - BlockedPackageUrl: "http://localhost:8046/artifactory/api/npm/npm-repo/test-child/-/test-child-2.0.0.tgz", - PackageName: "test-child", - PackageVersion: "2.0.0", - BlockingReason: "Policy violations", - PkgType: "npm", - Policy: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - }, - }, - expectedPackagesStatus: []*PackageStatus{ - { - Action: "blocked", - BlockedPackageUrl: "http://localhost:8046/artifactory/api/npm/npm-repo/test-child/-/test-child-2.0.0.tgz", - PackageName: "test-child", - PackageVersion: "2.0.0", - BlockingReason: "Policy violations", - PkgType: "npm", - Policy: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - ParentName: "test-parent", - ParentVersion: "1.0.0", - DepRelation: "indirect", - }, - }, - }, - { - name: "no duplications", - givenGraph: &xrayUtils.GraphNode{ - Id: "npm://root-test", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "npm://test-parent:1.0.0", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "npm://test-child:2.0.0", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "npm://@dev/test-child:4.0.0", - }, - }, - }, - { - Id: "npm://test-child:3.0.0", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "npm://@dev/test-child:4.0.0", - }, - }, - }, - { - Id: "npm://@dev/test-child:5.0.0", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "npm://test-child:4.0.0", - }, - }, - }, - }, - }, - { - Id: "npm://@dev/test-parent:1.0.0", - Nodes: []*xrayUtils.GraphNode{ - { - Id: "npm://test-child:4.0.0", - }, - }, - }, - }, - }, - givenMap: []*PackageStatus{ - { - Action: "blocked", - BlockedPackageUrl: "http://localhost:8046/artifactory/api/npm/npm-repo/@dev/test-child/-/test-child-4.0.0.tgz", - PackageName: "@dev/test-child", - PackageVersion: "4.0.0", - BlockingReason: "Policy violations", - PkgType: "npm", - Policy: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - }, - { - Action: "blocked", - BlockedPackageUrl: "http://localhost:8046/artifactory/api/npm/npm-repo/test-child/-/test-child-4.0.0.tgz", - PackageName: "test-child", - PackageVersion: "4.0.0", - BlockingReason: "Policy violations", - PkgType: "npm", - Policy: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - }, - }, - expectedPackagesStatus: []*PackageStatus{ - { - Action: "blocked", - BlockedPackageUrl: "http://localhost:8046/artifactory/api/npm/npm-repo/test-child/-/test-child-4.0.0.tgz", - PackageName: "test-child", - PackageVersion: "4.0.0", - BlockingReason: "Policy violations", - PkgType: "npm", - Policy: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - ParentName: "test-parent", - ParentVersion: "1.0.0", - DepRelation: "indirect", - }, - { - Action: "blocked", - BlockedPackageUrl: "http://localhost:8046/artifactory/api/npm/npm-repo/test-child/-/test-child-4.0.0.tgz", - PackageName: "test-child", - PackageVersion: "4.0.0", - BlockingReason: "Policy violations", - PkgType: "npm", - Policy: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - ParentName: "@dev/test-parent", - ParentVersion: "1.0.0", - DepRelation: "indirect", - }, - { - Action: "blocked", - BlockedPackageUrl: "http://localhost:8046/artifactory/api/npm/npm-repo/@dev/test-child/-/test-child-4.0.0.tgz", - PackageName: "@dev/test-child", - PackageVersion: "4.0.0", - BlockingReason: "Policy violations", - PkgType: "npm", - Policy: []Policy{ - { - Policy: "policy1", - Condition: "condition1", - }, - }, - ParentName: "test-parent", - ParentVersion: "1.0.0", - DepRelation: "indirect", - }, - }, - }, - } - return tests -} - -func fillSyncedMap(pkgStatus []*PackageStatus) *sync.Map { - syncMap := sync.Map{} - for _, value := range pkgStatus { - syncMap.Store(value.BlockedPackageUrl, value) - } - return &syncMap -} - -func TestDoCurationAudit(t *testing.T) { - tests := getTestCasesForDoCurationAudit() - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - currentDir, err := os.Getwd() - assert.NoError(t, err) - configurationDir := filepath.Join("..", "testdata", "npm-project", ".jfrog") - callback := clienttestutils.SetEnvWithCallbackAndAssert(t, coreutils.HomeDir, filepath.Join(currentDir, configurationDir)) - defer callback() - - mockServer, config := curationServer(t, tt.expectedRequest, tt.requestToFail, tt.requestToError) - defer mockServer.Close() - configFilePath := WriteServerDetailsConfigFileBytes(t, config.ArtifactoryUrl, configurationDir) - defer func() { - assert.NoError(t, fileutils.RemoveTempDir(configFilePath)) - }() - curationCmd := NewCurationAuditCommand() - curationCmd.parallelRequests = 3 - curationCmd.SetIgnoreConfigFile(true) - rootDir, err := os.Getwd() - assert.NoError(t, err) - // Set the working dir for npm project. - callback = clienttestutils.ChangeDirWithCallback(t, rootDir, "../testdata/npm-project") - defer callback() - results := map[string][]*PackageStatus{} - if tt.requestToError == nil { - assert.NoError(t, curationCmd.doCurateAudit(results)) - } else { - gotError := curationCmd.doCurateAudit(results) - assert.Error(t, gotError) - startUrl := strings.Index(tt.expectedError, "/") - assert.GreaterOrEqual(t, startUrl, 0) - errMsgExpected := tt.expectedError[:startUrl] + config.ArtifactoryUrl + - tt.expectedError[strings.Index(tt.expectedError, "/")+1:] - assert.EqualError(t, gotError, errMsgExpected) - } - // Add the mock server to the expected blocked message url - for index := range tt.expectedResp { - tt.expectedResp[index].BlockedPackageUrl = fmt.Sprintf("%s%s", strings.TrimSuffix(config.GetArtifactoryUrl(), "/"), tt.expectedResp[index].BlockedPackageUrl) - } - gotResults := results["npm_test:1.0.0"] - assert.Equal(t, tt.expectedResp, gotResults) - for _, requestDone := range tt.expectedRequest { - assert.True(t, requestDone) - } - }) - } -} - -func getTestCasesForDoCurationAudit() []struct { - name string - expectedRequest map[string]bool - requestToFail map[string]bool - expectedResp []*PackageStatus - requestToError map[string]bool - expectedError string -} { - tests := []struct { - name string - expectedRequest map[string]bool - requestToFail map[string]bool - expectedResp []*PackageStatus - requestToError map[string]bool - expectedError string - }{ - { - name: "npm tree - two blocked package ", - expectedRequest: map[string]bool{ - "/api/npm/npms/lightweight/-/lightweight-0.1.0.tgz": false, - "/api/npm/npms/underscore/-/underscore-1.13.6.tgz": false, - }, - requestToFail: map[string]bool{ - "/api/npm/npms/underscore/-/underscore-1.13.6.tgz": false, - }, - expectedResp: []*PackageStatus{ - { - Action: "blocked", - ParentVersion: "1.13.6", - ParentName: "underscore", - BlockedPackageUrl: "/api/npm/npms/underscore/-/underscore-1.13.6.tgz", - PackageName: "underscore", - PackageVersion: "1.13.6", - BlockingReason: "Policy violations", - PkgType: "npm", - DepRelation: "direct", - Policy: []Policy{ - { - Policy: "pol1", - Condition: "cond1", - }, - }, - }, - }, - }, - { - name: "npm tree - two blocked one error", - expectedRequest: map[string]bool{ - "/api/npm/npms/lightweight/-/lightweight-0.1.0.tgz": false, - "/api/npm/npms/underscore/-/underscore-1.13.6.tgz": false, - }, - requestToFail: map[string]bool{ - "/api/npm/npms/underscore/-/underscore-1.13.6.tgz": false, - }, - requestToError: map[string]bool{ - "/api/npm/npms/lightweight/-/lightweight-0.1.0.tgz": false, - }, - expectedResp: []*PackageStatus{ - { - Action: "blocked", - ParentVersion: "1.13.6", - ParentName: "underscore", - BlockedPackageUrl: "/api/npm/npms/underscore/-/underscore-1.13.6.tgz", - PackageName: "underscore", - PackageVersion: "1.13.6", - BlockingReason: "Policy violations", - PkgType: "npm", - DepRelation: "direct", - Policy: []Policy{ - { - Policy: "pol1", - Condition: "cond1", - }, - }, - }, - }, - expectedError: fmt.Sprintf("failed sending HEAD request to %s for package '%s'. Status-code: %v. "+ - "Cause: executor timeout after 2 attempts with 0 milliseconds wait intervals", - "/api/npm/npms/lightweight/-/lightweight-0.1.0.tgz", "lightweight:0.1.0", http.StatusInternalServerError), - }, - } - return tests -} - -func curationServer(t *testing.T, expectedRequest map[string]bool, requestToFail map[string]bool, requestToError map[string]bool) (*httptest.Server, *config.ServerDetails) { - mapLockReadWrite := sync.Mutex{} - serverMock, config, _ := coretests.CreateRtRestsMockServer(t, func(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodHead { - mapLockReadWrite.Lock() - if _, exist := expectedRequest[r.RequestURI]; exist { - expectedRequest[r.RequestURI] = true - } - mapLockReadWrite.Unlock() - if _, exist := requestToFail[r.RequestURI]; exist { - w.WriteHeader(http.StatusForbidden) - } - if _, exist := requestToError[r.RequestURI]; exist { - w.WriteHeader(http.StatusInternalServerError) - } - } - if r.Method == http.MethodGet { - if _, exist := requestToFail[r.RequestURI]; exist { - w.WriteHeader(http.StatusForbidden) - _, err := w.Write([]byte("{\n \"errors\": [\n {\n \"status\": 403,\n " + - "\"message\": \"Package download was blocked by JFrog Packages " + - "Curation service due to the following policies violated {pol1, cond1}\"\n }\n ]\n}")) - assert.NoError(t, err) - } - } - }) - return serverMock, config -} - -func WriteServerDetailsConfigFileBytes(t *testing.T, url string, configPath string) string { - serverDetails := config.ConfigV5{ - Servers: []*config.ServerDetails{ - { - User: "admin", - Password: "password", - ServerId: "test", - Url: url, - ArtifactoryUrl: url, - }, - }, - Version: "v" + strconv.Itoa(coreutils.GetCliConfigVersion()), - } - - detailsByte, err := json.Marshal(serverDetails) - assert.NoError(t, err) - confFilePath := filepath.Join(configPath, "jfrog-cli.conf.v"+strconv.Itoa(coreutils.GetCliConfigVersion())) - assert.NoError(t, os.WriteFile(confFilePath, detailsByte, 0644)) - return confFilePath -} diff --git a/xray/commands/curl/curl.go b/xray/commands/curl/curl.go deleted file mode 100644 index 54a047a24..000000000 --- a/xray/commands/curl/curl.go +++ /dev/null @@ -1,17 +0,0 @@ -package curl - -import ( - "github.com/jfrog/jfrog-cli-core/v2/common/commands" -) - -type XrCurlCommand struct { - commands.CurlCommand -} - -func NewXrCurlCommand(curlCommand commands.CurlCommand) *XrCurlCommand { - return &XrCurlCommand{curlCommand} -} - -func (curlCmd *XrCurlCommand) CommandName() string { - return "xr_curl" -} diff --git a/xray/commands/offlineupdate/offlineupdate.go b/xray/commands/offlineupdate/offlineupdate.go deleted file mode 100644 index 3a9a7d401..000000000 --- a/xray/commands/offlineupdate/offlineupdate.go +++ /dev/null @@ -1,476 +0,0 @@ -package offlineupdate - -import ( - "encoding/json" - "errors" - "fmt" - "golang.org/x/exp/maps" - "net/http" - "net/url" - "os" - "path/filepath" - "sort" - "strconv" - "strings" - - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-client-go/http/httpclient" - "github.com/jfrog/jfrog-client-go/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/io/httputils" - "github.com/jfrog/jfrog-client-go/utils/log" -) - -const ( - Vulnerability = "__vuln" - Component = "__comp" - JxrayDefaultBaseUrl = "https://jxray.jfrog.io/" - JxrayApiBundles = "api/v1/updates/bundles" - JxrayApiOnboarding = "api/v1/updates/onboarding" - periodicState = "periodic" - onboardingState = "onboarding" -) - -func OfflineUpdate(flags *OfflineUpdatesFlags) error { - if shouldUseDBSyncV3(flags) { - return handleDBSyncV3OfflineUpdate(flags) - } - return handleDBSyncV1OfflineUpdate(flags) -} - -// Should use DBSync version 3 if the 'stream' flag was specified. -func shouldUseDBSyncV3(flags *OfflineUpdatesFlags) bool { - return flags.Stream != "" -} - -func handleDBSyncV1OfflineUpdate(flags *OfflineUpdatesFlags) error { - updatesUrl, err := buildUpdatesUrl(flags) - if err != nil { - return err - } - vulnerabilities, components, lastUpdate, err := getFilesList(updatesUrl, flags) - if err != nil { - return err - } - zipSuffix := "_" + strconv.FormatInt(lastUpdate, 10) - xrayTempDir, err := getXrayTempDir() - if err != nil { - return err - } - - if flags.Target != "" && (len(vulnerabilities) > 0 || len(components) > 0) { - err = os.MkdirAll(flags.Target, 0777) - if errorutils.CheckError(err) != nil { - return err - } - } - - if len(vulnerabilities) > 0 { - log.Info("Downloading vulnerabilities...") - err := saveData(xrayTempDir, "vuln", zipSuffix, flags.Target, vulnerabilities) - if err != nil { - return err - } - } else { - log.Info("There are no new vulnerabilities.") - } - - if len(components) > 0 { - log.Info("Downloading components...") - err := saveData(xrayTempDir, "comp", zipSuffix, flags.Target, components) - if err != nil { - return err - } - } else { - log.Info("There are no new components.") - } - return nil -} - -func getURLsToDownloadDBSyncV3(responseBody []byte, isPeriodicUpdate bool) ([]string, error) { - var onboardingResponse OnboardingResponse - var periodicResponse V3PeriodicUpdateResponse - var urlsToDownload []string - var err error - if isPeriodicUpdate { - err = json.Unmarshal(responseBody, &periodicResponse) - if err != nil { - return nil, errorutils.CheckError(err) - } - for _, packageUrl := range periodicResponse.Update { - urlsToDownload = append(urlsToDownload, packageUrl.DownloadUrl) - logV3UpdateFileChecksum(packageUrl) - } - for _, packageUrl := range periodicResponse.Deletion { - urlsToDownload = append(urlsToDownload, packageUrl.DownloadUrl) - logV3UpdateFileChecksum(packageUrl) - } - } else { - err = json.Unmarshal(responseBody, &onboardingResponse) - if err != nil { - return nil, errorutils.CheckError(err) - } - for _, packageUrl := range onboardingResponse { - urlsToDownload = append(urlsToDownload, packageUrl.DownloadUrl) - logV3UpdateFileChecksum(packageUrl) - } - } - return urlsToDownload, nil -} - -func getV3UpdateFilename(updateFileItem V3UpdateResponseItem) string { - parsedUrl, err := url.Parse(updateFileItem.DownloadUrl) - if err != nil { - return updateFileItem.DownloadUrl - } - pathParts := strings.Split(parsedUrl.Path, "/") - return pathParts[len(pathParts)-1] -} - -func logV3UpdateFileChecksum(updateFileItem V3UpdateResponseItem) { - if updateFileItem.Sha256 == "" { - return - } - filename := getV3UpdateFilename(updateFileItem) - log.Info(fmt.Sprintf("Got info on update package [%s] with sha256 [%s]", filename, updateFileItem.Sha256)) -} - -func createV3MetadataFile(state string, body []byte, destFolder string) (err error) { - metaDataFileName := state + ".json" - metaDataFile := filepath.Join(destFolder, metaDataFileName) - f, err := os.Create(metaDataFile) - if err != nil { - return errorutils.CheckError(err) - } - defer func() { - if cerr := f.Close(); err != nil { - err = cerr - } - }() - _, err = f.Write(body) - return errorutils.CheckError(err) -} - -func handleDBSyncV3OfflineUpdate(flags *OfflineUpdatesFlags) (err error) { - url := buildUrlDBSyncV3(flags) - log.Info("Getting updates...") - headers := make(map[string]string) - headers["X-Xray-License"] = flags.License - httpClientDetails := httputils.HttpClientDetails{ - Headers: headers, - } - client, err := httpclient.ClientBuilder().SetRetries(3).Build() - if err != nil { - return err - } - resp, body, _, err := client.SendGet(url, false, httpClientDetails, "") - if errorutils.CheckError(err) != nil { - return err - } - if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil { - return err - } - - urlsToDownload, err := getURLsToDownloadDBSyncV3(body, flags.IsPeriodicUpdate) - if err != nil { - return err - } - - var state string - if flags.IsPeriodicUpdate { - state = periodicState - } else { - state = onboardingState - } - dataDir, err := os.MkdirTemp(flags.Target, "xray_downloaded_data") - if err != nil { - return err - } - defer func() { - if cerr := fileutils.RemoveTempDir(dataDir); err == nil { - err = cerr - } - }() - err = downloadData(urlsToDownload, dataDir, createXrayFileNameFromUrlV3) - if err != nil { - return err - } - - err = createV3MetadataFile(state, body, dataDir) - if err != nil { - return err - } - - packageName := "xray_" + flags.Stream + "_update_package" + "_" + state - err = createZipArchive(dataDir, flags.Target, packageName, "") - if err != nil { - return err - } - return nil -} - -func buildUrlDBSyncV3(flags *OfflineUpdatesFlags) string { - streams := NewValidStreams() - url := getJxRayBaseUrl() + "api/v3/updates/" - // Build JAS urls if needed. - if flags.Stream == streams.GetExposuresStream() { - url += streams.GetExposuresStream() + "/" - } else if flags.Stream == streams.GetContextualAnalysisStream() { - url += streams.GetContextualAnalysisStream() + "/" - } - - if flags.IsPeriodicUpdate { - return url + periodicState - } else { - return url + onboardingState - } -} - -func getJxRayBaseUrl() string { - jxRayBaseUrl := os.Getenv("JFROG_CLI_JXRAY_BASE_URL") - jxRayBaseUrl = utils.AddTrailingSlashIfNeeded(jxRayBaseUrl) - if jxRayBaseUrl == "" { - jxRayBaseUrl = JxrayDefaultBaseUrl - } - return jxRayBaseUrl -} - -func getUpdatesBaseUrl(datesSpecified bool) string { - jxRayBaseUrl := getJxRayBaseUrl() - if datesSpecified { - return jxRayBaseUrl + JxrayApiBundles - } - return jxRayBaseUrl + JxrayApiOnboarding -} - -func buildUpdatesUrl(flags *OfflineUpdatesFlags) (string, error) { - var queryParams string - datesSpecified := flags.From > 0 && flags.To > 0 - if datesSpecified { - if err := validateDates(flags.From, flags.To); err != nil { - return "", err - } - queryParams += fmt.Sprintf("from=%v&to=%v", flags.From, flags.To) - } - if flags.Version != "" { - if queryParams != "" { - queryParams += "&" - } - queryParams += fmt.Sprintf("version=%v", flags.Version) - } - url := getUpdatesBaseUrl(datesSpecified) - if queryParams != "" { - url += "?" + queryParams - } - return url, nil -} - -func validateDates(from, to int64) error { - if from < 0 || to < 0 { - err := errors.New("invalid dates") - return errorutils.CheckError(err) - } - if from > to { - err := errors.New("invalid dates range") - return errorutils.CheckError(err) - } - return nil -} - -func getXrayTempDir() (string, error) { - xrayDir := filepath.Join(coreutils.GetCliPersistentTempDirPath(), "jfrog", "xray") - if err := os.MkdirAll(xrayDir, 0777); err != nil { - return "", errorutils.CheckError(err) - } - return xrayDir, nil -} - -func downloadData(urlsList []string, dataDir string, fileNameFromUrlFunc func(string) (string, error)) error { - log.Info(fmt.Sprintf("Downloading updated packages to %s.", dataDir)) - for _, url := range urlsList { - fileName, err := fileNameFromUrlFunc(url) - if err != nil { - return err - } - client, err := httpclient.ClientBuilder().SetRetries(3).Build() - if err != nil { - log.Error(fmt.Sprintf("Couldn't download from %s", url)) - return err - } - - details := &httpclient.DownloadFileDetails{ - FileName: fileName, - DownloadPath: url, - LocalPath: dataDir, - LocalFileName: fileName} - response, _, err := client.SendHead(url, httputils.HttpClientDetails{}, "") - if err != nil { - return fmt.Errorf("couldn't get content length of %s. Error: %s", url, err.Error()) - } - log.Info(fmt.Sprintf("Downloading updated package from %s. Content size: %.4f MB.", url, float64(response.ContentLength)/1000000)) - _, err = client.DownloadFile(details, "", httputils.HttpClientDetails{}, false, false) - if err != nil { - return errorutils.CheckErrorf("Couldn't download from %s. Error: %s", url, err.Error()) - } - } - log.Info("Download completed.") - return nil -} - -func createZipArchive(dataDir, targetPath, filesPrefix, zipSuffix string) error { - log.Info("Zipping files.") - err := fileutils.ZipFolderFiles(dataDir, filepath.Join(targetPath, filesPrefix+zipSuffix+".zip")) - if err != nil { - return err - } - log.Info("Done zipping files.") - return nil -} - -func saveData(xrayTmpDir, filesPrefix, zipSuffix, targetPath string, urlsList []string) (err error) { - dataDir, err := os.MkdirTemp(xrayTmpDir, filesPrefix) - if err != nil { - return err - } - defer func() { - if cerr := fileutils.RemoveTempDir(dataDir); cerr != nil && err == nil { - err = cerr - } - }() - err = downloadData(urlsList, dataDir, createXrayFileNameFromUrl) - if err != nil { - return err - } - err = createZipArchive(dataDir, targetPath, filesPrefix, zipSuffix) - if err != nil { - return err - } - return nil -} - -func getUrlSections(url string) []string { - index := strings.Index(url, "?") - if index != -1 { - url = url[:index] - } - index = strings.Index(url, ";") - if index != -1 { - url = url[:index] - } - return strings.Split(url, "/") -} - -func createXrayFileNameFromUrlV3(url string) (string, error) { - sections := getUrlSections(url) - length := len(sections) - return sections[length-1], nil -} - -func createXrayFileNameFromUrl(url string) (fileName string, err error) { - sections := getUrlSections(url) - length := len(sections) - if length < 2 { - err = errorutils.CheckErrorf("Unexpected URL format: %s", url) - return - } - fileName = fmt.Sprintf("%s__%s", sections[length-2], sections[length-1]) - return -} - -func getFilesList(updatesUrl string, flags *OfflineUpdatesFlags) (vulnerabilities []string, components []string, lastUpdate int64, err error) { - log.Info("Getting updates...") - headers := make(map[string]string) - headers["X-Xray-License"] = flags.License - httpClientDetails := httputils.HttpClientDetails{ - Headers: headers, - } - client, err := httpclient.ClientBuilder().SetRetries(3).Build() - if err != nil { - return - } - resp, body, _, err := client.SendGet(updatesUrl, false, httpClientDetails, "") - if errorutils.CheckError(err) != nil { - return - } - if err = errorutils.CheckResponseStatusWithBody(resp, body, http.StatusOK); err != nil { - return - } - - var urls FilesList - err = json.Unmarshal(body, &urls) - if err != nil { - err = errorutils.CheckErrorf("Failed parsing json response: " + string(body)) - return - } - - for _, v := range urls.Urls { - if strings.Contains(v, Vulnerability) { - vulnerabilities = append(vulnerabilities, v) - } else if strings.Contains(v, Component) { - components = append(components, v) - } - } - lastUpdate = urls.LastUpdate - return -} - -// ValidStreams represents the valid values that can be provided to the 'stream' flag during offline updates. -type ValidStreams struct { - StreamsMap map[string]bool -} - -func NewValidStreams() *ValidStreams { - validStreams := &ValidStreams{StreamsMap: map[string]bool{}} - validStreams.StreamsMap[validStreams.GetPublicDataStream()] = true - validStreams.StreamsMap[validStreams.GetExposuresStream()] = true - validStreams.StreamsMap[validStreams.GetContextualAnalysisStream()] = true - return validStreams -} - -func (vs *ValidStreams) GetValidStreamsString() string { - streams := maps.Keys(vs.StreamsMap) - sort.Sort(sort.Reverse(sort.StringSlice(streams))) - streamsStr := strings.Join(streams[0:len(streams)-1], ", ") - return fmt.Sprintf("%s and %s", streamsStr, streams[len(streams)-1]) -} - -func (vs *ValidStreams) GetPublicDataStream() string { - return "public_data" -} - -func (vs *ValidStreams) GetExposuresStream() string { - return "exposures" -} - -func (vs *ValidStreams) GetContextualAnalysisStream() string { - return "contextual_analysis" -} - -type OfflineUpdatesFlags struct { - License string - From int64 - To int64 - Version string - Target string - Stream string - IsPeriodicUpdate bool -} - -type FilesList struct { - LastUpdate int64 - Urls []string -} - -type V3UpdateResponseItem struct { - DownloadUrl string `json:"download_url"` - Timestamp int64 `json:"timestamp"` - Sha256 string `json:"sha256,omitempty"` -} - -type V3PeriodicUpdateResponse struct { - Update []V3UpdateResponseItem `json:"update"` - Deletion []V3UpdateResponseItem `json:"deletion"` -} - -type OnboardingResponse []V3UpdateResponseItem diff --git a/xray/commands/offlineupdate/offlineupdate_test.go b/xray/commands/offlineupdate/offlineupdate_test.go deleted file mode 100644 index ef26efa5d..000000000 --- a/xray/commands/offlineupdate/offlineupdate_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package offlineupdate - -import ( - "github.com/magiconair/properties/assert" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestCreateXrayFileNameFromUrl(t *testing.T) { - tests := []struct { - url string - fileName string - }{ - {url: "https://dl.bintray.com/jfrog/jxray-data-dumps/2018-05/onboarding__vuln9__.json?expiry=1528473414900&id=K8v%2BJBItDfdcU9%2BBa2lxhmJRitQZPWsH89MtXs3pYfWKvRUwGNuUB8vcHv7EvJydaJGrwKm%2B%2FYAIAjMR3TaTm5VIRouiChTABPYbDNTNf%2F4%3D&signature=ePBfZuVZBljVvQTFHIpPH6lo7Qby%2Ban44resdLMo5f16W%2FX4Ou6gOleBHo5ViyWFy1tnFoPopk1XIQgB918ZFg%3D%3D", fileName: "2018-05__onboarding__vuln9__.json"}, - {url: "https://dl.bintray.com/jfrog/jxray-data-dumps/2018-06-07/onboarding__vulnR1_1__.zip?expiry=1528711288481&id=K8v%2BJBItDfdcU9%2BBa2lxhmJRitQZPWsH89MtXs3pYfWKvRUwGNuUB8vcHv7EvJyd3g6UkTiZXV2mGxN1HD6KtovwjhKr4IdWuYKciRkl1agY487O8kk4jIOibc7paR2t&signature=eiB%2FcOMjWKjJdSybFr%2BPo56FmusgHvzvRMTnHSuHwIWvY5QnX2dIumsbIlMaVvL9xzoQObWHJ%2FMZyWnTVcv67g%3D%3D", fileName: "2018-06-07__onboarding__vulnR1_1__.zip"}, - {url: "https://dl.bintray.com/jfrog/jxray-data-dumps/2018-05/onboarding__vulnR1_16__.zip?expiry=1528711287386&id=K8v%2BJBItDfdcU9%2BBa2lxhmJRitQZPWsH89MtXs3pYfWKvRUwGNuUB8vcHv7EvJydaJGrwKm%2B%2FYAIAjMR3TaTm9Wd2NqK5BiRQc33JGl4b0DZ9e%2B1cTtPyVtm5jxX9kIL&signature=HQKhgmRBtvJ1EwomgggR47M9TAWSegvWFUw9NItI5Cj22EZ2BqbhxIfcVAti8WJTjsKfAS2ap7yb%2BBmQilnSng%3D%3D", fileName: "2018-05__onboarding__vulnR1_16__.zip"}, - {url: "https://dl.bintray.com/jfrog/jxray-data-dumps/2018-06-07/onboarding__vulnS1_1__.zip?expiry=1528711288397&id=K8v%2BJBItDfdcU9%2BBa2lxhmJRitQZPWsH89MtXs3pYfWKvRUwGNuUB8vcHv7EvJyd3g6UkTiZXV2mGxN1HD6KtozvQ8zhzPTSbLjftsv4zhgY487O8kk4jIOibc7paR2t&signature=P9XPWugJkqz5ekpEQrOkAbIsogAB7EOgq7ou1%2BTAPSOFfsKA9j1I%2Fhj94y%2BoIipYRtUUtSGCqXyRP%2B%2BG%2FscwmA%3D%3D", fileName: "2018-06-07__onboarding__vulnS1_1__.zip"}, - } - - for _, test := range tests { - fileName, err := createXrayFileNameFromUrl(test.url) - if err != nil { - t.Error(err) - } - assert.Equal(t, fileName, test.fileName) - } -} - -// DBSync V3 test data - -var periodicUpdateResponse = "[{\"download_url\":\"some_url_to_package_update\",\"timestamp\":1234}]" -var periodicDeletionResponse = "[{\"download_url\":\"some_url_to_package_delete\",\"timestamp\":1234}]" -var periodicUpdateResponseSection = "\"update\":" + periodicUpdateResponse -var periodicDeleteResponseSection = "\"deletion\":" + periodicDeletionResponse - -var periodicResponse = "{" + periodicUpdateResponseSection + "," + periodicDeleteResponseSection + "}" -var onboardingResponse = "[{\"download_url\":\"some_url_to_package_onboard\",\"timestamp\":1234}]" - -func TestBuildUrlDBSyncV3(t *testing.T) { - streams := NewValidStreams() - tests := []struct { - flags *OfflineUpdatesFlags - expected string - }{ - {&OfflineUpdatesFlags{Stream: streams.GetPublicDataStream(), IsPeriodicUpdate: true}, "api/v3/updates/periodic"}, - {&OfflineUpdatesFlags{Stream: streams.GetPublicDataStream(), IsPeriodicUpdate: false}, "api/v3/updates/onboarding"}, - {&OfflineUpdatesFlags{Stream: streams.GetExposuresStream(), IsPeriodicUpdate: true}, "api/v3/updates/exposures/periodic"}, - {&OfflineUpdatesFlags{Stream: streams.GetExposuresStream(), IsPeriodicUpdate: false}, "api/v3/updates/exposures/onboarding"}, - {&OfflineUpdatesFlags{Stream: streams.GetContextualAnalysisStream(), IsPeriodicUpdate: true}, "api/v3/updates/contextual_analysis/periodic"}, - {&OfflineUpdatesFlags{Stream: streams.GetContextualAnalysisStream(), IsPeriodicUpdate: false}, "api/v3/updates/contextual_analysis/onboarding"}, - } - for _, test := range tests { - url := buildUrlDBSyncV3(test.flags) - assert.Equal(t, strings.HasSuffix(url, test.expected), true) - } -} - -func TestDBSyncV3getURLsToDownload(t *testing.T) { - tests := []struct { - serverResponse []byte - isPeriodic bool - expected []string - }{ - {[]byte(periodicResponse), true, []string{"some_url_to_package_update", "some_url_to_package_delete"}}, - {[]byte(onboardingResponse), false, []string{"some_url_to_package_onboard"}}, - } - - for _, test := range tests { - urls, err := getURLsToDownloadDBSyncV3(test.serverResponse, test.isPeriodic) - if err != nil { - t.Error(err) - } - assert.Equal(t, urls, test.expected) - } -} - -func TestDBSyncV3createXrayFileNameFromURL(t *testing.T) { - tests := []struct { - url string - expected string - }{{"a/b/c/d.zip", "d.zip"}, {"x/y.zip", "y.zip"}} - - for _, test := range tests { - expected, err := createXrayFileNameFromUrlV3(test.url) - if err != nil { - t.Error(err) - } - assert.Equal(t, expected, test.expected) - } -} - -func TestDBSyncV3createV3MetadataFile(t *testing.T) { - tests := []struct { - serverResponse []byte - state string - expectedFilename string - }{ - {[]byte(periodicResponse), periodicState, periodicState + ".json"}, - {[]byte(onboardingResponse), onboardingState, onboardingState + ".json"}, - } - - for _, test := range tests { - dir := t.TempDir() - err := createV3MetadataFile(test.state, test.serverResponse, dir) - if err != nil { - t.Error(err) - } - fileContent, err := os.ReadFile(filepath.Join(dir, test.expectedFilename)) - if err != nil { - t.Error(err) - } - assert.Equal(t, fileContent, test.serverResponse) - } - -} - -func TestGetValidStreamsString(t *testing.T) { - validStreams := NewValidStreams() - assert.Equal(t, 3, len(validStreams.StreamsMap)) - assert.Equal(t, validStreams.GetValidStreamsString(), "public_data, exposures and contextual_analysis") -} - -func TestLogV3UpdateFileChecksum(t *testing.T) { - tests := []struct { - item V3UpdateResponseItem - expected string - }{ - {item: V3UpdateResponseItem{DownloadUrl: "http://www.example.com/some/path/filename.tar.zst", Sha256: "0000000000000000000000000000000000000000000000000000000000000000"}, expected: "filename.tar.zst"}, - {item: V3UpdateResponseItem{DownloadUrl: ">bad_url%+o", Sha256: "0000000000000000000000000000000000000000000000000000000000000000"}, expected: ">bad_url%+o"}, - {item: V3UpdateResponseItem{DownloadUrl: "http://www.example.com/some/path/filename.tar.zst"}, expected: "filename.tar.zst"}, - } - - for _, test := range tests { - assert.Equal(t, test.expected, getV3UpdateFilename(test.item)) - } -} diff --git a/xray/commands/scan/buildscan.go b/xray/commands/scan/buildscan.go deleted file mode 100644 index 675bc0ba1..000000000 --- a/xray/commands/scan/buildscan.go +++ /dev/null @@ -1,168 +0,0 @@ -package scan - -import ( - "errors" - - "github.com/jfrog/jfrog-cli-core/v2/common/build" - "github.com/jfrog/jfrog-cli-core/v2/common/format" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - xrutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - clientutils "github.com/jfrog/jfrog-client-go/utils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/jfrog/jfrog-client-go/xray" - "github.com/jfrog/jfrog-client-go/xray/services" -) - -const ( - BuildScanMinVersion = "3.37.0" - BuildScanIncludeVulnerabilitiesMinVersion = "3.40.0" -) - -type BuildScanCommand struct { - serverDetails *config.ServerDetails - outputFormat format.OutputFormat - buildConfiguration *build.BuildConfiguration - includeVulnerabilities bool - failBuild bool - printExtendedTable bool - rescan bool -} - -func NewBuildScanCommand() *BuildScanCommand { - return &BuildScanCommand{} -} - -func (bsc *BuildScanCommand) SetServerDetails(server *config.ServerDetails) *BuildScanCommand { - bsc.serverDetails = server - return bsc -} - -func (bsc *BuildScanCommand) SetOutputFormat(format format.OutputFormat) *BuildScanCommand { - bsc.outputFormat = format - return bsc -} - -func (bsc *BuildScanCommand) ServerDetails() (*config.ServerDetails, error) { - return bsc.serverDetails, nil -} - -func (bsc *BuildScanCommand) SetBuildConfiguration(buildConfiguration *build.BuildConfiguration) *BuildScanCommand { - bsc.buildConfiguration = buildConfiguration - return bsc -} - -func (bsc *BuildScanCommand) SetIncludeVulnerabilities(include bool) *BuildScanCommand { - bsc.includeVulnerabilities = include - return bsc -} - -func (bsc *BuildScanCommand) SetFailBuild(failBuild bool) *BuildScanCommand { - bsc.failBuild = failBuild - return bsc -} - -func (bsc *BuildScanCommand) SetPrintExtendedTable(printExtendedTable bool) *BuildScanCommand { - bsc.printExtendedTable = printExtendedTable - return bsc -} - -func (bsc *BuildScanCommand) SetRescan(rescan bool) *BuildScanCommand { - bsc.rescan = rescan - return bsc -} - -// Scan published builds with Xray -func (bsc *BuildScanCommand) Run() (err error) { - xrayManager, xrayVersion, err := utils.CreateXrayServiceManagerAndGetVersion(bsc.serverDetails) - if err != nil { - return err - } - err = clientutils.ValidateMinimumVersion(clientutils.Xray, xrayVersion, BuildScanMinVersion) - if err != nil { - return err - } - if bsc.includeVulnerabilities { - err = clientutils.ValidateMinimumVersion(clientutils.Xray, xrayVersion, BuildScanIncludeVulnerabilitiesMinVersion) - if err != nil { - return errors.New("build-scan command with '--vuln' flag is not supported on your current Xray version. " + err.Error()) - } - } - buildName, err := bsc.buildConfiguration.GetBuildName() - if err != nil { - return err - } - buildNumber, err := bsc.buildConfiguration.GetBuildNumber() - if err != nil { - return err - } - params := services.XrayBuildParams{ - BuildName: buildName, - BuildNumber: buildNumber, - Project: bsc.buildConfiguration.GetProject(), - Rescan: bsc.rescan, - } - - isFailBuildResponse, err := bsc.runBuildScanAndPrintResults(xrayManager, xrayVersion, params) - if err != nil { - return err - } - // If failBuild flag is true and also got fail build response from Xray - if bsc.failBuild && isFailBuildResponse { - return xrutils.NewFailBuildError() - } - return -} - -func (bsc *BuildScanCommand) runBuildScanAndPrintResults(xrayManager *xray.XrayServicesManager, xrayVersion string, params services.XrayBuildParams) (isFailBuildResponse bool, err error) { - buildScanResults, noFailBuildPolicy, err := xrayManager.BuildScan(params, bsc.includeVulnerabilities) - if err != nil { - return false, err - } - log.Info("The scan data is available at: " + buildScanResults.MoreDetailsUrl) - isFailBuildResponse = buildScanResults.FailBuild - - scanResponse := []services.ScanResponse{{ - Violations: buildScanResults.Violations, - Vulnerabilities: buildScanResults.Vulnerabilities, - XrayDataUrl: buildScanResults.MoreDetailsUrl, - }} - - scanResults := xrutils.NewAuditResults() - scanResults.XrayVersion = xrayVersion - scanResults.ScaResults = []xrutils.ScaScanResult{{XrayResults: scanResponse}} - - resultsPrinter := xrutils.NewResultsWriter(scanResults). - SetOutputFormat(bsc.outputFormat). - SetIncludeVulnerabilities(bsc.includeVulnerabilities). - SetIncludeLicenses(false). - SetIsMultipleRootProject(true). - SetPrintExtendedTable(bsc.printExtendedTable). - SetScanType(services.Binary). - SetExtraMessages(nil) - - if bsc.outputFormat != format.Table { - // Print the violations and/or vulnerabilities as part of one JSON. - err = resultsPrinter.PrintScanResults() - } else { - // Print two different tables for violations and vulnerabilities (if needed) - - // If "No Xray Fail build policy...." error received, no need to print violations - if !noFailBuildPolicy { - if err = resultsPrinter.PrintScanResults(); err != nil { - return false, err - } - } - if bsc.includeVulnerabilities { - resultsPrinter.SetIncludeVulnerabilities(true) - if err = resultsPrinter.PrintScanResults(); err != nil { - return false, err - } - } - } - return -} - -func (bsc *BuildScanCommand) CommandName() string { - return "xr_build_scan" -} diff --git a/xray/commands/scan/dockerscan.go b/xray/commands/scan/dockerscan.go deleted file mode 100644 index 462c65f4f..000000000 --- a/xray/commands/scan/dockerscan.go +++ /dev/null @@ -1,145 +0,0 @@ -package scan - -import ( - "bytes" - "fmt" - "github.com/jfrog/jfrog-cli-core/v2/common/spec" - xrayutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - clientutils "github.com/jfrog/jfrog-client-go/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - "os" - "os/exec" - "path/filepath" - "strings" -) - -const ( - indexerEnvPrefix = "JFROG_INDEXER_" - DockerScanMinXrayVersion = "3.40.0" -) - -type DockerScanCommand struct { - ScanCommand - imageTag string - targetRepoPath string -} - -func NewDockerScanCommand() *DockerScanCommand { - return &DockerScanCommand{ScanCommand: *NewScanCommand()} -} - -func (dsc *DockerScanCommand) SetImageTag(imageTag string) *DockerScanCommand { - dsc.imageTag = imageTag - return dsc -} - -func (dsc *DockerScanCommand) SetTargetRepoPath(repoPath string) *DockerScanCommand { - dsc.targetRepoPath = repoPath - return dsc -} - -func (dsc *DockerScanCommand) Run() (err error) { - // Validate Xray minimum version - _, xrayVersion, err := xrayutils.CreateXrayServiceManagerAndGetVersion(dsc.ScanCommand.serverDetails) - if err != nil { - return err - } - err = clientutils.ValidateMinimumVersion(clientutils.Xray, xrayVersion, DockerScanMinXrayVersion) - if err != nil { - return err - } - - tempDirPath, err := fileutils.CreateTempDir() - if err != nil { - return err - } - defer func() { - e := fileutils.RemoveTempDir(tempDirPath) - if err == nil { - err = e - } - }() - - // Run the 'docker save' command, to create tar file from the docker image, and pass it to the indexer-app - if dsc.progress != nil { - dsc.progress.SetHeadlineMsg("Creating image archive 📦") - } - log.Info("Creating image archive...") - imageTarPath := filepath.Join(tempDirPath, "image.tar") - dockerSaveCmd := exec.Command("docker", "save", dsc.imageTag, "-o", imageTarPath) - var stderr bytes.Buffer - dockerSaveCmd.Stderr = &stderr - err = dockerSaveCmd.Run() - if err != nil { - return fmt.Errorf("failed running command: '%s' with error: %s - %s", strings.Join(dockerSaveCmd.Args, " "), err.Error(), stderr.String()) - } - - // Perform scan on image.tar - dsc.SetSpec(spec.NewBuilder(). - Pattern(imageTarPath). - Target(dsc.targetRepoPath). - BuildSpec()).SetThreads(1) - err = dsc.setCredentialEnvsForIndexerApp() - if err != nil { - return errorutils.CheckError(err) - } - defer func() { - e := dsc.unsetCredentialEnvsForIndexerApp() - if err == nil { - err = errorutils.CheckError(e) - } - }() - return dsc.ScanCommand.Run() -} - -// When indexing RPM files inside the docker container, the indexer-app needs to connect to the Xray Server. -// This is because RPM indexing is performed on the server side. This method therefore sets the Xray credentials as env vars to be read and used by the indexer-app. -func (dsc *DockerScanCommand) setCredentialEnvsForIndexerApp() error { - err := os.Setenv(indexerEnvPrefix+"XRAY_URL", dsc.serverDetails.XrayUrl) - if err != nil { - return err - } - if dsc.serverDetails.AccessToken != "" { - err = os.Setenv(indexerEnvPrefix+"XRAY_ACCESS_TOKEN", dsc.serverDetails.AccessToken) - if err != nil { - return err - } - } else { - err = os.Setenv(indexerEnvPrefix+"XRAY_USER", dsc.serverDetails.User) - if err != nil { - return err - } - err = os.Setenv(indexerEnvPrefix+"XRAY_PASSWORD", dsc.serverDetails.Password) - if err != nil { - return err - } - } - return nil -} - -func (dsc *DockerScanCommand) unsetCredentialEnvsForIndexerApp() error { - err := os.Unsetenv(indexerEnvPrefix + "XRAY_URL") - if err != nil { - return err - } - err = os.Unsetenv(indexerEnvPrefix + "XRAY_ACCESS_TOKEN") - if err != nil { - return err - } - err = os.Unsetenv(indexerEnvPrefix + "XRAY_USER") - if err != nil { - return err - } - err = os.Unsetenv(indexerEnvPrefix + "XRAY_PASSWORD") - if err != nil { - return err - } - - return nil -} - -func (dsc *DockerScanCommand) CommandName() string { - return "xr_docker_scan" -} diff --git a/xray/commands/scan/downloadindexer.go b/xray/commands/scan/downloadindexer.go deleted file mode 100644 index d0c3456d9..000000000 --- a/xray/commands/scan/downloadindexer.go +++ /dev/null @@ -1,193 +0,0 @@ -package scan - -import ( - "errors" - "fmt" - "net/http" - "os" - "path/filepath" - "runtime" - "sort" - "strings" - - gofrogio "github.com/jfrog/gofrog/io" - "github.com/jfrog/gofrog/version" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/utils/lock" - "github.com/jfrog/jfrog-client-go/http/httpclient" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/jfrog/jfrog-client-go/xray" -) - -const ( - indexerDirName = "xray-indexer" - tempIndexerDirName = "temp" -) - -func DownloadIndexerIfNeeded(xrayManager *xray.XrayServicesManager, xrayVersionStr string) (indexerPath string, err error) { - dependenciesPath, err := config.GetJfrogDependenciesPath() - if err != nil { - return - } - indexerDirPath := filepath.Join(dependenciesPath, indexerDirName) - indexerBinaryName := getIndexerBinaryName() - indexerPath = filepath.Join(indexerDirPath, xrayVersionStr, indexerBinaryName) - - locksDirPath, err := coreutils.GetJfrogLocksDir() - if err != nil { - return - } - unlockFunc, err := lock.CreateLock(filepath.Join(locksDirPath, indexerDirName)) - // Defer the lockFile.Unlock() function before throwing a possible error to avoid deadlock situations. - defer func() { - e := unlockFunc() - if err == nil { - err = e - } - }() - if err != nil { - return - } - exists, err := fileutils.IsFileExists(indexerPath, false) - if exists || err != nil { - return - } - - log.Info("JFrog Xray Indexer " + xrayVersionStr + " is not cached locally. Downloading it now...") - indexerPath, err = downloadIndexer(xrayManager, indexerDirPath, indexerBinaryName) - if err != nil { - err = errors.New("failed while attempting to download Xray indexer: " + err.Error()) - } - return -} - -func downloadIndexer(xrayManager *xray.XrayServicesManager, indexerDirPath, indexerBinaryName string) (string, error) { - tempDirPath := filepath.Join(indexerDirPath, tempIndexerDirName) - - // Delete the temporary directory if it exists - tempDirExists, err := fileutils.IsDirExists(tempDirPath, false) - if err != nil { - return "", err - } - if tempDirExists { - err = fileutils.RemoveTempDir(tempDirPath) - if err != nil { - return "", errorutils.CheckErrorf("Temporary download directory already exists, and can't be removed: %s\nRemove this directory manually and try again: %s", err.Error(), tempDirPath) - } - } - - // Delete all old indexers, but the two newest - err = deleteOldIndexers(indexerDirPath) - if err != nil { - return "", err - } - - // Download the indexer from Xray to the temporary directory - url := fmt.Sprintf("%sapi/v1/indexer-resources/download/%s/%s", xrayManager.Config().GetServiceDetails().GetUrl(), runtime.GOOS, runtime.GOARCH) - downloadFileDetails := &httpclient.DownloadFileDetails{ - DownloadPath: url, - LocalPath: tempDirPath, - LocalFileName: indexerBinaryName, - } - httpClientDetails := xrayManager.Config().GetServiceDetails().CreateHttpClientDetails() - resp, err := xrayManager.Client().DownloadFile(downloadFileDetails, "", &httpClientDetails, false, false) - if err != nil { - return "", fmt.Errorf("an error occurred while trying to download '%s':\n%s", url, err.Error()) - } - if err = errorutils.CheckResponseStatus(resp, http.StatusOK); err != nil { - if resp.StatusCode == http.StatusUnauthorized { - err = fmt.Errorf(err.Error() + "\nHint: It appears that the credentials provided do not have sufficient permissions for JFrog Xray. This could be due to either incorrect credentials or limited permissions restricted to Artifactory only.") - } - return "", fmt.Errorf("failed while attempting to download '%s':\n%s", url, err.Error()) - } - - // Add execution permissions to the indexer - indexerPath := filepath.Join(tempDirPath, indexerBinaryName) - err = os.Chmod(indexerPath, 0777) - if err != nil { - return "", errorutils.CheckError(err) - } - indexerVersion, err := getIndexerVersion(indexerPath) - if err != nil { - return "", err - } - log.Info("The downloaded Xray Indexer version is " + indexerVersion) - newDirPath := filepath.Join(indexerDirPath, indexerVersion) - - // In case of a hot upgrade of Xray in progress, the version of the downloaded indexer might be different from the Xray version we got above, - // so the indexer we just downloaded may already exist. - newDirExists, err := fileutils.IsDirExists(newDirPath, false) - if err != nil { - return "", err - } - if newDirExists { - err = fileutils.RemoveTempDir(tempDirPath) - } else { - err = fileutils.MoveDir(tempDirPath, newDirPath) - } - - return filepath.Join(newDirPath, indexerBinaryName), errorutils.CheckError(err) -} - -func getIndexerVersion(indexerPath string) (string, error) { - indexCmd := &coreutils.GeneralExecCmd{ - ExecPath: indexerPath, - Command: []string{"version"}, - } - output, err := gofrogio.RunCmdOutput(indexCmd) - if err != nil { - return "", errorutils.CheckError(err) - } - splitOutput := strings.Split(output, " ") - // The output of the command looks like: jfrog xray indexer-app version 1.2.3 - indexerVersion := strings.TrimSuffix(splitOutput[len(splitOutput)-1], "\n") - return indexerVersion, nil -} - -func deleteOldIndexers(indexerDirPath string) error { - indexerDirExists, err := fileutils.IsDirExists(indexerDirPath, false) - if !indexerDirExists || err != nil { - return err - } - - filesList, err := os.ReadDir(indexerDirPath) - if err != nil { - return errorutils.CheckError(err) - } - var dirsList []string - for _, file := range filesList { - if file.IsDir() { - dirsList = append(dirsList, file.Name()) - } - } - - if len(dirsList) <= 2 { - return nil - } - - sort.Slice(dirsList, func(i, j int) bool { - currVersion := version.NewVersion(dirsList[i]) - return currVersion.AtLeast(dirsList[j]) - }) - - for i := 2; i < len(dirsList); i++ { - err = os.RemoveAll(filepath.Join(indexerDirPath, dirsList[i])) - if err != nil { - return errorutils.CheckError(err) - } - } - - return nil -} - -func getIndexerBinaryName() string { - switch runtime.GOOS { - case "windows": - return "indexer-app.exe" - default: - return "indexer-app" - } -} diff --git a/xray/commands/scan/downloadindexer_test.go b/xray/commands/scan/downloadindexer_test.go deleted file mode 100644 index 0cc7e7b82..000000000 --- a/xray/commands/scan/downloadindexer_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package scan - -import ( - "github.com/jfrog/jfrog-cli-core/v2/utils/tests" - "os" - "path/filepath" - "testing" - - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/stretchr/testify/assert" -) - -func TestDeleteOldIndexers(t *testing.T) { - testsDir, createTempDirCallback := tests.CreateTempDirWithCallbackAndAssert(t) - defer createTempDirCallback() - indexersDir := filepath.Join(testsDir, "xray-indexer") - indexersDirsPaths := []string{ - filepath.Join(indexersDir, "1.0.0"), - filepath.Join(indexersDir, "1.2.0"), - filepath.Join(indexersDir, "1.3.x-SNAPSHOT"), - } - - // Test no indexers directory at all - assert.NoError(t, deleteOldIndexers(indexersDir)) - - // Test there are two directories in the indexers directory - nothing should be deleted - createDummyIndexer(t, indexersDirsPaths[0]) - createDummyIndexer(t, indexersDirsPaths[1]) - assert.NoError(t, deleteOldIndexers(indexersDir)) - assert.True(t, checkIndexerExists(t, indexersDirsPaths[0])) - assert.True(t, checkIndexerExists(t, indexersDirsPaths[1])) - - // Test there are three directories in the indexers directory - the oldest one (by version) should be deleted - createDummyIndexer(t, indexersDirsPaths[2]) - assert.NoError(t, deleteOldIndexers(indexersDir)) - assert.False(t, checkIndexerExists(t, indexersDirsPaths[0])) - assert.True(t, checkIndexerExists(t, indexersDirsPaths[1])) - assert.True(t, checkIndexerExists(t, indexersDirsPaths[2])) -} - -func createDummyIndexer(t *testing.T, dirPath string) { - err := os.MkdirAll(dirPath, 0777) - assert.NoError(t, err) - fullPath := filepath.Join(dirPath, getIndexerBinaryName()) - file, err := os.Create(fullPath) - assert.NoError(t, err) - defer func() { - assert.NoError(t, file.Close()) - }() - _, err = file.Write([]byte(fullPath)) - assert.NoError(t, err) -} - -func checkIndexerExists(t *testing.T, dirPath string) bool { - indexerPath := filepath.Join(dirPath, getIndexerBinaryName()) - exists, err := fileutils.IsFileExists(indexerPath, true) - assert.NoError(t, err) - return exists -} diff --git a/xray/commands/scan/scan.go b/xray/commands/scan/scan.go deleted file mode 100644 index 69c688797..000000000 --- a/xray/commands/scan/scan.go +++ /dev/null @@ -1,454 +0,0 @@ -package scan - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "os/exec" - "path/filepath" - "regexp" - "strings" - - "github.com/jfrog/jfrog-cli-core/v2/xray/scangraph" - xrayUtils "github.com/jfrog/jfrog-client-go/xray/services/utils" - - "github.com/jfrog/gofrog/parallel" - "github.com/jfrog/jfrog-cli-core/v2/common/format" - "github.com/jfrog/jfrog-cli-core/v2/common/spec" - "github.com/jfrog/jfrog-cli-core/v2/utils/config" - "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" - "github.com/jfrog/jfrog-cli-core/v2/xray/formats" - xrutils "github.com/jfrog/jfrog-cli-core/v2/xray/utils" - "github.com/jfrog/jfrog-client-go/artifactory/services/fspatterns" - clientutils "github.com/jfrog/jfrog-client-go/utils" - "github.com/jfrog/jfrog-client-go/utils/errorutils" - ioUtils "github.com/jfrog/jfrog-client-go/utils/io" - "github.com/jfrog/jfrog-client-go/utils/io/fileutils" - "github.com/jfrog/jfrog-client-go/utils/log" - "github.com/jfrog/jfrog-client-go/xray/services" -) - -type FileContext func(string) parallel.TaskFunc -type indexFileHandlerFunc func(file string) - -const ( - BypassArchiveLimitsMinXrayVersion = "3.59.0" - indexingCommand = "graph" - fileNotSupportedExitCode = 3 -) - -type ScanCommand struct { - serverDetails *config.ServerDetails - spec *spec.SpecFiles - threads int - // The location of the downloaded Xray indexer binary on the local file system. - indexerPath string - indexerTempDir string - outputFormat format.OutputFormat - projectKey string - minSeverityFilter string - watches []string - includeVulnerabilities bool - includeLicenses bool - fail bool - printExtendedTable bool - bypassArchiveLimits bool - fixableOnly bool - progress ioUtils.ProgressMgr -} - -func (scanCmd *ScanCommand) SetMinSeverityFilter(minSeverityFilter string) *ScanCommand { - scanCmd.minSeverityFilter = minSeverityFilter - return scanCmd -} - -func (scanCmd *ScanCommand) SetFixableOnly(fixable bool) *ScanCommand { - scanCmd.fixableOnly = fixable - return scanCmd -} - -func (scanCmd *ScanCommand) SetProgress(progress ioUtils.ProgressMgr) { - scanCmd.progress = progress -} - -func (scanCmd *ScanCommand) SetThreads(threads int) *ScanCommand { - scanCmd.threads = threads - return scanCmd -} - -func (scanCmd *ScanCommand) SetOutputFormat(format format.OutputFormat) *ScanCommand { - scanCmd.outputFormat = format - return scanCmd -} - -func (scanCmd *ScanCommand) SetServerDetails(server *config.ServerDetails) *ScanCommand { - scanCmd.serverDetails = server - return scanCmd -} - -func (scanCmd *ScanCommand) SetSpec(spec *spec.SpecFiles) *ScanCommand { - scanCmd.spec = spec - return scanCmd -} - -func (scanCmd *ScanCommand) SetProject(project string) *ScanCommand { - scanCmd.projectKey = project - return scanCmd -} - -func (scanCmd *ScanCommand) SetWatches(watches []string) *ScanCommand { - scanCmd.watches = watches - return scanCmd -} - -func (scanCmd *ScanCommand) SetIncludeVulnerabilities(include bool) *ScanCommand { - scanCmd.includeVulnerabilities = include - return scanCmd -} - -func (scanCmd *ScanCommand) SetIncludeLicenses(include bool) *ScanCommand { - scanCmd.includeLicenses = include - return scanCmd -} - -func (scanCmd *ScanCommand) ServerDetails() (*config.ServerDetails, error) { - return scanCmd.serverDetails, nil -} - -func (scanCmd *ScanCommand) SetFail(fail bool) *ScanCommand { - scanCmd.fail = fail - return scanCmd -} - -func (scanCmd *ScanCommand) SetPrintExtendedTable(printExtendedTable bool) *ScanCommand { - scanCmd.printExtendedTable = printExtendedTable - return scanCmd -} - -func (scanCmd *ScanCommand) SetBypassArchiveLimits(bypassArchiveLimits bool) *ScanCommand { - scanCmd.bypassArchiveLimits = bypassArchiveLimits - return scanCmd -} - -func (scanCmd *ScanCommand) indexFile(filePath string) (*xrayUtils.BinaryGraphNode, error) { - var indexerResults xrayUtils.BinaryGraphNode - indexerCmd := exec.Command(scanCmd.indexerPath, indexingCommand, filePath, "--temp-dir", scanCmd.indexerTempDir) - if scanCmd.bypassArchiveLimits { - indexerCmd.Args = append(indexerCmd.Args, "--bypass-archive-limits") - } - var stderr bytes.Buffer - var stdout bytes.Buffer - indexerCmd.Stdout = &stdout - indexerCmd.Stderr = &stderr - err := indexerCmd.Run() - if err != nil { - var e *exec.ExitError - if errors.As(err, &e) { - if e.ExitCode() == fileNotSupportedExitCode { - log.Debug(fmt.Sprintf("File %s is not supported by Xray indexer app.", filePath)) - return &indexerResults, nil - } - } - return nil, errorutils.CheckErrorf("Xray indexer app failed indexing %s with %s: %s", filePath, err, stderr.String()) - } - if stderr.String() != "" { - log.Info(stderr.String()) - } - err = json.Unmarshal(stdout.Bytes(), &indexerResults) - return &indexerResults, errorutils.CheckError(err) -} - -func (scanCmd *ScanCommand) Run() (err error) { - defer func() { - if err != nil { - var e *exec.ExitError - if errors.As(err, &e) { - if e.ExitCode() != coreutils.ExitCodeVulnerableBuild.Code { - err = errors.New("Scan command failed. " + err.Error()) - } - } - } - }() - xrayManager, xrayVersion, err := xrutils.CreateXrayServiceManagerAndGetVersion(scanCmd.serverDetails) - if err != nil { - return err - } - - // Validate Xray minimum version for graph scan command - err = clientutils.ValidateMinimumVersion(clientutils.Xray, xrayVersion, scangraph.GraphScanMinXrayVersion) - if err != nil { - return err - } - - if scanCmd.bypassArchiveLimits { - // Validate Xray minimum version for BypassArchiveLimits flag for indexer - err = clientutils.ValidateMinimumVersion(clientutils.Xray, xrayVersion, BypassArchiveLimitsMinXrayVersion) - if err != nil { - return err - } - } - log.Info("JFrog Xray version is:", xrayVersion) - // First download Xray Indexer if needed - scanCmd.indexerPath, err = DownloadIndexerIfNeeded(xrayManager, xrayVersion) - if err != nil { - return err - } - // Create Temp dir for Xray Indexer - scanCmd.indexerTempDir, err = fileutils.CreateTempDir() - if err != nil { - return err - } - defer func() { - e := fileutils.RemoveTempDir(scanCmd.indexerTempDir) - if err == nil { - err = e - } - }() - threads := 1 - if scanCmd.threads > 1 { - threads = scanCmd.threads - } - - // resultsArr is a two-dimensional array. Each array in it contains a list of ScanResponses that were requested and collected by a specific thread. - resultsArr := make([][]*services.ScanResponse, threads) - fileProducerConsumer := parallel.NewRunner(scanCmd.threads, 20000, false) - fileProducerErrors := make([][]formats.SimpleJsonError, threads) - indexedFileProducerConsumer := parallel.NewRunner(scanCmd.threads, 20000, false) - indexedFileProducerErrors := make([][]formats.SimpleJsonError, threads) - fileCollectingErrorsQueue := clientutils.NewErrorsQueue(1) - // Start walking on the filesystem to "produce" files that match the given pattern - // while the consumer uses the indexer to index those files. - scanCmd.prepareScanTasks(fileProducerConsumer, indexedFileProducerConsumer, resultsArr, fileProducerErrors, indexedFileProducerErrors, fileCollectingErrorsQueue, xrayVersion) - scanCmd.performScanTasks(fileProducerConsumer, indexedFileProducerConsumer) - - // Handle results - flatResults := []services.ScanResponse{} - for _, arr := range resultsArr { - for _, res := range arr { - flatResults = append(flatResults, *res) - } - } - if scanCmd.progress != nil { - if err = scanCmd.progress.Quit(); err != nil { - return err - } - - } - - fileCollectingErr := fileCollectingErrorsQueue.GetError() - var scanErrors []formats.SimpleJsonError - if fileCollectingErr != nil { - scanErrors = append(scanErrors, formats.SimpleJsonError{ErrorMessage: fileCollectingErr.Error()}) - } - scanErrors = appendErrorSlice(scanErrors, fileProducerErrors) - scanErrors = appendErrorSlice(scanErrors, indexedFileProducerErrors) - - scanResults := xrutils.NewAuditResults() - scanResults.XrayVersion = xrayVersion - scanResults.ScaResults = []xrutils.ScaScanResult{{XrayResults: flatResults}} - - if err = xrutils.NewResultsWriter(scanResults). - SetOutputFormat(scanCmd.outputFormat). - SetIncludeVulnerabilities(scanCmd.includeVulnerabilities). - SetIncludeLicenses(scanCmd.includeLicenses). - SetPrintExtendedTable(scanCmd.printExtendedTable). - SetIsMultipleRootProject(true). - SetScanType(services.Binary). - PrintScanResults(); err != nil { - return - } - - if err != nil { - return err - } - // If includeVulnerabilities is false it means that context was provided, so we need to check for build violations. - // If user provided --fail=false, don't fail the build. - if scanCmd.fail && !scanCmd.includeVulnerabilities { - if xrutils.CheckIfFailBuild(flatResults) { - return xrutils.NewFailBuildError() - } - } - if len(scanErrors) > 0 { - return errorutils.CheckErrorf(scanErrors[0].ErrorMessage) - } - log.Info("Scan completed successfully.") - return nil -} - -func NewScanCommand() *ScanCommand { - return &ScanCommand{} -} - -func (scanCmd *ScanCommand) CommandName() string { - return "xr_scan" -} - -func (scanCmd *ScanCommand) prepareScanTasks(fileProducer, indexedFileProducer parallel.Runner, resultsArr [][]*services.ScanResponse, fileErrors, indexedFileErrors [][]formats.SimpleJsonError, fileCollectingErrorsQueue *clientutils.ErrorsQueue, xrayVersion string) { - go func() { - defer fileProducer.Done() - // Iterate over file-spec groups and produce indexing tasks. - // When encountering an error, log and move to next group. - specFiles := scanCmd.spec.Files - for i := range specFiles { - artifactHandlerFunc := scanCmd.createIndexerHandlerFunc(&specFiles[i], indexedFileProducer, resultsArr, fileErrors, indexedFileErrors, xrayVersion) - taskHandler := getAddTaskToProducerFunc(fileProducer, artifactHandlerFunc) - - err := collectFilesForIndexing(specFiles[i], taskHandler) - if err != nil { - log.Error(err) - fileCollectingErrorsQueue.AddError(err) - } - } - }() -} - -func (scanCmd *ScanCommand) createIndexerHandlerFunc(file *spec.File, indexedFileProducer parallel.Runner, resultsArr [][]*services.ScanResponse, fileErrors, indexedFileErrors [][]formats.SimpleJsonError, xrayVersion string) FileContext { - return func(filePath string) parallel.TaskFunc { - return func(threadId int) (err error) { - logMsgPrefix := clientutils.GetLogMsgPrefix(threadId, false) - log.Info(logMsgPrefix+"Indexing file:", filePath) - if scanCmd.progress != nil { - scanCmd.progress.SetHeadlineMsg("Indexing file: " + filepath.Base(filePath) + " 🗄") - } - graph, err := scanCmd.indexFile(filePath) - if err != nil { - fileErrors[threadId] = append(fileErrors[threadId], formats.SimpleJsonError{FilePath: filePath, ErrorMessage: err.Error()}) - return err - } - // In case of empty graph returned by the indexer, - // for instance due to unsupported file format, continue without sending a - // graph request to Xray. - if graph.Id == "" { - return nil - } - // Add a new task to the second producer/consumer - // which will send the indexed binary to Xray and then will store the received result. - taskFunc := func(threadId int) (err error) { - params := &services.XrayGraphScanParams{ - BinaryGraph: graph, - RepoPath: getXrayRepoPathFromTarget(file.Target), - Watches: scanCmd.watches, - IncludeLicenses: scanCmd.includeLicenses, - IncludeVulnerabilities: scanCmd.includeVulnerabilities, - ProjectKey: scanCmd.projectKey, - ScanType: services.Binary, - } - if scanCmd.progress != nil { - scanCmd.progress.SetHeadlineMsg("Scanning 🔍") - } - scanGraphParams := scangraph.NewScanGraphParams(). - SetServerDetails(scanCmd.serverDetails). - SetXrayGraphScanParams(params). - SetXrayVersion(xrayVersion). - SetFixableOnly(scanCmd.fixableOnly). - SetSeverityLevel(scanCmd.minSeverityFilter) - scanResults, err := scangraph.RunScanGraphAndGetResults(scanGraphParams) - if err != nil { - log.Error(fmt.Sprintf("scanning '%s' failed with error: %s", graph.Id, err.Error())) - indexedFileErrors[threadId] = append(indexedFileErrors[threadId], formats.SimpleJsonError{FilePath: filePath, ErrorMessage: err.Error()}) - return - } - resultsArr[threadId] = append(resultsArr[threadId], scanResults) - return - } - - _, _ = indexedFileProducer.AddTask(taskFunc) - return - } - } -} - -func getAddTaskToProducerFunc(producer parallel.Runner, fileHandlerFunc FileContext) indexFileHandlerFunc { - return func(filePath string) { - taskFunc := fileHandlerFunc(filePath) - _, _ = producer.AddTask(taskFunc) - } -} - -func (scanCmd *ScanCommand) performScanTasks(fileConsumer parallel.Runner, indexedFileConsumer parallel.Runner) { - go func() { - // Blocking until consuming is finished. - fileConsumer.Run() - // After all files have been indexed, The second producer notifies that no more tasks will be produced. - indexedFileConsumer.Done() - }() - // Blocking until consuming is finished. - indexedFileConsumer.Run() -} - -func collectFilesForIndexing(fileData spec.File, dataHandlerFunc indexFileHandlerFunc) error { - - fileData.Pattern = clientutils.ReplaceTildeWithUserHome(fileData.Pattern) - patternType := fileData.GetPatternType() - rootPath, err := fspatterns.GetRootPath(fileData.Pattern, fileData.Target, "", patternType, false) - if err != nil { - return err - } - - isDir, err := fileutils.IsDirExists(rootPath, false) - if err != nil { - return err - } - - // If the path is a single file, index it and return - if !isDir { - dataHandlerFunc(rootPath) - return nil - } - fileData.Pattern = clientutils.ConvertLocalPatternToRegexp(fileData.Pattern, patternType) - return collectPatternMatchingFiles(fileData, rootPath, dataHandlerFunc) -} - -func collectPatternMatchingFiles(fileData spec.File, rootPath string, dataHandlerFunc indexFileHandlerFunc) error { - fileParams, err := fileData.ToCommonParams() - if err != nil { - return err - } - excludePathPattern := fspatterns.PrepareExcludePathPattern(fileParams.Exclusions, fileParams.GetPatternType(), fileParams.IsRecursive()) - patternRegex, err := regexp.Compile(fileData.Pattern) - if errorutils.CheckError(err) != nil { - return err - } - recursive, err := fileData.IsRecursive(true) - if err != nil { - return err - } - - paths, err := fspatterns.ListFiles(rootPath, recursive, false, false, false, excludePathPattern) - if err != nil { - return err - } - for _, path := range paths { - matches, isDir, err := fspatterns.SearchPatterns(path, false, false, patternRegex) - if err != nil { - return err - } - // Because paths should contain all files and directories (walks recursively) we can ignore dirs, as only files relevance for indexing. - if isDir { - continue - } - if len(matches) > 0 { - dataHandlerFunc(path) - } - } - return nil -} - -// Xray expects a path inside a repo, but does not accept a path to a file. -// Therefore, if the given target path is a path to a file, -// the path to the parent directory will be returned. -// Otherwise, the func will return the path itself. -func getXrayRepoPathFromTarget(target string) (repoPath string) { - if strings.HasSuffix(target, "/") { - return target - } - return target[:strings.LastIndex(target, "/")+1] -} - -func appendErrorSlice(scanErrors []formats.SimpleJsonError, errorsToAdd [][]formats.SimpleJsonError) []formats.SimpleJsonError { - for _, errorSlice := range errorsToAdd { - scanErrors = append(scanErrors, errorSlice...) - } - return scanErrors -} diff --git a/xray/commands/testdata/applicability-scan/applicable-cve-results.sarif b/xray/commands/testdata/applicability-scan/applicable-cve-results.sarif deleted file mode 100644 index 66aee38a5..000000000 --- a/xray/commands/testdata/applicability-scan/applicable-cve-results.sarif +++ /dev/null @@ -1,84 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Applicability Scanner", - "rules": [ - { - "id": "applic_testCve1", - "fullDescription": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called.", - "markdown": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "name": "CVE-2021-3807", - "shortDescription": { - "text": "Scanner for CVE-2021-3807" - } - }, - { - "id": "applic_testCve3", - "fullDescription": { - "text": "The scanner checks whether any of the following vulnerable functions are called:\n\n* `json-schema.validate` with external input to its 1st (`instance`) argument.\n* `json-schema.checkPropertyChange` with external input to its 2nd (`schema`) argument.", - "markdown": "The scanner checks whether any of the following vulnerable functions are called:\n\n* `json-schema.validate` with external input to its 1st (`instance`) argument.\n* `json-schema.checkPropertyChange` with external input to its 2nd (`schema`) argument." - }, - "name": "CVE-2021-3918", - "shortDescription": { - "text": "Scanner for CVE-2021-3918" - } - } - ], - "version": "APPLIC_SCANNERv0.2.3" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "ca_scanner/applicability_scanner", - "scan", - "ca_config_example.yaml" - ], - "workingDirectory": { - "uri": "file:///Users/ort/Desktop/am_versions_for_ga/mac_arm" - } - } - ], - "results": [ - { - "message": { - "text": "The vulnerable function json-schema.validate is called with external input" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/ort/Desktop/am_versions_for_ga/mac_arm/demo/node_modules/npm/node_modules/jsprim/lib/jsprim.js" - }, - "region": { - "endColumn": 53, - "endLine": 531, - "snippet": { - "text": "mod_jsonschema.validate(input, schema)" - }, - "startColumn": 15, - "startLine": 531 - } - } - } - ], - "ruleId": "applic_testCve1" - }, - { - "message": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "kind": "pass", - "ruleId": "applic_testCve3" - } - ] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/applicability-scan/empty-results.sarif b/xray/commands/testdata/applicability-scan/empty-results.sarif deleted file mode 100644 index ec3c9ccff..000000000 --- a/xray/commands/testdata/applicability-scan/empty-results.sarif +++ /dev/null @@ -1,29 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Applicability Scanner", - "rules": [], - "version": "APPLIC_SCANNERv0.2.3" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "ca_scanner/applicability_scanner", - "scan", - "/Users/ort/workspace/src/jfrog.com/jfrog-cli/LeWVtGDMPW.yaml" - ], - "workingDirectory": { - "uri": "file:///Users/ort/workspace/src/jfrog.com/jfrog-cli" - } - } - ], - "results": [] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/applicability-scan/no-applicable-cves-results.sarif b/xray/commands/testdata/applicability-scan/no-applicable-cves-results.sarif deleted file mode 100644 index 4257bc869..000000000 --- a/xray/commands/testdata/applicability-scan/no-applicable-cves-results.sarif +++ /dev/null @@ -1,121 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Applicability Scanner", - "rules": [ - { - "id": "applic_testCve2", - "fullDescription": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called.", - "markdown": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "name": "CVE-2021-3807", - "shortDescription": { - "text": "Scanner for CVE-2021-3807" - } - }, - { - "id": "applic_testCve3", - "fullDescription": { - "text": "The scanner checks whether any of the following vulnerable functions are called:\n\n* `json-schema.validate` with external input to its 1st (`instance`) argument.\n* `json-schema.checkPropertyChange` with external input to its 2nd (`schema`) argument.", - "markdown": "The scanner checks whether any of the following vulnerable functions are called:\n\n* `json-schema.validate` with external input to its 1st (`instance`) argument.\n* `json-schema.checkPropertyChange` with external input to its 2nd (`schema`) argument." - }, - "name": "CVE-2021-3918", - "shortDescription": { - "text": "Scanner for CVE-2021-3918" - } - }, - { - "id": "applic_testCve4", - "fullDescription": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called.", - "markdown": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "name": "CVE-2021-3807", - "shortDescription": { - "text": "Scanner for CVE-2021-3807" - } - }, - { - "id": "applic_testCve5", - "fullDescription": { - "text": "The scanner checks whether any of the following vulnerable functions are called:\n\n* `json-schema.validate` with external input to its 1st (`instance`) argument.\n* `json-schema.checkPropertyChange` with external input to its 2nd (`schema`) argument.", - "markdown": "The scanner checks whether any of the following vulnerable functions are called:\n\n* `json-schema.validate` with external input to its 1st (`instance`) argument.\n* `json-schema.checkPropertyChange` with external input to its 2nd (`schema`) argument." - }, - "name": "CVE-2021-3918", - "shortDescription": { - "text": "Scanner for CVE-2021-3918" - } - }, - { - "id": "applic_testCve1", - "fullDescription": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called.", - "markdown": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "name": "CVE-2021-3807", - "shortDescription": { - "text": "Scanner for CVE-2021-3807" - } - } - ], - "version": "APPLIC_SCANNERv0.2.3" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "ca_scanner/applicability_scanner", - "scan", - "ca_config_example.yaml" - ], - "workingDirectory": { - "uri": "file:///Users/ort/Desktop/am_versions_for_ga/mac_arm" - } - } - ], - "results": [ - { - "message": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "kind": "pass", - "ruleId": "applic_testCve2" - }, - { - "message": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "kind": "pass", - "ruleId": "applic_testCve3" - }, - { - "message": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "kind": "pass", - "ruleId": "applic_testCve4" - }, - { - "message": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "kind": "pass", - "ruleId": "applic_testCve5" - }, - { - "message": { - "text": "The scanner checks whether the vulnerable function `ansi-regex` is called." - }, - "kind": "pass", - "ruleId": "applic_testCve1" - } - ] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/artifactory-maven-plugin/pom.xml b/xray/commands/testdata/artifactory-maven-plugin/pom.xml deleted file mode 100644 index 8d3c4669d..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/pom.xml +++ /dev/null @@ -1,327 +0,0 @@ - - 4.0.0 - org.jfrog.buildinfo - artifactory-maven-plugin - maven-plugin - 3.2.3 - Artifactory Maven plugin - https://www.jfrog.com/confluence/display/JFROG/Maven+Artifactory+Plugin - A Maven plugin to resolve artifacts from Artifactory, deploy artifacts to Artifactory, capture and - publish build info. - - - - 3.3.9 - 2.26.4 - UTF-8 - 1.8 - 1.8 - true - - - - - releases - jfrog-dependencies - https://oss.jfrog.org/artifactory/jfrog-dependencies - - - - snapshots - libs-snapshot - https://oss.jfrog.org/artifactory/libs-snapshot - - - - - - false - - releases - jfrog-dependencies - https://oss.jfrog.org/artifactory/jfrog-dependencies - - - - snapshots - plugins-snapshot - https://oss.jfrog.org/artifactory/plugins-snapshot - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - - - ${maven.min.version} - - - - JFrog - https://jfrog.com - - - - scm:git:git://github.com/jfrog/artifactory-maven-plugin.git - scm:git:git@github.com:jfrog/artifactory-maven-plugin.git - https://github.com/jfrog/artifactory-maven-plugin - - - - - JFrog - eco-system@jfrog.com - - - - - - The Apache Software License, Version 2.0 - https://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - jira - https://www.jfrog.com/jira/browse/NMAP - - - - - - org.apache.maven - maven-plugin-api - ${maven.min.version} - - - org.apache.maven - maven-core - ${maven.min.version} - - - org.apache.maven - maven-model - ${maven.min.version} - - - - - org.jfrog.buildinfo - build-info-extractor - ${buildinfo.version} - - - org.jfrog.buildinfo - build-info-api - ${buildinfo.version} - - - - - org.apache.commons - commons-lang3 - 3.11 - - - org.apache.commons - commons-collections4 - 4.4 - - - commons-io - commons-io - 2.9.0 - - - - - org.apache.maven.plugin-tools - maven-plugin-annotations - 3.6.0 - provided - - - org.codehaus.plexus - plexus-component-annotations - 2.1.0 - provided - - - org.projectlombok - lombok - 1.18.12 - provided - - - - - org.slf4j - slf4j-simple - 1.7.30 - test - - - - - - - org.apache.maven.plugins - maven-plugin-plugin - 3.6.0 - - - org.apache.maven.plugins - maven-source-plugin - 3.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - - attach-javadocs - - jar - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.1 - - - **/*ITest.java - - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.22.1 - - - - WARN - - - **/*ITest.java - - - - - integration-test - - integration-test - - - - - - - - - - release - - - - ARTIFACTORY_URL - - - - - - org.jfrog.buildinfo - artifactory-maven-plugin - ${project.version} - false - - - build-info - - publish - - - - ${ARTIFACTORY_URL} - ${ARTIFACTORY_USERNAME} - ${ARTIFACTORY_PASSWORD} - oss-release-local - oss-snapshot-local - - - - - - - - - - - upload-to-central - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.8 - true - - ossrh - https://oss.sonatype.org - true - - - - - - - diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/ArtifactoryMojo.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/ArtifactoryMojo.java deleted file mode 100644 index 4f9a3769b..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/ArtifactoryMojo.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.jfrog.buildinfo; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; -import org.jfrog.build.api.BuildInfoFields; -import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration; -import org.jfrog.build.extractor.clientConfiguration.ClientProperties; -import org.jfrog.buildinfo.deployment.BuildInfoRecorder; -import org.jfrog.buildinfo.resolution.RepositoryListener; -import org.jfrog.buildinfo.resolution.ResolutionRepoHelper; -import org.jfrog.buildinfo.utils.Utils; - -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import static org.jfrog.buildinfo.utils.Utils.getMavenVersion; - -/** - * The plugin's entry point - - * Replace the resolution repositories. - * Replace the default deployment with the BuildInfoRecorder. - */ -@Mojo(name = "publish", defaultPhase = LifecyclePhase.VALIDATE, threadSafe = true) -public class ArtifactoryMojo extends AbstractMojo { - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - private static final String[] DEPLOY_GOALS = {"deploy", "maven-deploy-plugin"}; - - @Parameter(required = true, defaultValue = "${project}") - MavenProject project; - - @Parameter(required = true, defaultValue = "${session}") - MavenSession session; - - @Component(role = RepositoryListener.class) - RepositoryListener repositoryListener; - - @Parameter - Config.Artifactory artifactory = new Config.Artifactory(); - - @Parameter - Map deployProperties = new HashMap<>(); - - @Parameter - Config.BuildInfo buildInfo = new Config.BuildInfo(); - - @Parameter - Config.Publisher publisher = new Config.Publisher(); - - @Parameter - Config.Resolver resolver = new Config.Resolver(); - - @Override - public void execute() { - if (session.getRequest().getData().putIfAbsent("configured", Boolean.TRUE) == null) { - replaceVariables(); - enforceResolution(); - enforceDeployment(); - } - } - - /** - * Replace variables in pom.xml surrounded by {{}} with environment and system variables. - */ - private void replaceVariables() { - artifactory.delegate.getAllProperties().replaceAll((key, value) -> Utils.parseInput(value)); - deployProperties.replaceAll((key, value) -> Utils.parseInput(value)); - } - - /** - * Enforce resolution from Artifactory repositories if there is a 'resolver' configuration. - */ - private void enforceResolution() { - ResolutionRepoHelper helper = new ResolutionRepoHelper(getLog(), session, artifactory.delegate); - List resolutionRepositories = helper.getResolutionRepositories(); - if (CollectionUtils.isNotEmpty(resolutionRepositories)) { - // User configured the 'resolver' - for (MavenProject mavenProject : session.getProjects()) { - mavenProject.setPluginArtifactRepositories(resolutionRepositories); - mavenProject.setRemoteArtifactRepositories(resolutionRepositories); - } - } - } - - /** - * Enforce deployment to Artifactory repositories if there is a 'publisher' configuration. - */ - private void enforceDeployment() { - if (!deployGoalExist()) { - return; - } - skipDefaultDeploy(); - completeConfig(); - addDeployProperties(); - BuildInfoRecorder executionListener = new BuildInfoRecorder(session, getLog(), artifactory.delegate); - repositoryListener.setBuildInfoRecorder(executionListener); - session.getRequest().setExecutionListener(executionListener); - } - - /** - * Return true if 'deploy' or 'maven-deploy-plugin' goals exist. - * - * @return true if 'deploy' or 'maven-deploy-plugin' goals exist - */ - private boolean deployGoalExist() { - return session.getGoals().stream().anyMatch(goal -> ArrayUtils.contains(DEPLOY_GOALS, goal)); - } - - /** - * Skip the default maven deploy behaviour. - */ - private void skipDefaultDeploy() { - session.getUserProperties().put("maven.deploy.skip", Boolean.TRUE.toString()); - } - - /** - * Complete missing configuration. - */ - private void completeConfig() { - ArtifactoryClientConfiguration.BuildInfoHandler buildInfo = this.buildInfo.delegate; - buildInfo.setBuildTimestamp(Long.toString(session.getStartTime().getTime())); - buildInfo.setBuildStarted(DATE_FORMAT.format(session.getStartTime())); - if (StringUtils.isBlank(buildInfo.getBuildName())) { - buildInfo.setBuildName(project.getArtifactId()); - } - if (StringUtils.isBlank(buildInfo.getBuildNumber())) { - buildInfo.setBuildNumber(buildInfo.getBuildTimestamp()); - } - buildInfo.setBuildAgentName("Maven"); - buildInfo.setBuildAgentVersion(getMavenVersion(getClass())); - if (buildInfo.getBuildRetentionDays() != null) { - buildInfo.setBuildRetentionMinimumDate(buildInfo.getBuildRetentionDays().toString()); - } - } - - /** - * Add buildName, buildNumber, the timestamp and the configured deployProperties as a deployment properties. - * The deployer adds these properties to each of of the deployed artifacts. - */ - private void addDeployProperties() { - ArtifactoryClientConfiguration.BuildInfoHandler buildInfo = this.buildInfo.delegate; - Properties deployProperties = new Properties() {{ - addDeployProperty(this, BuildInfoFields.BUILD_TIMESTAMP, buildInfo.getBuildTimestamp()); - addDeployProperty(this, BuildInfoFields.BUILD_NAME, buildInfo.getBuildName()); - addDeployProperty(this, BuildInfoFields.BUILD_NUMBER, buildInfo.getBuildNumber()); - }}; - this.deployProperties.forEach((key, value) -> addDeployProperty(deployProperties, key, value)); - artifactory.delegate.fillFromProperties(deployProperties); - } - - /** - * Add a single deploy property. - * - * @param deployProperties - The deploy properties collection - * @param key - The key of the property - * @param value - The value of the property - */ - private void addDeployProperty(Properties deployProperties, String key, String value) { - if (StringUtils.isNotBlank(value)) { - deployProperties.put(ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX + key, value); - } - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/Config.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/Config.java deleted file mode 100644 index 9bb56cfbf..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/Config.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.jfrog.buildinfo; - -import lombok.experimental.Delegate; -import org.jfrog.build.api.util.NullLog; -import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration; -import org.jfrog.build.extractor.clientConfiguration.PrefixPropertyHandler; - -/** - * Represents the Artifactory Maven plugin configuration in the pom.xml file. - * The configuration is automatically injected to this class. - * - * @author yahavi - */ -public class Config { - - private static final ArtifactoryClientConfiguration CLIENT_CONFIGURATION = new ArtifactoryClientConfiguration(new NullLog()); - - /** - * Represents the 'artifactory' configuration in the pom.xml. - */ - public static class Artifactory { - @Delegate - ArtifactoryClientConfiguration delegate = CLIENT_CONFIGURATION; - } - - /** - * Represents the 'resolver' configuration in the pom.xml. - */ - public static class Resolver { - @Delegate(types = { - ArtifactoryClientConfiguration.ResolverHandler.class, - ArtifactoryClientConfiguration.RepositoryConfiguration.class, - ArtifactoryClientConfiguration.AuthenticationConfiguration.class, - PrefixPropertyHandler.class}) - ArtifactoryClientConfiguration.ResolverHandler delegate = CLIENT_CONFIGURATION.resolver; - } - - /** - * Represents the 'publisher' configuration in the pom.xml. - */ - public static class Publisher { - @Delegate(types = { - ArtifactoryClientConfiguration.PublisherHandler.class, - ArtifactoryClientConfiguration.RepositoryConfiguration.class, - ArtifactoryClientConfiguration.AuthenticationConfiguration.class, - PrefixPropertyHandler.class}) - ArtifactoryClientConfiguration.PublisherHandler delegate = CLIENT_CONFIGURATION.publisher; - } - - /** - * Represents the 'buildInfo' configuration in the pom.xml. - */ - public static class BuildInfo { - @Delegate(types = {ArtifactoryClientConfiguration.BuildInfoHandler.class, PrefixPropertyHandler.class}) - ArtifactoryClientConfiguration.BuildInfoHandler delegate = CLIENT_CONFIGURATION.info; - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildDeployer.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildDeployer.java deleted file mode 100644 index d4e230607..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildDeployer.java +++ /dev/null @@ -1,152 +0,0 @@ -package org.jfrog.buildinfo.deployment; - -import org.apache.commons.collections4.ListUtils; -import org.apache.commons.collections4.MapUtils; -import org.apache.maven.plugin.logging.Log; -import org.jfrog.build.api.Artifact; -import org.jfrog.build.api.Build; -import org.jfrog.build.api.Module; -import org.jfrog.build.extractor.BuildInfoExtractorUtils; -import org.jfrog.build.extractor.ModuleParallelDeployHelper; -import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration; -import org.jfrog.build.extractor.clientConfiguration.ArtifactoryManagerBuilder; -import org.jfrog.build.extractor.clientConfiguration.client.artifactory.ArtifactoryManager; -import org.jfrog.build.extractor.clientConfiguration.deploy.DeployDetails; -import org.jfrog.build.extractor.retention.Utils; -import org.jfrog.buildinfo.utils.ArtifactoryMavenLogger; - -import java.io.IOException; -import java.util.*; - -import static org.jfrog.buildinfo.utils.Utils.setChecksums; - -/** - * Deploy artifacts and publish build info. - * - * @author yahavi - */ -public class BuildDeployer { - - private static final String LOG_PREFIX = "Artifactory Build info recorder: "; - private final Log logger; - - public BuildDeployer(Log logger) { - this.logger = logger; - } - - /** - * Deploy artifacts and publish the build info. - * - * @param build - The build to deploy - * @param clientConf - Artifactory client configuration - * @param deployableArtifacts - The deployable artifacts - */ - public void deploy(Build build, ArtifactoryClientConfiguration clientConf, Map deployableArtifacts) { - Map> deployableArtifactsByModule = prepareDeployableArtifacts(build.getModules(), deployableArtifacts); - boolean isDeployArtifacts = isDeployArtifacts(clientConf, deployableArtifactsByModule); - boolean isPublishBuildInfo = isPublishBuildInfo(clientConf); - if (!isDeployArtifacts && !isPublishBuildInfo) { - // Nothing to deploy - return; - } - - try (ArtifactoryManager client = new ArtifactoryManagerBuilder() - .setClientConfiguration(clientConf, clientConf.publisher).setLog(new ArtifactoryMavenLogger(logger)).build()) { - if (clientConf.getInsecureTls()) { - client.setInsecureTls(true); - } - if (isDeployArtifacts) { - logger.debug(LOG_PREFIX + "Publication fork count: " + clientConf.publisher.getPublishForkCount()); - new ModuleParallelDeployHelper().deployArtifacts(client, deployableArtifactsByModule, clientConf.publisher.getPublishForkCount()); - } - if (isPublishBuildInfo) { - logger.info(LOG_PREFIX + "Deploying build info ..."); - Utils.sendBuildAndBuildRetention(client, build, clientConf); - } - } catch (IOException e) { - throw new RuntimeException(LOG_PREFIX + "Failed to deploy build info.", e); - } - } - - /** - * Return true if should deploy artifacts. - * - * @param clientConf - Artifactory client configuration - * @param deployableArtifacts - The deployable artifacts - * @return true if should deploy artifacts - */ - private boolean isDeployArtifacts(ArtifactoryClientConfiguration clientConf, Map> deployableArtifacts) { - if (!clientConf.publisher.isPublishArtifacts()) { - logger.info(LOG_PREFIX + "deploy artifacts set to false, artifacts will not be deployed..."); - return false; - } - if (MapUtils.isEmpty(deployableArtifacts)) { - logger.info(LOG_PREFIX + "no artifacts to deploy..."); - return false; - } - return true; - } - - /** - * Return true if should publish build info. - * - * @param clientConf - Artifactory client configuration - * @return true if should publish build info - */ - private boolean isPublishBuildInfo(ArtifactoryClientConfiguration clientConf) { - if (!clientConf.publisher.isPublishBuildInfo()) { - logger.info(LOG_PREFIX + "publish build info set to false, build info will not be published..."); - return false; - } - return true; - } - - /** - * Prepare deployable artifacts by module map. - * - * @param modules - The build modules - * @param deployableArtifacts - The deployable artifacts - * @return deployable artifacts by module map - */ - private Map> prepareDeployableArtifacts(List modules, Map deployableArtifacts) { - Map> deployableArtifactsByModule = new LinkedHashMap<>(); - for (Module module : modules) { - - // Create deployable artifacts set for current module - Set moduleDeployableArtifacts = new LinkedHashSet<>(); - for (Artifact moduleArtifact : ListUtils.emptyIfNull(module.getArtifacts())) { - String artifactId = BuildInfoExtractorUtils.getArtifactId(module.getId(), moduleArtifact.getName()); - DeployDetails deployableArtifact = deployableArtifacts.get(artifactId); - if (deployableArtifact != null) { - moduleDeployableArtifacts.add(createDeployDetails(deployableArtifact, moduleArtifact)); - } - } - - // If the deployable artifacts set is not empty, add it to the results - if (!moduleDeployableArtifacts.isEmpty()) { - deployableArtifactsByModule.put(module.getId(), moduleDeployableArtifacts); - } - } - return deployableArtifactsByModule; - } - - /** - * Create DeployDetails of an artifact to deploy. - * - * @param deployableArtifact - DeployDetails without sha1 - * @param artifact - Thw artifact to deploy - * @return DeployDetails of artifact to deploy - */ - private DeployDetails createDeployDetails(DeployDetails deployableArtifact, Artifact artifact) { - setChecksums(deployableArtifact.getFile(), artifact, logger); - return new DeployDetails.Builder(). - artifactPath(deployableArtifact.getArtifactPath()). - file(deployableArtifact.getFile()). - md5(artifact.getMd5()). - sha1(artifact.getSha1()). - addProperties(deployableArtifact.getProperties()). - targetRepository(deployableArtifact.getTargetRepository()). - packageType(DeployDetails.PackageType.MAVEN). - build(); - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoModelPropertyResolver.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoModelPropertyResolver.java deleted file mode 100644 index 07762cdec..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoModelPropertyResolver.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.jfrog.buildinfo.deployment; - -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.logging.Log; -import org.jfrog.build.api.Agent; -import org.jfrog.build.api.Build; -import org.jfrog.build.api.BuildAgent; -import org.jfrog.build.api.MatrixParameter; -import org.jfrog.build.api.builder.BuildInfoMavenBuilder; -import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration; - -import static org.jfrog.build.api.BuildInfoFields.*; -import static org.jfrog.buildinfo.utils.Utils.getMavenVersion; -import static org.jfrog.buildinfo.utils.Utils.getPluginVersion; - -/** - * Maven Build info builder that resolves the configuration from {@link ArtifactoryClientConfiguration} - * - * @author yahavi - */ -public class BuildInfoModelPropertyResolver extends BuildInfoMavenBuilder { - - private final Log logger; - - public BuildInfoModelPropertyResolver(Log logger, MavenSession session, ArtifactoryClientConfiguration clientConf) { - super(StringUtils.firstNonBlank(clientConf.info.getBuildName(), session.getTopLevelProject().getName())); - this.logger = logger; - resolveCoreProperties(session, clientConf); - resolveProperties(clientConf); - resolveBuildAgent(clientConf); - addRunParameters(clientConf); - } - - /** - * Resolve mandatory properties - build-name build-number and build-started. - * - * @param session - The current maven session to extract the start time - * @param clientConf - Artifactory client configuration - */ - private void resolveCoreProperties(MavenSession session, ArtifactoryClientConfiguration clientConf) { - String buildNumber = StringUtils.defaultIfBlank(clientConf.info.getBuildNumber(), Long.toString(System.currentTimeMillis())); - number(buildNumber); - - long buildStartTime = session.getRequest().getStartTime().getTime(); - String buildStarted = StringUtils.defaultIfBlank(clientConf.info.getBuildStarted(), Build.formatBuildStarted(buildStartTime)); - started(buildStarted); - - logResolvedProperty(BUILD_NAME, super.name); - logResolvedProperty(BUILD_NUMBER, buildNumber); - logResolvedProperty(BUILD_STARTED, buildStarted); - } - - /** - * Resolve general optional properties. - * - * @param clientConf - Artifactory client configuration - */ - private void resolveProperties(ArtifactoryClientConfiguration clientConf) { - artifactoryPluginVersion(clientConf.info.getArtifactoryPluginVersion()); - artifactoryPrincipal(clientConf.publisher.getName()); - parentNumber(clientConf.info.getParentBuildNumber()); - parentName(clientConf.info.getParentBuildName()); - vcsRevision(clientConf.info.getVcsRevision()); - principal(clientConf.info.getPrincipal()); - url(clientConf.info.getBuildUrl()); - } - - /** - * Resolve the build agent - * - * @param clientConf - Artifactory client configuration - */ - private void resolveBuildAgent(ArtifactoryClientConfiguration clientConf) { - BuildAgent buildAgent = new BuildAgent("Maven", getMavenVersion(getClass())); - buildAgent(buildAgent); - String agentName = clientConf.info.getAgentName(); - String agentVersion = clientConf.info.getAgentVersion(); - if (StringUtils.isBlank(agentName)) { - agentName = "artifactory-maven-plugin"; - agentVersion = getPluginVersion(); - } - agent(new Agent(agentName, agentVersion)); - } - - /** - * Add run parameters - * - * @param clientConf - Artifactory client configuration - */ - private void addRunParameters(ArtifactoryClientConfiguration clientConf) { - clientConf.info.getRunParameters().entrySet().stream() - .map(param -> new MatrixParameter(param.getKey(), param.getValue())) - .forEach(this::addRunParameters); - } - - private void logResolvedProperty(String key, String value) { - logger.debug("Artifactory Build Info Model Property Resolver: " + key + " = " + value); - } -} \ No newline at end of file diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoRecorder.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoRecorder.java deleted file mode 100644 index c1e7f321c..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/deployment/BuildInfoRecorder.java +++ /dev/null @@ -1,465 +0,0 @@ -package org.jfrog.buildinfo.deployment; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.execution.AbstractExecutionListener; -import org.apache.maven.execution.ExecutionEvent; -import org.apache.maven.execution.ExecutionListener; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.artifact.ProjectArtifactMetadata; -import org.apache.maven.repository.legacy.metadata.ArtifactMetadata; -import org.jfrog.build.api.Build; -import org.jfrog.build.api.Dependency; -import org.jfrog.build.api.builder.ArtifactBuilder; -import org.jfrog.build.api.builder.BuildInfoMavenBuilder; -import org.jfrog.build.api.builder.DependencyBuilder; -import org.jfrog.build.api.builder.ModuleBuilder; -import org.jfrog.build.extractor.BuildInfoExtractor; -import org.jfrog.build.extractor.BuildInfoExtractorUtils; -import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration; -import org.jfrog.build.extractor.clientConfiguration.IncludeExcludePatterns; -import org.jfrog.build.extractor.clientConfiguration.PatternMatcher; -import org.jfrog.build.extractor.clientConfiguration.deploy.DeployDetails; -import org.jfrog.buildinfo.resolution.RepositoryListener; -import org.jfrog.buildinfo.types.ModuleArtifacts; -import org.jfrog.buildinfo.utils.Utils; - -import java.io.File; -import java.util.*; - -import static org.jfrog.build.extractor.BuildInfoExtractorUtils.getModuleIdString; -import static org.jfrog.build.extractor.BuildInfoExtractorUtils.getTypeString; -import static org.jfrog.buildinfo.utils.Utils.*; - -/** - * @author yahavi - */ -public class BuildInfoRecorder implements BuildInfoExtractor, ExecutionListener { - - private final Map deployableArtifacts = Maps.newConcurrentMap(); - private final Set buildTimeDependencies = Collections.synchronizedSet(new HashSet<>()); - private final ModuleArtifacts currentModuleDependencies = new ModuleArtifacts(); - private final ModuleArtifacts currentModuleArtifacts = new ModuleArtifacts(); - private final ThreadLocal currentModule = new ThreadLocal<>(); - private final BuildInfoMavenBuilder buildInfoBuilder; - private final ArtifactoryClientConfiguration conf; - private final ExecutionListener wrappedListener; - private final BuildDeployer buildDeployer; - private final Log logger; - - public BuildInfoRecorder(MavenSession session, Log logger, ArtifactoryClientConfiguration conf) { - this.wrappedListener = ObjectUtils.defaultIfNull(session.getRequest().getExecutionListener(), new AbstractExecutionListener()); - this.buildInfoBuilder = new BuildInfoModelPropertyResolver(logger, session, conf); - this.buildDeployer = new BuildDeployer(logger); - this.logger = logger; - this.conf = conf; - } - - /** - * Collect artifacts and dependencies from the project. - * - * @param event - The Maven execution event - */ - @Override - public void projectSucceeded(ExecutionEvent event) { - MavenProject project = event.getProject(); - ModuleBuilder moduleBuilder = new ModuleBuilder() - .id(getModuleIdString(project.getGroupId(), project.getArtifactId(), project.getVersion())) - .properties(project.getProperties()); - - // Replace variables - conf.getAllProperties().replaceAll((key, value) -> Utils.parseInput(value)); - - // Fill currentModuleArtifacts - addArtifacts(project); - - // Fill currentModuleDependencies - addDependencies(project); - - // Build module - addArtifactsToCurrentModule(project, moduleBuilder); - addDependenciesToCurrentModule(moduleBuilder); - buildInfoBuilder.addModule(moduleBuilder.build()); - - // Clean up - currentModule.remove(); - currentModuleArtifacts.remove(); - currentModuleDependencies.remove(); - buildTimeDependencies.clear(); - - wrappedListener.projectSucceeded(event); - } - - /** - * Add dependencies to the current running project. - * - * @param event - The Maven execution event - */ - @Override - public void mojoSucceeded(ExecutionEvent event) { - addDependencies(event.getProject()); - - wrappedListener.mojoSucceeded(event); - } - - /** - * Add dependencies to the current running project. - * - * @param event - The Maven execution event - */ - @Override - public void mojoFailed(ExecutionEvent event) { - addDependencies(event.getProject()); - - wrappedListener.mojoFailed(event); - } - - /** - * Build and publish build info. - * - * @param event - The Maven execution event - */ - @Override - public void sessionEnded(ExecutionEvent event) { - Build build = extract(event); - if (build != null) { - buildDeployer.deploy(build, conf, deployableArtifacts); - } - deployableArtifacts.clear(); - - wrappedListener.sessionEnded(event); - } - - /** - * Create a build info from 'buildInfoBuilder'. - * - * @param event - The Maven execution event - * @return - The build info object - */ - @Override - public Build extract(ExecutionEvent event) { - MavenSession session = event.getSession(); - if (session.getResult().hasExceptions()) { - return null; - } - if (conf.isIncludeEnvVars()) { - Properties envProperties = new Properties(); - envProperties.putAll(conf.getAllProperties()); - envProperties = BuildInfoExtractorUtils.getEnvProperties(envProperties, conf.getLog()); - envProperties.forEach(buildInfoBuilder::addProperty); - } - long time = new Date().getTime() - session.getRequest().getStartTime().getTime(); - return buildInfoBuilder.durationMillis(time).build(); - } - - public Set getCurrentModuleDependencies() { - return currentModuleDependencies.get(); - } - - public BuildInfoMavenBuilder getBuildInfoBuilder() { - return buildInfoBuilder; - } - - /** - * Called by {@link RepositoryListener} during resolution of implicit project and build-time dependencies. - * Enabled if 'recordAllDependencies' is set to true. - * - * @param artifact - The resolved artifact - */ - public void artifactResolved(Artifact artifact) { - if (artifact != null) { - buildTimeDependencies.add(artifact); - } - } - - /** - * Add project artifacts to the current module artifacts set. - * - * @param project - The Maven project - */ - private void addArtifacts(MavenProject project) { - currentModuleArtifacts.add(project.getArtifact()); - currentModuleArtifacts.addAll(project.getAttachedArtifacts()); - } - - /** - * Add project dependencies to the current module dependencies set. - * In case an artifact is included in both MavenProject dependencies and currentModuleDependencies, - * we'd like to keep the one that was taken from the MavenProject, because of the scope it has. - * - * @param project - The Maven project - */ - private void addDependencies(MavenProject project) { - // Create a set with new project dependencies. These dependencies are 1st priority in the set. - Set dependencies = Sets.newHashSet(); - for (Artifact artifact : project.getArtifacts()) { - String classifier = StringUtils.defaultString(artifact.getClassifier()); - String scope = StringUtils.defaultIfBlank(artifact.getScope(), Artifact.SCOPE_COMPILE); - Artifact art = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), - artifact.getVersion(), scope, artifact.getType(), classifier, artifact.getArtifactHandler()); - art.setFile(artifact.getFile()); - dependencies.add(art); - } - - // Add current project dependencies. These dependencies are 2nd priority in the set. - dependencies.addAll(currentModuleDependencies.getOrCreate()); - - // if recordAllDependencies=true, add build time dependencies - if (conf.publisher.isRecordAllDependencies()) { - dependencies.addAll(buildTimeDependencies); - } - - currentModuleDependencies.set(dependencies); - } - - /** - * Add artifacts from currentModuleArtifacts to the current module. - * - * @param project - The current Maven project - * @param moduleBuilder - The current Maven module - */ - private void addArtifactsToCurrentModule(MavenProject project, ModuleBuilder moduleBuilder) { - Set artifacts = currentModuleArtifacts.getOrCreate(); - - IncludeExcludePatterns patterns = new IncludeExcludePatterns(conf.publisher.getIncludePatterns(), conf.publisher.getExcludePatterns()); - boolean excludeArtifactsFromBuild = conf.publisher.isFilterExcludedArtifactsFromBuild(); - - boolean pomFileAdded = false; - Artifact nonPomArtifact = null; - String pomFileName = null; - - for (Artifact moduleArtifact : artifacts) { - String artifactId = moduleArtifact.getArtifactId(); - String artifactVersion = moduleArtifact.getVersion(); - String artifactClassifier = moduleArtifact.getClassifier(); - String artifactExtension = moduleArtifact.getArtifactHandler().getExtension(); - String type = getTypeString(moduleArtifact.getType(), artifactClassifier, artifactExtension); - String artifactName = getArtifactName(artifactId, artifactVersion, artifactClassifier, artifactExtension); - File artifactFile = moduleArtifact.getFile(); - - if ("pom".equals(type)) { - pomFileAdded = true; - // For pom projects take the file from the project if the artifact file is null. - if (moduleArtifact.equals(project.getArtifact())) { - // project.getFile() returns the project pom file - artifactFile = project.getFile(); - } - } else { - boolean pomExist = moduleArtifact.getMetadataList().stream() - .anyMatch(artifactMetadata -> artifactMetadata instanceof ProjectArtifactMetadata); - if (pomExist) { - nonPomArtifact = moduleArtifact; - pomFileName = StringUtils.removeEnd(artifactName, artifactExtension) + "pom"; - } - } - - org.jfrog.build.api.Artifact artifact = new ArtifactBuilder(artifactName).type(type).build(); - String groupId = moduleArtifact.getGroupId(); - String deploymentPath = getDeploymentPath(groupId, artifactId, artifactVersion, artifactClassifier, artifactExtension); - if (isFile(artifactFile)) { - boolean pathConflicts = PatternMatcher.pathConflicts(deploymentPath, patterns); - addArtifactToBuildInfo(moduleBuilder, artifact, pathConflicts, excludeArtifactsFromBuild); - addDeployableArtifact(moduleBuilder, artifact, artifactFile, pathConflicts, moduleArtifact.getGroupId(), - artifactId, artifactVersion, artifactClassifier, artifactExtension); - } - } - /* - * In case of non packaging Pom project module, we need to create the pom file from the ProjectArtifactMetadata on the Artifact - */ - if (!pomFileAdded && nonPomArtifact != null) { - String deploymentPath = getDeploymentPath(nonPomArtifact.getGroupId(), nonPomArtifact.getArtifactId(), - nonPomArtifact.getVersion(), nonPomArtifact.getClassifier(), "pom"); - addPomArtifact(moduleBuilder, nonPomArtifact, patterns, deploymentPath, pomFileName, excludeArtifactsFromBuild); - } - } - - /** - * Add artifacts from currentModuleDependencies to the current module. - * - * @param moduleBuilder - The current Maven module - */ - private void addDependenciesToCurrentModule(ModuleBuilder moduleBuilder) { - for (Artifact moduleDependency : currentModuleDependencies.getOrCreate()) { - File depFile = moduleDependency.getFile(); - DependencyBuilder dependencyBuilder = new DependencyBuilder() - .id(getModuleIdString(moduleDependency.getGroupId(), moduleDependency.getArtifactId(), moduleDependency.getVersion())) - .type(getTypeString(moduleDependency.getType(), moduleDependency.getClassifier(), getFileExtension(depFile))); - String scopes = moduleDependency.getScope(); - if (StringUtils.isNotBlank(scopes)) { - dependencyBuilder.scopes(Sets.newHashSet(scopes)); - } - Dependency dependency = dependencyBuilder.build(); - setChecksums(depFile, dependency, logger); - moduleBuilder.addDependency(dependency); - } - } - - /** - * Add pom artifact from currentModuleDependencies to the current module. - * - * @param moduleBuilder - The current Maven module - */ - private void addPomArtifact(ModuleBuilder moduleBuilder, Artifact nonPomArtifact, IncludeExcludePatterns patterns, - String deploymentPath, String pomFileName, boolean excludeArtifactsFromBuild) { - - ArtifactMetadata artifactMetadata = nonPomArtifact.getMetadataList().stream() - .filter(artifact -> artifact instanceof ProjectArtifactMetadata) - .findFirst().orElse(null); - if (artifactMetadata == null) { - // Couldn't find pom - return; - } - - File pomFile = ((ProjectArtifactMetadata) artifactMetadata).getFile(); - if (!isFile(pomFile)) { - // Couldn't find pom - return; - } - - ArtifactBuilder artifactBuilder = new ArtifactBuilder(pomFileName).type("pom"); - org.jfrog.build.api.Artifact pomArtifact = artifactBuilder.build(); - boolean pathConflicts = PatternMatcher.pathConflicts(deploymentPath, patterns); - addArtifactToBuildInfo(moduleBuilder, pomArtifact, pathConflicts, excludeArtifactsFromBuild); - addDeployableArtifact(moduleBuilder, pomArtifact, pomFile, pathConflicts, nonPomArtifact.getGroupId(), - nonPomArtifact.getArtifactId(), nonPomArtifact.getVersion(), nonPomArtifact.getClassifier(), "pom"); - } - - /** - * Add an artifact to the build. - * If excludeArtifactsFromBuild and the PatternMatcher found conflicts, add the excluded artifact to the excluded artifacts list in the build info. - * Otherwise, add the artifact to the regular artifacts list. - * - * @param module - The current Maven module - * @param artifact - The artifact to add - * @param pathConflicts - If true, consider adding the artifact to the excluded artifacts list - * @param isFilterExcludedArtifactsFromBuild - If true and the artifacts should be excluded, add the artifact to the excluded artifacts list - */ - private void addArtifactToBuildInfo(ModuleBuilder module, org.jfrog.build.api.Artifact artifact, boolean pathConflicts, boolean isFilterExcludedArtifactsFromBuild) { - if (isFilterExcludedArtifactsFromBuild && pathConflicts) { - module.addExcludedArtifact(artifact); - return; - } - module.addArtifact(artifact); - } - - /** - * Add an artifact to the deployable artifacts map. - * - * @param module - The current Maven module - * @param artifact - The artifact to add - * @param artifactFile - The file of the artifact - * @param pathConflicts - If the path conflicts, don't deploy the artifact - * @param groupId - The artifact's group ID - * @param artifactId - The artifact's ID - * @param version - The artifact's version - * @param classifier - The artifact's classifier - * @param fileExtension - The file extension, for example - 'jar' or 'pom' - */ - private void addDeployableArtifact(ModuleBuilder module, org.jfrog.build.api.Artifact artifact, File artifactFile, boolean pathConflicts, - String groupId, String artifactId, String version, String classifier, String fileExtension) { - if (pathConflicts) { - logger.info("'" + artifact.getName() + "' will not be deployed due to the defined include-exclude patterns."); - return; - } - String deploymentPath = getDeploymentPath(groupId, artifactId, version, classifier, fileExtension); - // deploy to snapshots or releases repository based on the deploy version - String targetRepository = getTargetRepository(deploymentPath); - - DeployDetails deployable = new DeployDetails.Builder() - .artifactPath(deploymentPath) - .file(artifactFile) - .targetRepository(targetRepository) - .addProperties(conf.publisher.getMatrixParams()) - .packageType(DeployDetails.PackageType.MAVEN).build(); - String myArtifactId = BuildInfoExtractorUtils.getArtifactId(module.build().getId(), artifact.getName()); - - deployableArtifacts.put(myArtifactId, deployable); - } - - /** - * Return the target deployment repository. - * Either the releases repository (default) or snapshots if defined and the deployed file is a snapshot. - * - * @param deployPath the full path string to extract the repo from - * @return Return the target deployment repository. - */ - public String getTargetRepository(String deployPath) { - String snapshotsRepository = conf.publisher.getSnapshotRepoKey(); - if (snapshotsRepository != null && deployPath.contains("-SNAPSHOT")) { - return snapshotsRepository; - } - return conf.publisher.getRepoKey(); - } - - // Forward any all events to the wrapped listener if set - @Override - public void projectDiscoveryStarted(ExecutionEvent event) { - wrappedListener.projectDiscoveryStarted(event); - } - - @Override - public void sessionStarted(ExecutionEvent event) { - wrappedListener.sessionStarted(event); - } - - @Override - public void projectSkipped(ExecutionEvent event) { - wrappedListener.projectSkipped(event); - } - - @Override - public void projectStarted(ExecutionEvent event) { - wrappedListener.projectStarted(event); - } - - @Override - public void projectFailed(ExecutionEvent event) { - wrappedListener.projectFailed(event); - } - - @Override - public void forkStarted(ExecutionEvent event) { - wrappedListener.forkStarted(event); - } - - @Override - public void forkSucceeded(ExecutionEvent event) { - wrappedListener.forkSucceeded(event); - } - - @Override - public void forkFailed(ExecutionEvent event) { - wrappedListener.forkFailed(event); - } - - @Override - public void mojoSkipped(ExecutionEvent event) { - wrappedListener.mojoSkipped(event); - } - - @Override - public void mojoStarted(ExecutionEvent event) { - wrappedListener.mojoStarted(event); - } - - @Override - public void forkedProjectStarted(ExecutionEvent event) { - wrappedListener.forkedProjectStarted(event); - } - - @Override - public void forkedProjectSucceeded(ExecutionEvent event) { - wrappedListener.forkedProjectSucceeded(event); - } - - @Override - public void forkedProjectFailed(ExecutionEvent event) { - wrappedListener.forkedProjectFailed(event); - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/RepositoryListener.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/RepositoryListener.java deleted file mode 100644 index cff232bbf..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/RepositoryListener.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.jfrog.buildinfo.resolution; - -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.codehaus.plexus.logging.Logger; -import org.eclipse.aether.AbstractRepositoryListener; -import org.eclipse.aether.RepositoryEvent; -import org.eclipse.aether.resolution.ArtifactRequest; -import org.jfrog.buildinfo.deployment.BuildInfoRecorder; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -/** - * Resolve build time dependencies. Useful if recordAllDependencies=true. - * - * @author yahavi - */ -@Named -@Singleton -public class RepositoryListener extends AbstractRepositoryListener { - - private BuildInfoRecorder buildInfoRecorder; - - /** - * Empty constructor for serialization - */ - @SuppressWarnings("unused") - public RepositoryListener() { - } - - /** - * Constructor for tests - * - * @param logger - The logger - */ - public RepositoryListener(Logger logger) { - this.logger = logger; - } - - @Inject - private Logger logger; - - public void setBuildInfoRecorder(BuildInfoRecorder buildInfoRecorder) { - this.buildInfoRecorder = buildInfoRecorder; - } - - @Override - public void artifactResolved(RepositoryEvent event) { - if (buildInfoRecorder == null) { - return; - } - String requestContext = ((ArtifactRequest) event.getTrace().getData()).getRequestContext(); - String scope = getScopeByRequestContext(requestContext); - Artifact artifact = toMavenArtifact(event.getArtifact(), scope); - if (artifact == null) { - return; - } - if (event.getRepository() != null) { - logger.debug("[buildinfo] Resolved artifact: " + artifact + " from: " + event.getRepository() + ". Context is: " + requestContext); - buildInfoRecorder.artifactResolved(artifact); - return; - } - logger.debug("[buildinfo] Could not resolve artifact: " + artifact); - } - - /** - * Converts org.eclipse.aether.artifact.Artifact objects into org.apache.maven.artifact.Artifact objects. - */ - private Artifact toMavenArtifact(final org.eclipse.aether.artifact.Artifact art, String scope) { - if (art == null) { - return null; - } - String classifier = StringUtils.defaultString(art.getClassifier()); - DefaultArtifact artifact = new DefaultArtifact(art.getGroupId(), art.getArtifactId(), art.getVersion(), scope, art.getExtension(), classifier, null); - artifact.setFile(art.getFile()); - return artifact; - } - - private String getScopeByRequestContext(String requestContext) { - return StringUtils.equals(requestContext, "plugin") ? "build" : "project"; - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/ResolutionRepoHelper.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/ResolutionRepoHelper.java deleted file mode 100644 index 922bdcf60..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/resolution/ResolutionRepoHelper.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.jfrog.buildinfo.resolution; - -import com.google.common.collect.Lists; -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; -import org.apache.maven.artifact.repository.Authentication; -import org.apache.maven.artifact.repository.MavenArtifactRepository; -import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.logging.Log; -import org.jfrog.build.extractor.BuildInfoExtractorUtils; -import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration; -import org.jfrog.buildinfo.utils.ArtifactoryMavenLogger; - -import java.util.List; -import java.util.Properties; - -/** - * Create Artifactory resolution repositories list. - * - * @author yahavi - */ -public class ResolutionRepoHelper { - - private final ArtifactoryClientConfiguration clientConfiguration; - private final Log logger; - - public ResolutionRepoHelper(Log logger, MavenSession session, ArtifactoryClientConfiguration clientConfiguration) { - this.logger = logger; - this.clientConfiguration = clientConfiguration; - Properties allMavenProps = new Properties() {{ - putAll(session.getSystemProperties()); - putAll(session.getUserProperties()); - }}; - Properties allProps = BuildInfoExtractorUtils.mergePropertiesWithSystemAndPropertyFile(allMavenProps, new ArtifactoryMavenLogger(logger)); - this.clientConfiguration.fillFromProperties(allProps); - } - - /** - * Get Artifactory resolution repositories. - * - * @return Artifactory resolution repositories - */ - public List getResolutionRepositories() { - List resolutionRepositories = Lists.newArrayList(); - String snapshotRepoUrl = getRepoSnapshotUrl(); - String releaseRepoUrl = getRepoReleaseUrl(); - String username = getRepoUsername(); - Authentication authentication = StringUtils.isNotBlank(username) ? new Authentication(username, getRepoPassword()) : null; - - // Add snapshots repository - if (StringUtils.isNotBlank(snapshotRepoUrl)) { - resolutionRepositories.add(createSnapshotsRepository(snapshotRepoUrl, authentication)); - } - - // Add releases repository - if (StringUtils.isNotBlank(releaseRepoUrl)) { - resolutionRepositories.add(createReleasesRepository(releaseRepoUrl, authentication, resolutionRepositories.isEmpty())); - } - - return resolutionRepositories; - } - - /** - * Create artifactory snapshots resolution repository. - * - * @param repoUrl - The repository URL - * @param authentication - The repository credentials - * @return artifactory snapshots resolution repository - */ - private ArtifactRepository createSnapshotsRepository(String repoUrl, Authentication authentication) { - logger.debug("[buildinfo] Enforcing snapshot repository for resolution: " + repoUrl); - ArtifactRepositoryPolicy releasePolicy = new ArtifactRepositoryPolicy(false, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); - ArtifactRepositoryPolicy snapshotPolicy = new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); - ArtifactRepository snapshotRepository = new MavenArtifactRepository("artifactory-snapshot", repoUrl, new DefaultRepositoryLayout(), snapshotPolicy, releasePolicy); - if (authentication != null) { - logger.debug("[buildinfo] Enforcing repository authentication: " + authentication + " for snapshot resolution repository"); - snapshotRepository.setAuthentication(authentication); - } - return snapshotRepository; - } - - /** - * Create artifactory releases resolution repository. - * - * @param repoUrl - The repository URL - * @param authentication - The repository credentials - * @param snapshotPolicyEnabled - True to resolve both snapshots and releases dependencies - * @return artifactory snapshots resolution repository - */ - private ArtifactRepository createReleasesRepository(String repoUrl, Authentication authentication, boolean snapshotPolicyEnabled) { - logger.debug("[buildinfo] Enforcing release repository for resolution: " + repoUrl); - String repositoryId = snapshotPolicyEnabled ? "artifactory-release-snapshot" : "artifactory-release"; - - ArtifactRepositoryPolicy releasePolicy = new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); - ArtifactRepositoryPolicy snapshotPolicy = new ArtifactRepositoryPolicy(snapshotPolicyEnabled, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN); - ArtifactRepository releasePluginRepository = new MavenArtifactRepository(repositoryId, repoUrl, new DefaultRepositoryLayout(), snapshotPolicy, releasePolicy); - if (authentication != null) { - logger.debug("[buildinfo] Enforcing repository authentication: " + authentication + " for release resolution repository"); - releasePluginRepository.setAuthentication(authentication); - } - return releasePluginRepository; - } - - private String getRepoReleaseUrl() { - return clientConfiguration.resolver.getUrl(clientConfiguration.resolver.getRepoKey()); - } - - private String getRepoSnapshotUrl() { - return clientConfiguration.resolver.getUrl(clientConfiguration.resolver.getDownloadSnapshotRepoKey()); - } - - private String getRepoUsername() { - return clientConfiguration.resolver.getUsername(); - } - - private String getRepoPassword() { - return clientConfiguration.resolver.getPassword(); - } - -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/types/ModuleArtifacts.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/types/ModuleArtifacts.java deleted file mode 100644 index a08f3e606..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/types/ModuleArtifacts.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.jfrog.buildinfo.types; - -import org.apache.maven.artifact.Artifact; - -import javax.annotation.Nonnull; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -/** - * Represents a thread local set of current module artifacts or dependencies. - * - * @author yahavi - */ -public class ModuleArtifacts extends ThreadLocal> { - - /** - * Get the set of artifacts. - * - * @return the set of current artifacts - */ - @Nonnull - public Set getOrCreate() { - Set artifacts = super.get(); - if (artifacts == null) { - artifacts = new HashSet<>(); - set(artifacts); - } - return artifacts; - } - - /** - * Add all artifacts to the set. - * - * @param artifactsToAdd - The artifacts to add - */ - public void addAll(Collection artifactsToAdd) { - Set artifacts = getOrCreate(); - artifacts.addAll(artifactsToAdd); - } - - /** - * Add an artifact to the set. - * - * @param artifactToAdd - The artifact to add - */ - public void add(Artifact artifactToAdd) { - Set artifacts = getOrCreate(); - artifacts.add(artifactToAdd); - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/ArtifactoryMavenLogger.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/ArtifactoryMavenLogger.java deleted file mode 100644 index 33f2bd285..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/ArtifactoryMavenLogger.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.jfrog.buildinfo.utils; - -import org.jfrog.build.api.util.Log; - -/** - * @author yahavi - */ -public class ArtifactoryMavenLogger implements Log { - private final org.apache.maven.plugin.logging.Log logger; - - public ArtifactoryMavenLogger(org.apache.maven.plugin.logging.Log logger) { - this.logger = logger; - } - - public void debug(String message) { - logger.debug(message); - } - - public void info(String message) { - logger.info(message); - } - - public void warn(String message) { - logger.warn(message); - } - - public void error(String message) { - logger.error(message); - } - - public void error(String message, Throwable e) { - logger.error(message, e); - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/Utils.java b/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/Utils.java deleted file mode 100644 index ce59a5045..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/java/org/jfrog/buildinfo/utils/Utils.java +++ /dev/null @@ -1,223 +0,0 @@ -package org.jfrog.buildinfo.utils; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.Maven; -import org.apache.maven.plugin.logging.Log; -import org.jfrog.build.api.BaseBuildFileBean; -import org.jfrog.build.api.util.FileChecksumCalculator; -import org.jfrog.buildinfo.ArtifactoryMojo; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.util.Map; -import java.util.Properties; -import java.util.stream.Stream; - -/** - * @author yahavi - */ -public class Utils { - - /** - * Set md5 and sha1 for the input file. - * - * @param file - The file to calculate the checksums - * @param buildFile - Dependency or Artifact - * @param logger - The logger - */ - public static void setChecksums(File file, BaseBuildFileBean buildFile, Log logger) { - if (!isFile(file)) { - return; - } - try { - Map checksumsMap = FileChecksumCalculator.calculateChecksums(file, "md5", "sha1"); - buildFile.setMd5(checksumsMap.get("md5")); - buildFile.setSha1(checksumsMap.get("sha1")); - } catch (NoSuchAlgorithmException | IOException e) { - logger.error("Could not set checksum values on '" + buildFile.getLocalPath() + "': " + e.getMessage(), e); - } - } - - /** - * Get running Maven version. - * - * @param currentClass - The caller class - * @return the Maven version - */ - @SuppressWarnings("rawtypes") - public static String getMavenVersion(Class currentClass) { - // Get Maven version from this class - Properties mavenVersionProperties = new Properties(); - try (InputStream inputStream = currentClass.getClassLoader().getResourceAsStream("org/apache/maven/messages/build.properties")) { - if (inputStream != null) { - mavenVersionProperties.load(inputStream); - } - } catch (IOException e) { - throw new RuntimeException("Error while extracting Maven version properties from: org/apache/maven/messages/build.properties", e); - } - - // Get Maven version from Maven core class - if (mavenVersionProperties.isEmpty()) { - try (InputStream inputStream = Maven.class.getClassLoader().getResourceAsStream("META-INF/maven/org.apache.maven/maven-core/pom.properties")) { - if (inputStream != null) { - mavenVersionProperties.load(inputStream); - } - } catch (IOException e) { - throw new RuntimeException("Error while extracting Maven version properties from: META-INF/maven/org.apache.maven/maven-core/pom.properties", e); - } - } - - if (mavenVersionProperties.isEmpty()) { - throw new RuntimeException("Could not extract Maven version: unable to find resources 'org/apache/maven/messages/build.properties' or 'META-INF/maven/org.apache.maven/maven-core/pom.properties'"); - } - String version = mavenVersionProperties.getProperty("version"); - if (StringUtils.isBlank(version)) { - throw new RuntimeException("Could not extract Maven version: no version property found in the resource 'org/apache/maven/messages/build.properties' or or 'META-INF/maven/org.apache.maven/maven-core/pom.properties'"); - } - return version; - } - - /** - * Get the Artifactory Maven plugin version. - * - * @return the plugin's version - */ - public static String getPluginVersion() { - try (InputStream inputStream = ArtifactoryMojo.class.getClassLoader().getResourceAsStream("META-INF/maven/org.jfrog.buildinfo/artifactory-maven-plugin/plugin-help.xml")) { - if (inputStream != null) { - try (Stream lines = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines()) { - String version = lines.filter(line -> line.contains("")).findFirst().orElse(""); - return StringUtils.substringBetween(version, "", ""); - } - } - } catch (IOException e) { - // Ignore - } - return null; - } - - /** - * Get the artifact name in form of 'artifactId-version-classifier.extension' or 'artifactId-version.extension' - * - * @param artifactId - The artifact ID - * @param version - The artifact version - * @param classifier - The classifier - * @param fileExtension - The extension of the file - * @return the artifact name - */ - public static String getArtifactName(String artifactId, String version, String classifier, String fileExtension) { - String name = artifactId + "-" + version; - if (StringUtils.isNotBlank(classifier)) { - name += "-" + classifier; - } - return name + "." + fileExtension; - } - - /** - * Get the layout path in artifactory to deploy. - * - * @param groupId - The group ID - * @param artifactId - The artifact ID - * @param version - The version - * @param classifier - The classifier - * @param fileExtension - The extension of the file - * @return deployment path - */ - public static String getDeploymentPath(String groupId, String artifactId, String version, String classifier, String fileExtension) { - return String.join("/", groupId.replace(".", "/"), artifactId, version, getArtifactName(artifactId, version, classifier, fileExtension)); - } - - /** - * Get extension of the input file. - * - * @param file - The file - * @return extension of the input file - */ - public static String getFileExtension(File file) { - if (file == null) { - return StringUtils.EMPTY; - } - return FilenameUtils.getExtension(file.getName()); - } - - /** - * Return true if the input File is actually a file. - * - * @param file - The file to check - * @return true if the input File is actually a file - */ - public static boolean isFile(File file) { - return file != null && file.isFile(); - } - - /** - * Parse "aaa{{var1|var2|var3}bbb}" values provided by the user in the pom.xml. - * - * @param input - Value from pom.xml - * @return the selected value - * @throws IllegalArgumentException if '}}' is missing - */ - public static String parseInput(String input) { - StringBuilder result = new StringBuilder(); - while (StringUtils.isNotBlank(input)) { - // Add everything before '{{' to results - String beforeBrackets = StringUtils.substringBefore(input, "{{"); - result.append(beforeBrackets); - - // Remove everything before '{{' - input = StringUtils.removeStart(input, beforeBrackets); - - // Parse everything inside '{{}}' - if (StringUtils.startsWith(input, "{{")) { - result.append(parseCurlyBrackets(input)); - // Remove '{{}}' - input = StringUtils.substringAfter(input, "}}"); - } - } - return result.toString(); - } - - /** - * Parse "{{var1|var2|var3}}" entries in the value specified to their corresponding environment variables - * or system properties. Last variable is the fallback (default) value if wrapped in double quotes. - * - * @param input - Input values surrounded by {{}}, separated by "|" - * @return first variable exist in environment or system properties. Empty string otherwise. - * @throws IllegalArgumentException if '}}' is missing - */ - private static String parseCurlyBrackets(String input) { - // Unbox curly brackets from string - String unboxed = StringUtils.substringBetween(input, "{{", "}}"); - if (unboxed == null) { - throw new IllegalArgumentException("Illegal input '" + input + "'. Missing '}}'."); - } - - // Tokenize string by '|' - String[] tokens = StringUtils.split(unboxed, "|"); - if (ArrayUtils.isEmpty(tokens)) { - // {{}} - return StringUtils.EMPTY; - } - - // Calculate default value - String lastValue = tokens[tokens.length - 1]; - String defaultValue = StringUtils.substringBetween(lastValue, "\""); // Nullable - - // Return first value that exists as environment variable or system property. - // Otherwise, if the default value exist, return it. - // Otherwise, return empty string. - int lastNotDefault = defaultValue == null ? tokens.length - 1 : tokens.length - 2; - for (int i = 0; i <= lastNotDefault; i++) { - String currentToken = tokens[i]; - String variableValue = StringUtils.firstNonBlank(System.getenv(currentToken), System.getProperty(currentToken)); - if (variableValue != null) { - return variableValue; - } - } - - return StringUtils.defaultString(defaultValue); - } -} diff --git a/xray/commands/testdata/artifactory-maven-plugin/src/main/resources/META-INF/plexus/components.xml b/xray/commands/testdata/artifactory-maven-plugin/src/main/resources/META-INF/plexus/components.xml deleted file mode 100644 index d54233acf..000000000 --- a/xray/commands/testdata/artifactory-maven-plugin/src/main/resources/META-INF/plexus/components.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - org.apache.maven.lifecycle.mapping.LifecycleMapping - jar - org.apache.maven.lifecycle.mapping.DefaultLifecycleMapping - - - org.jfrog.buildinfo:artifactory-maven-plugin:publish - - - - - diff --git a/xray/commands/testdata/dotnet-projects/dotnet-multi/ClassLibrary1/ClassLibrary1.csproj b/xray/commands/testdata/dotnet-projects/dotnet-multi/ClassLibrary1/ClassLibrary1.csproj deleted file mode 100644 index 2e24f62d3..000000000 --- a/xray/commands/testdata/dotnet-projects/dotnet-multi/ClassLibrary1/ClassLibrary1.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - netstandard2.0 - AnyCPU;x64 - Some Compnay - Some product - Copyright © 2020 by Foobar. - 1.0.0 - - - - - - - - - - - - - - diff --git a/xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.projitems b/xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.projitems deleted file mode 100644 index 266b8837a..000000000 --- a/xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.projitems +++ /dev/null @@ -1,13 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - 64bb14a4-9a54-4444-8b83-e8405a1b83a2 - - - SharedProject1 - - - - diff --git a/xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.shproj b/xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.shproj deleted file mode 100644 index 0b201723d..000000000 --- a/xray/commands/testdata/dotnet-projects/dotnet-multi/SharedProject1/SharedProject1.shproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - 64bb14a4-9a54-4444-8b83-e8405a1b83a2 - 14.0 - - - - - - - - diff --git a/xray/commands/testdata/dotnet-projects/dotnet-multi/TestApp1/TestApp1.csproj b/xray/commands/testdata/dotnet-projects/dotnet-multi/TestApp1/TestApp1.csproj deleted file mode 100644 index 86876bc8e..000000000 --- a/xray/commands/testdata/dotnet-projects/dotnet-multi/TestApp1/TestApp1.csproj +++ /dev/null @@ -1,41 +0,0 @@ - - - - Exe - netcoreapp3.1 - TestCompany - 1.0.0 - AProduct - Foobar - Frederik - AnyCPU;x64 - - - - bin\x64\Release\ - - - - bin\x64\Release\ - - - - - - - - - - - - - - - - - - - - - - diff --git a/xray/commands/testdata/dotnet-projects/dotnet-multi/TestSolution.sln b/xray/commands/testdata/dotnet-projects/dotnet-multi/TestSolution.sln deleted file mode 100644 index 1f834792b..000000000 --- a/xray/commands/testdata/dotnet-projects/dotnet-multi/TestSolution.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.32106.194 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp1", "TestApp1\TestApp1.csproj", "{757C1D5A-BAA9-453F-B612-A0571390976B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClassLibrary1", "ClassLibrary1\ClassLibrary1.csproj", "{D9C89660-69F8-46E2-B9C4-78E9B505E8B1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {757C1D5A-BAA9-453F-B612-A0571390976B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {757C1D5A-BAA9-453F-B612-A0571390976B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {757C1D5A-BAA9-453F-B612-A0571390976B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {757C1D5A-BAA9-453F-B612-A0571390976B}.Release|Any CPU.Build.0 = Release|Any CPU - {D9C89660-69F8-46E2-B9C4-78E9B505E8B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D9C89660-69F8-46E2-B9C4-78E9B505E8B1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D9C89660-69F8-46E2-B9C4-78E9B505E8B1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D9C89660-69F8-46E2-B9C4-78E9B505E8B1}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {D8547989-C4F7-4FCC-95BB-F7478F7D2484} - EndGlobalSection -EndGlobal diff --git a/xray/commands/testdata/dotnet-projects/dotnet-single/Class1.cs b/xray/commands/testdata/dotnet-projects/dotnet-single/Class1.cs deleted file mode 100644 index 4c7e615e2..000000000 --- a/xray/commands/testdata/dotnet-projects/dotnet-single/Class1.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace dotnet-single; - -public class Class1 -{ - -} diff --git a/xray/commands/testdata/dotnet-projects/dotnet-single/dotnet-single.csproj b/xray/commands/testdata/dotnet-projects/dotnet-single/dotnet-single.csproj deleted file mode 100644 index 0b5a60de8..000000000 --- a/xray/commands/testdata/dotnet-projects/dotnet-single/dotnet-single.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - net7.0 - enable - enable - - - - - - - - - - diff --git a/xray/commands/testdata/go-project/go.mod.txt b/xray/commands/testdata/go-project/go.mod.txt deleted file mode 100644 index d2ab5a42f..000000000 --- a/xray/commands/testdata/go-project/go.mod.txt +++ /dev/null @@ -1,7 +0,0 @@ -module testGoList - -go 1.16 - -require rsc.io/quote v1.5.2 - -require golang.org/x/text v0.3.3 // indirect diff --git a/xray/commands/testdata/go-project/go.sum.txt b/xray/commands/testdata/go-project/go.sum.txt deleted file mode 100644 index f97c270ca..000000000 --- a/xray/commands/testdata/go-project/go.sum.txt +++ /dev/null @@ -1,8 +0,0 @@ -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -rsc.io/quote v1.5.2 h1:w5fcysjrx7yqtD/aO+QwRjYZOKnaM9Uh2b40tElTs3Y= -rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPXsUe+TKr0= -rsc.io/sampler v1.3.0 h1:7uVkIFmeBqHfdjD+gZwtXXI+RODJ2Wc4O7MPEh/QiW4= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/xray/commands/testdata/go-project/test.go.txt b/xray/commands/testdata/go-project/test.go.txt deleted file mode 100644 index 751deb4ca..000000000 --- a/xray/commands/testdata/go-project/test.go.txt +++ /dev/null @@ -1,10 +0,0 @@ -package testGoList - -import ( - "fmt" - "rsc.io/quote" -) - -func PrintHello() { - fmt.Println(quote.Hello()) -} diff --git a/xray/commands/testdata/gradle-example-ci-server/.jfrog/projects/gradle.yaml b/xray/commands/testdata/gradle-example-ci-server/.jfrog/projects/gradle.yaml deleted file mode 100644 index 7cb5dd938..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/.jfrog/projects/gradle.yaml +++ /dev/null @@ -1,4 +0,0 @@ -version: 1 -type: gradle -usePlugin: true -useWrapper: true diff --git a/xray/commands/testdata/gradle-example-ci-server/api/build.gradle b/xray/commands/testdata/gradle-example-ci-server/api/build.gradle deleted file mode 100644 index 492158b15..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/api/build.gradle +++ /dev/null @@ -1,15 +0,0 @@ -configurations { - spi -} - -dependencies { - implementation project(':shared') - implementation module("commons-lang:commons-lang:2.4") { - dependency("commons-io:commons-io:1.2") - } - implementation group: 'org.apache.wicket', name: 'wicket', version: '1.3.7' - -} - -// Just a smoke test that using this option does not lead to any exception -compileJava.options.compilerArgs = ['-Xlint:unchecked'] diff --git a/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/PersonList.java b/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/PersonList.java deleted file mode 100644 index 1d80a16b3..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/PersonList.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.api; - -import org.gradle.apiImpl.Impl; -import org.gradle.shared.Person; - -import java.util.ArrayList; - - -public class PersonList { - private ArrayList persons = new ArrayList(); - - public void doSomethingWithImpl() { - org.apache.commons.lang.builder.ToStringBuilder stringBuilder; - try { - Class.forName("org.apache.commons.io.FileUtils"); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - new Impl().implMethod(); - } - -} diff --git a/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/package.html b/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/package.html deleted file mode 100644 index cea998a80..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/api/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - -

These are the API classes

- diff --git a/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/apiImpl/Impl.java b/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/apiImpl/Impl.java deleted file mode 100644 index 76cf0cc22..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/api/src/main/java/org/gradle/apiImpl/Impl.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.apiImpl; - - -public class Impl { - - public void implMethod() { - double a = 4.0 * 4; - } - -} diff --git a/xray/commands/testdata/gradle-example-ci-server/build.gradle b/xray/commands/testdata/gradle-example-ci-server/build.gradle deleted file mode 100644 index 79619705d..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/build.gradle +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2013 JFrog Ltd. - * - * 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. - */ - -buildscript { - repositories { - mavenCentral() - } -} - -allprojects { - repositories { - mavenCentral() - } - apply plugin: 'java' - apply plugin: 'maven-publish' - - group = 'org.jfrog.example.gradle' - version = '1.0' - status = 'integration' -} diff --git a/xray/commands/testdata/gradle-example-ci-server/gradle/wrapper/gradle-wrapper.jar b/xray/commands/testdata/gradle-example-ci-server/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 5c2d1cf016b3885f6930543d57b744ea8c220a1a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 55616 zcmafaW0WS*vSoFbZJS-TZP!<}ZQEV8ZQHihW!tvx>6!c9%-lQoy;&DmfdT@8fB*sl68LLCKtKQ283+jS?^Q-bNq|NIAW8=eB==8_)^)r*{C^$z z{u;{v?IMYnO`JhmPq7|LA_@Iz75S9h~8`iX>QrjrmMeu{>hn4U;+$dor zz+`T8Q0f}p^Ao)LsYq74!W*)&dTnv}E8;7H*Zetclpo2zf_f>9>HT8;`O^F8;M%l@ z57Z8dk34kG-~Wg7n48qF2xwPp;SOUpd1}9Moir5$VSyf4gF)Mp-?`wO3;2x9gYj59oFwG>?Leva43@e(z{mjm0b*@OAYLC`O9q|s+FQLOE z!+*Y;%_0(6Sr<(cxE0c=lS&-FGBFGWd_R<5$vwHRJG=tB&Mi8@hq_U7@IMyVyKkOo6wgR(<% zQw1O!nnQl3T9QJ)Vh=(`cZM{nsEKChjbJhx@UQH+G>6p z;beBQ1L!3Zl>^&*?cSZjy$B3(1=Zyn~>@`!j%5v7IBRt6X`O)yDpVLS^9EqmHxBcisVG$TRwiip#ViN|4( zYn!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="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/xray/commands/testdata/gradle-example-ci-server/gradlew.bat b/xray/commands/testdata/gradle-example-ci-server/gradlew.bat deleted file mode 100644 index 9618d8d96..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/gradlew.bat +++ /dev/null @@ -1,100 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/xray/commands/testdata/gradle-example-ci-server/services/webservice/build.gradle b/xray/commands/testdata/gradle-example-ci-server/services/webservice/build.gradle deleted file mode 100644 index f3ded41f2..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/services/webservice/build.gradle +++ /dev/null @@ -1,8 +0,0 @@ -apply plugin: 'war' - -dependencies { - implementation project(':shared'), 'commons-collections:commons-collections:3.2@jar', 'commons-io:commons-io:1.2', 'commons-lang:commons-lang:2.4@jar' - implementation group: 'org.apache.wicket', name: 'wicket', version: '1.3.7' - testImplementation group: 'junit', name: 'junit', version: '4.11' - implementation project(':api') -} diff --git a/xray/commands/testdata/gradle-example-ci-server/services/webservice/src/main/java/org/gradle/webservice/TestTest.java b/xray/commands/testdata/gradle-example-ci-server/services/webservice/src/main/java/org/gradle/webservice/TestTest.java deleted file mode 100644 index 4843cca41..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/services/webservice/src/main/java/org/gradle/webservice/TestTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.webservice; - -import org.apache.commons.collections.list.GrowthList; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.gradle.api.PersonList; -import org.gradle.shared.Person; - -public class TestTest { - private String name; - - public void method() { - FilenameUtils.separatorsToUnix("my/unix/filename"); - ToStringBuilder.reflectionToString(new Person("name")); - new GrowthList(); - new PersonList().doSomethingWithImpl(); // compile with api-spi, runtime with api - } - -} diff --git a/xray/commands/testdata/gradle-example-ci-server/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java b/xray/commands/testdata/gradle-example-ci-server/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java deleted file mode 100644 index b8e22a4ad..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2007 the original author or authors. - * - * 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. - */ -package org.gradle.webservice; - -import junit.framework.TestCase; - -/** - * @author Hans Dockter - */ -public class TestTestTest extends TestCase { - public void testClasspath() { - new TestTest().method(); - } - - public void testApiCompileClasspath() { - new org.gradle.api.PersonList(); - } -} diff --git a/xray/commands/testdata/gradle-example-ci-server/settings.gradle b/xray/commands/testdata/gradle-example-ci-server/settings.gradle deleted file mode 100644 index 397a3021a..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -include "shared", "api", "services:webservice" diff --git a/xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/Person.java b/xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/Person.java deleted file mode 100644 index d9ed11ee8..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/Person.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.shared; - -import java.io.IOException; -import java.util.Properties; - -public class Person { - private String name; - - public Person(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String readProperty() throws IOException { - Properties properties = new Properties(); - properties.load(getClass().getClassLoader().getResourceAsStream("org/gradle/shared/main.properties")); - return properties.getProperty("main"); - } -} diff --git a/xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/package-info.java b/xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/package-info.java deleted file mode 100644 index 7c5f65caf..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/shared/src/main/java/org/gradle/shared/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -/** - * These are the shared classes. - */ -package org.gradle.shared; diff --git a/xray/commands/testdata/gradle-example-ci-server/shared/src/main/resources/org/gradle/shared/main.properties b/xray/commands/testdata/gradle-example-ci-server/shared/src/main/resources/org/gradle/shared/main.properties deleted file mode 100644 index 68fed4627..000000000 --- a/xray/commands/testdata/gradle-example-ci-server/shared/src/main/resources/org/gradle/shared/main.properties +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright (C) 2011 JFrog Ltd. -# -# 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. -# - -main=mainValue diff --git a/xray/commands/testdata/gradle-example-publish/.jfrog/projects/gradle.yaml b/xray/commands/testdata/gradle-example-publish/.jfrog/projects/gradle.yaml deleted file mode 100644 index 7cb5dd938..000000000 --- a/xray/commands/testdata/gradle-example-publish/.jfrog/projects/gradle.yaml +++ /dev/null @@ -1,4 +0,0 @@ -version: 1 -type: gradle -usePlugin: true -useWrapper: true diff --git a/xray/commands/testdata/gradle-example-publish/api/build.gradle b/xray/commands/testdata/gradle-example-publish/api/build.gradle deleted file mode 100644 index 492158b15..000000000 --- a/xray/commands/testdata/gradle-example-publish/api/build.gradle +++ /dev/null @@ -1,15 +0,0 @@ -configurations { - spi -} - -dependencies { - implementation project(':shared') - implementation module("commons-lang:commons-lang:2.4") { - dependency("commons-io:commons-io:1.2") - } - implementation group: 'org.apache.wicket', name: 'wicket', version: '1.3.7' - -} - -// Just a smoke test that using this option does not lead to any exception -compileJava.options.compilerArgs = ['-Xlint:unchecked'] diff --git a/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/PersonList.java b/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/PersonList.java deleted file mode 100644 index 1d80a16b3..000000000 --- a/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/PersonList.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.api; - -import org.gradle.apiImpl.Impl; -import org.gradle.shared.Person; - -import java.util.ArrayList; - - -public class PersonList { - private ArrayList persons = new ArrayList(); - - public void doSomethingWithImpl() { - org.apache.commons.lang.builder.ToStringBuilder stringBuilder; - try { - Class.forName("org.apache.commons.io.FileUtils"); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - new Impl().implMethod(); - } - -} diff --git a/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/package.html b/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/package.html deleted file mode 100644 index cea998a80..000000000 --- a/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/api/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - -

These are the API classes

- diff --git a/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/apiImpl/Impl.java b/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/apiImpl/Impl.java deleted file mode 100644 index 76cf0cc22..000000000 --- a/xray/commands/testdata/gradle-example-publish/api/src/main/java/org/gradle/apiImpl/Impl.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.apiImpl; - - -public class Impl { - - public void implMethod() { - double a = 4.0 * 4; - } - -} diff --git a/xray/commands/testdata/gradle-example-publish/build.gradle b/xray/commands/testdata/gradle-example-publish/build.gradle deleted file mode 100644 index 13c8bbf43..000000000 --- a/xray/commands/testdata/gradle-example-publish/build.gradle +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (C) 2013 JFrog Ltd. - * - * 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. - */ - -buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '4+') - } - configurations.classpath { - resolutionStrategy { - cacheDynamicVersionsFor 0, 'seconds' - cacheChangingModulesFor 0, 'seconds' - } - } -} - - -def javaProjects() { - subprojects.findAll { new File(it.projectDir, 'src').directory } -} - -allprojects { - apply plugin: 'com.jfrog.artifactory' - group = 'org.jfrog.test.gradle.publish' - version = currentVersion - status = 'Integration' - repositories { - mavenCentral() - } -} - -// Setting this property to true will make the artifactoryPublish task -// skip this module (in our case, the root module): -artifactoryPublish.skip = true - -project('services') { - artifactoryPublish.skip = true -} - -configure(javaProjects()) { - apply plugin: 'java' - apply plugin: 'maven-publish' - - dependencies { - testImplementation 'junit:junit:4.7' - } - - publishing { - publications { - mavenJava(MavenPublication) { - from components.java - artifact(file("$rootDir/gradle.properties")) - } - } - } -} - -project('api') { - apply plugin: 'ivy-publish' - - publishing { - publications { - ivyJava(IvyPublication) { - from components.java - artifact(file("$rootDir/settings.gradle")) { - name "gradle-settings" - extension "txt" - type "text" - } - // The config below will add a extra attribute to the ivy.xml - // See http://ant.apache.org/ivy/history/latest-milestone/concept.html#extra - descriptor.withXml { - asNode().info[0].attributes().put('e:architecture', 'amd64') - } - } - } - } - - artifactoryPublish { - publications(publishing.publications.ivyJava) - properties { - simpleFile '**:**:**:*@*', simpleFile: 'only on settings file' - } - } -} - -artifactory { - clientConfig.setIncludeEnvVars(true) - clientConfig.info.addEnvironmentProperty('test.adding.dynVar',new java.util.Date().toString()) - - contextUrl = 'http://127.0.0.1:8081/artifactory' - publish { - repository { - repoKey = 'libs-snapshot-local' // The Artifactory repository key to publish to - username = "${artifactory_user}" // The publisher user name - password = "${artifactory_password}" // The publisher password - // This is an optional section for configuring Ivy publication (when publishIvy = true). - ivy { - ivyLayout = '[organization]/[module]/ivy-[revision].xml' - artifactLayout = '[organization]/[module]/[revision]/[module]-[revision](-[classifier]).[ext]' - mavenCompatible = true //Convert any dots in an [organization] layout value to path separators, similar to Maven's groupId-to-path conversion. True if not specified - } - } - defaults { - // Reference to Gradle publications defined in the build script. - // This is how we tell the Artifactory Plugin which artifacts should be - // published to Artifactory. - publications('mavenJava') - publishArtifacts = true - // Properties to be attached to the published artifacts. - properties = ['qa.level': 'basic', 'dev.team' : 'core'] - publishPom = true // Publish generated POM files to Artifactory (true by default) - publishIvy = true // Publish generated Ivy descriptor files to Artifactory (true by default) - } - } -} diff --git a/xray/commands/testdata/gradle-example-publish/gradle.properties b/xray/commands/testdata/gradle-example-publish/gradle.properties deleted file mode 100644 index 266947aa2..000000000 --- a/xray/commands/testdata/gradle-example-publish/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -currentVersion=1.0-SNAPSHOT -artifactory_user=admin -artifactory_password=password diff --git a/xray/commands/testdata/gradle-example-publish/gradle/wrapper/gradle-wrapper.jar b/xray/commands/testdata/gradle-example-publish/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 5c2d1cf016b3885f6930543d57b744ea8c220a1a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 55616 zcmafaW0WS*vSoFbZJS-TZP!<}ZQEV8ZQHihW!tvx>6!c9%-lQoy;&DmfdT@8fB*sl68LLCKtKQ283+jS?^Q-bNq|NIAW8=eB==8_)^)r*{C^$z z{u;{v?IMYnO`JhmPq7|LA_@Iz75S9h~8`iX>QrjrmMeu{>hn4U;+$dor zz+`T8Q0f}p^Ao)LsYq74!W*)&dTnv}E8;7H*Zetclpo2zf_f>9>HT8;`O^F8;M%l@ z57Z8dk34kG-~Wg7n48qF2xwPp;SOUpd1}9Moir5$VSyf4gF)Mp-?`wO3;2x9gYj59oFwG>?Leva43@e(z{mjm0b*@OAYLC`O9q|s+FQLOE z!+*Y;%_0(6Sr<(cxE0c=lS&-FGBFGWd_R<5$vwHRJG=tB&Mi8@hq_U7@IMyVyKkOo6wg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Mzeen3cGpiTgzVp- z`aj3&Wv0(he1qKI!2jpGpO-i0Wpcz%vdn`2o9x&3;^nsZPt3c \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/xray/commands/testdata/gradle-example-publish/gradlew.bat b/xray/commands/testdata/gradle-example-publish/gradlew.bat deleted file mode 100644 index 9618d8d96..000000000 --- a/xray/commands/testdata/gradle-example-publish/gradlew.bat +++ /dev/null @@ -1,100 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/xray/commands/testdata/gradle-example-publish/services/webservice/build.gradle b/xray/commands/testdata/gradle-example-publish/services/webservice/build.gradle deleted file mode 100644 index e64906460..000000000 --- a/xray/commands/testdata/gradle-example-publish/services/webservice/build.gradle +++ /dev/null @@ -1,7 +0,0 @@ -apply plugin: 'war' - -dependencies { - implementation project(':shared'), 'commons-collections:commons-collections:3.2@jar', 'commons-io:commons-io:1.2', 'commons-lang:commons-lang:2.4@jar' - implementation group: 'org.apache.wicket', name: 'wicket', version: '1.3.7' - implementation project(':api') -} diff --git a/xray/commands/testdata/gradle-example-publish/services/webservice/src/main/java/org/gradle/webservice/TestTest.java b/xray/commands/testdata/gradle-example-publish/services/webservice/src/main/java/org/gradle/webservice/TestTest.java deleted file mode 100644 index 4843cca41..000000000 --- a/xray/commands/testdata/gradle-example-publish/services/webservice/src/main/java/org/gradle/webservice/TestTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.webservice; - -import org.apache.commons.collections.list.GrowthList; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.gradle.api.PersonList; -import org.gradle.shared.Person; - -public class TestTest { - private String name; - - public void method() { - FilenameUtils.separatorsToUnix("my/unix/filename"); - ToStringBuilder.reflectionToString(new Person("name")); - new GrowthList(); - new PersonList().doSomethingWithImpl(); // compile with api-spi, runtime with api - } - -} diff --git a/xray/commands/testdata/gradle-example-publish/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java b/xray/commands/testdata/gradle-example-publish/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java deleted file mode 100644 index b8e22a4ad..000000000 --- a/xray/commands/testdata/gradle-example-publish/services/webservice/src/test/java/org/gradle/webservice/TestTestTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2007 the original author or authors. - * - * 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. - */ -package org.gradle.webservice; - -import junit.framework.TestCase; - -/** - * @author Hans Dockter - */ -public class TestTestTest extends TestCase { - public void testClasspath() { - new TestTest().method(); - } - - public void testApiCompileClasspath() { - new org.gradle.api.PersonList(); - } -} diff --git a/xray/commands/testdata/gradle-example-publish/settings.gradle b/xray/commands/testdata/gradle-example-publish/settings.gradle deleted file mode 100644 index 397a3021a..000000000 --- a/xray/commands/testdata/gradle-example-publish/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -include "shared", "api", "services:webservice" diff --git a/xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/Person.java b/xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/Person.java deleted file mode 100644 index d9ed11ee8..000000000 --- a/xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/Person.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -package org.gradle.shared; - -import java.io.IOException; -import java.util.Properties; - -public class Person { - private String name; - - public Person(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String readProperty() throws IOException { - Properties properties = new Properties(); - properties.load(getClass().getClassLoader().getResourceAsStream("org/gradle/shared/main.properties")); - return properties.getProperty("main"); - } -} diff --git a/xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/package-info.java b/xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/package-info.java deleted file mode 100644 index 7c5f65caf..000000000 --- a/xray/commands/testdata/gradle-example-publish/shared/src/main/java/org/gradle/shared/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2011 JFrog Ltd. - * - * 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. - */ - -/** - * These are the shared classes. - */ -package org.gradle.shared; diff --git a/xray/commands/testdata/gradle-example-publish/shared/src/main/resources/org/gradle/shared/main.properties b/xray/commands/testdata/gradle-example-publish/shared/src/main/resources/org/gradle/shared/main.properties deleted file mode 100644 index 68fed4627..000000000 --- a/xray/commands/testdata/gradle-example-publish/shared/src/main/resources/org/gradle/shared/main.properties +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright (C) 2011 JFrog Ltd. -# -# 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. -# - -main=mainValue diff --git a/xray/commands/testdata/iac-scan/contains-iac-violations-working-dir.sarif b/xray/commands/testdata/iac-scan/contains-iac-violations-working-dir.sarif deleted file mode 100644 index cb7d1aa51..000000000 --- a/xray/commands/testdata/iac-scan/contains-iac-violations-working-dir.sarif +++ /dev/null @@ -1,669 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Terraform scanner", - "rules": [ - { - "id": "aws_alb_https_only", - "fullDescription": { - "text": "Resources `aws_lb_listener` and `aws_alb_listener` should set `protocol = \"HTTPS\"` (default is `\"HTTP\"`)\n\nVulnerable example -\n```\nresource \"aws_lb_listener\" \"vulnerable_example\" {\n protocol = \"HTTP\"\n}\n```\n\nSecure example -\n```\nresource \"aws_lb_listener\" \"secure_example\" {\n protocol = \"HTTPS\"\n}\n```", - "markdown": "Resources `aws_lb_listener` and `aws_alb_listener` should set `protocol = \"HTTPS\"` (default is `\"HTTP\"`)\n\nVulnerable example -\n```\nresource \"aws_lb_listener\" \"vulnerable_example\" {\n protocol = \"HTTP\"\n}\n```\n\nSecure example -\n```\nresource \"aws_lb_listener\" \"secure_example\" {\n protocol = \"HTTPS\"\n}\n```" - }, - "shortDescription": { - "text": "Scanner for aws_alb_https_only" - } - }, - { - "id": "aws_cloudwatch_log_encrypt", - "fullDescription": { - "text": "Resource `aws_cloudwatch_log_group` should have `kms_key_id`\n\nVulnerable example - \n```\nresource \"aws_cloudwatch_log_group\" \"vulnerable_example\" {\n # kms_key_id is not set\n}\n```\n\nSecure example -\n```\nresource \"aws_cloudwatch_log_group\" \"secure_example\" {\n kms_key_id = aws_kms_key.example.arn\n}\n```", - "markdown": "Resource `aws_cloudwatch_log_group` should have `kms_key_id`\n\nVulnerable example - \n```\nresource \"aws_cloudwatch_log_group\" \"vulnerable_example\" {\n # kms_key_id is not set\n}\n```\n\nSecure example -\n```\nresource \"aws_cloudwatch_log_group\" \"secure_example\" {\n kms_key_id = aws_kms_key.example.arn\n}\n```" - }, - "shortDescription": { - "text": "Scanner for aws_cloudwatch_log_encrypt" - } - }, - { - "id": "aws_docdb_encrypt_cluster", - "fullDescription": { - "text": "Resource `aws_docdb_cluster` should have `storage_encrypted=true`\n\nVulnerable example - \n```\nresource \"aws_docdb_cluster\" \"vulnerable_example\" {\n # storage_encrypted is unset\n}\n```\n\nSecure example -\n```\nresource \"aws_docdb_cluster\" \"secure_example\" {\n storage_encrypted = true\n}\n```", - "markdown": "Resource `aws_docdb_cluster` should have `storage_encrypted=true`\n\nVulnerable example - \n```\nresource \"aws_docdb_cluster\" \"vulnerable_example\" {\n # storage_encrypted is unset\n}\n```\n\nSecure example -\n```\nresource \"aws_docdb_cluster\" \"secure_example\" {\n storage_encrypted = true\n}\n```" - }, - "shortDescription": { - "text": "Scanner for aws_docdb_encrypt_cluster" - } - }, - { - "id": "aws_eks_encrypt_cluster", - "fullDescription": { - "text": "Resource `aws_eks_cluster` should have key `encryption_config`\n\nVulnerable example -\n```\nresource \"aws_eks_cluster\" \"vulnerable_example\" {\n # encryption_config is not set\n}\n```\n\nSecure example -\n```\nresource \"aws_eks_cluster\" \"secure_example\" {\n encryption_config {\n resources = [ \"secrets\" ]\n provider {\n key_arn = aws_kms_key.example.arn\n }\n }\n}\n```", - "markdown": "Resource `aws_eks_cluster` should have key `encryption_config`\n\nVulnerable example -\n```\nresource \"aws_eks_cluster\" \"vulnerable_example\" {\n # encryption_config is not set\n}\n```\n\nSecure example -\n```\nresource \"aws_eks_cluster\" \"secure_example\" {\n encryption_config {\n resources = [ \"secrets\" ]\n provider {\n key_arn = aws_kms_key.example.arn\n }\n }\n}\n```" - }, - "shortDescription": { - "text": "Scanner for aws_eks_encrypt_cluster" - } - }, - { - "id": "aws_eks_no_cidr", - "fullDescription": { - "text": "Resource `aws_eks_cluster` should have key `public_access_cidrs` (default is `0.0.0.0/0` which is overly permissive). Note that this endpoint is only enabled when `endpoint_public_access = true` (default is `true`)\n\nVulnerable example -\n```\nresource \"aws_eks_cluster\" \"vulnerable_example\" {\n vpc_config {\n endpoint_public_access = true # or unset\n public_access_cidrs = [\"0.0.0.0/0\"] # or unset \n }\n }\n```\n\nSecure example #1 -\n```\nresource \"aws_eks_cluster\" \"secure_example_1\" {\n vpc_config {\n endpoint_public_access = false\n }\n }\n```\n\nSecure example #2 -\n```\nresource \"aws_eks_cluster\" \"secure_example_2\" {\n vpc_config {\n endpoint_public_access = true\n public_access_cidrs = [\"192.168.0.0/24\"]\n }\n }\n```", - "markdown": "Resource `aws_eks_cluster` should have key `public_access_cidrs` (default is `0.0.0.0/0` which is overly permissive). Note that this endpoint is only enabled when `endpoint_public_access = true` (default is `true`)\n\nVulnerable example -\n```\nresource \"aws_eks_cluster\" \"vulnerable_example\" {\n vpc_config {\n endpoint_public_access = true # or unset\n public_access_cidrs = [\"0.0.0.0/0\"] # or unset \n }\n }\n```\n\nSecure example #1 -\n```\nresource \"aws_eks_cluster\" \"secure_example_1\" {\n vpc_config {\n endpoint_public_access = false\n }\n }\n```\n\nSecure example #2 -\n```\nresource \"aws_eks_cluster\" \"secure_example_2\" {\n vpc_config {\n endpoint_public_access = true\n public_access_cidrs = [\"192.168.0.0/24\"]\n }\n }\n```" - }, - "shortDescription": { - "text": "Scanner for aws_eks_no_cidr" - } - }, - { - "id": "aws_rds_encrypt_instance", - "fullDescription": { - "text": "Resource `aws_db_instance` should have `storage_encrypted=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_db_instance\" \"vulnerable_example\" {\r\n # storage_encrypted is not set\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_db_instance\" \"secure_example\" {\r\n kms_key_id = aws_kms_key.example.arn\r\n storage_encrypted = true\r\n}\r\n```", - "markdown": "Resource `aws_db_instance` should have `storage_encrypted=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_db_instance\" \"vulnerable_example\" {\r\n # storage_encrypted is not set\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_db_instance\" \"secure_example\" {\r\n kms_key_id = aws_kms_key.example.arn\r\n storage_encrypted = true\r\n}\r\n```" - }, - "shortDescription": { - "text": "Scanner for aws_rds_encrypt_instance" - } - }, - { - "id": "aws_rds_iam_auth", - "fullDescription": { - "text": "Resource `aws_db_instance` should have `iam_database_authentication_enabled=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_db_instance\" \"vulnerable_example\" {\r\n # iam_database_authentication_enabled is unset (or false)\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_db_instance\" \"secure_example\" {\r\n iam_database_authentication_enabled = true\r\n}\r\n```", - "markdown": "Resource `aws_db_instance` should have `iam_database_authentication_enabled=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_db_instance\" \"vulnerable_example\" {\r\n # iam_database_authentication_enabled is unset (or false)\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_db_instance\" \"secure_example\" {\r\n iam_database_authentication_enabled = true\r\n}\r\n```" - }, - "shortDescription": { - "text": "Scanner for aws_rds_iam_auth" - } - }, - { - "id": "aws_s3_block_public_acl", - "fullDescription": { - "text": "If resource `aws_s3_bucket` exists, then resource `aws_s3_bucket_public_access_block` must also exist and have `block_public_acls=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"vulnerable_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n # block_public_acls is not set\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"secure_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n block_public_acls = true\r\n}\r\n```", - "markdown": "If resource `aws_s3_bucket` exists, then resource `aws_s3_bucket_public_access_block` must also exist and have `block_public_acls=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"vulnerable_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n # block_public_acls is not set\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"secure_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n block_public_acls = true\r\n}\r\n```" - }, - "shortDescription": { - "text": "Scanner for aws_s3_block_public_acl" - } - }, - { - "id": "aws_s3_block_public_policy", - "fullDescription": { - "text": "If resource `aws_s3_bucket` exists, then resource `aws_s3_bucket_public_access_block` must also exist and have `block_public_acls=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"vulnerable_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n # block_public_acls is not set\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"secure_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n block_public_acls = true\r\n}\r\n```", - "markdown": "If resource `aws_s3_bucket` exists, then resource `aws_s3_bucket_public_access_block` must also exist and have `block_public_acls=true`\r\n\r\nVulnerable example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"vulnerable_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n # block_public_acls is not set\r\n}\r\n```\r\n\r\nSecure example -\r\n```\r\nresource \"aws_s3_bucket\" \"example_bucket\" {\r\n bucket = \"mybucket\"\r\n}\r\n\r\nresource \"aws_s3_bucket_public_access_block\" \"secure_example\" {\r\n bucket = aws_s3_bucket.example_bucket.id\r\n block_public_acls = true\r\n}\r\n```" - }, - "shortDescription": { - "text": "Scanner for aws_s3_block_public_policy" - } - }, - { - "id": "aws_s3_encrypt", - "fullDescription": { - "text": "If resource `aws_s3_bucket` exists, then resource `aws_s3_bucket_server_side_encryption_configuration` must also exist with the key `apply_server_side_encryption_by_default`. Alternatively, the `aws_s3_bucket` resource should have the (deprecated) `server_side_encryption_configuration` key.\n\nVulnerable example #1 -\n```\nresource \"aws_s3_bucket\" \"mybucket\" {\n bucket = \"mybucket\"\n}\n\n# resource \"aws_s3_bucket_server_side_encryption_configuration\" is not defined\n```\n\nSecure example #1 -\n```\nresource \"aws_s3_bucket\" \"mybucket\" {\n bucket = \"mybucket\"\n}\n\nresource \"aws_s3_bucket_server_side_encryption_configuration\" \"secure_example_1\" {\n bucket = aws_s3_bucket.mybucket.bucket\n\n rule {\n apply_server_side_encryption_by_default {\n kms_master_key_id = aws_kms_key.mykey.arn\n sse_algorithm = \"aws:kms\"\n }\n }\n}\n```\n\nVulnerable example #2 -\n```\nresource \"aws_s3_bucket\" \"vulnerable_example_2\" {\n # server_side_encryption_configuration is not set\n}\n```\n\nSecure example #2 -\n```\nresource \"aws_s3_bucket\" \"secure_example_2\" {\n bucket = \"mybucket\"\n\n server_side_encryption_configuration {\n rule {\n apply_server_side_encryption_by_default {\n kms_master_key_id = aws_kms_key.mykey.arn\n sse_algorithm = \"aws:kms\"\n }\n }\n }\n}\n```", - "markdown": "If resource `aws_s3_bucket` exists, then resource `aws_s3_bucket_server_side_encryption_configuration` must also exist with the key `apply_server_side_encryption_by_default`. Alternatively, the `aws_s3_bucket` resource should have the (deprecated) `server_side_encryption_configuration` key.\n\nVulnerable example #1 -\n```\nresource \"aws_s3_bucket\" \"mybucket\" {\n bucket = \"mybucket\"\n}\n\n# resource \"aws_s3_bucket_server_side_encryption_configuration\" is not defined\n```\n\nSecure example #1 -\n```\nresource \"aws_s3_bucket\" \"mybucket\" {\n bucket = \"mybucket\"\n}\n\nresource \"aws_s3_bucket_server_side_encryption_configuration\" \"secure_example_1\" {\n bucket = aws_s3_bucket.mybucket.bucket\n\n rule {\n apply_server_side_encryption_by_default {\n kms_master_key_id = aws_kms_key.mykey.arn\n sse_algorithm = \"aws:kms\"\n }\n }\n}\n```\n\nVulnerable example #2 -\n```\nresource \"aws_s3_bucket\" \"vulnerable_example_2\" {\n # server_side_encryption_configuration is not set\n}\n```\n\nSecure example #2 -\n```\nresource \"aws_s3_bucket\" \"secure_example_2\" {\n bucket = \"mybucket\"\n\n server_side_encryption_configuration {\n rule {\n apply_server_side_encryption_by_default {\n kms_master_key_id = aws_kms_key.mykey.arn\n sse_algorithm = \"aws:kms\"\n }\n }\n }\n}\n```" - }, - "shortDescription": { - "text": "Scanner for aws_s3_encrypt" - } - } - ], - "version": "" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "iac_scanner/tf_scanner", - "scan", - "/var/folders/mj/sk15wcdx5kl7p5shk662bjt80000gn/T/jfrog.cli.temp.-1690974158-62790465/config.yaml" - ], - "workingDirectory": { - "uri": "file:///Users/omerz/.jfrog/dependencies/analyzerManager" - } - } - ], - "results": [ - { - "message": { - "text": "storage_encrypted=false was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/byok/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 121, - "snippet": { - "text": "byok_database" - }, - "startColumn": 1, - "startLine": 69 - } - } - } - ], - "ruleId": "aws_rds_encrypt_instance" - }, - { - "message": { - "text": "iam_database_authentication_enabled=False was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/byok/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 121, - "snippet": { - "text": "byok_database" - }, - "startColumn": 1, - "startLine": 69 - } - } - } - ], - "ruleId": "aws_rds_iam_auth" - }, - { - "message": { - "text": "storage_encrypted=False was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/documentdb/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 31, - "snippet": { - "text": "default" - }, - "startColumn": 1, - "startLine": 15 - } - } - } - ], - "ruleId": "aws_docdb_encrypt_cluster" - }, - { - "message": { - "text": "AWS EKS public API server is publicly accessible" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/eks_mng_ng/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 65, - "snippet": { - "text": "aws_eks" - }, - "startColumn": 1, - "startLine": 36 - } - } - } - ], - "ruleId": "aws_eks_no_cidr" - }, - { - "message": { - "text": "AWS EKS public API server is publicly accessible" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/eks_mng_ng_coralogix/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 65, - "snippet": { - "text": "aws_eks" - }, - "startColumn": 1, - "startLine": 36 - } - } - } - ], - "ruleId": "aws_eks_no_cidr" - }, - { - "message": { - "text": "AWS EKS public API server is publicly accessible" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/k8s/module/cluster.tf" - }, - "region": { - "endColumn": 2, - "endLine": 24, - "snippet": { - "text": "this" - }, - "startColumn": 1, - "startLine": 1 - } - } - } - ], - "ruleId": "aws_eks_no_cidr" - }, - { - "message": { - "text": "AWS EKS secrets do not usedata-at-rest encryption" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/k8s/module/cluster.tf" - }, - "region": { - "endColumn": 2, - "endLine": 24, - "snippet": { - "text": "this" - }, - "startColumn": 1, - "startLine": 1 - } - } - } - ], - "ruleId": "aws_eks_encrypt_cluster" - }, - { - "message": { - "text": "AWS EKS public API server is publicly accessible" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/k8s/module2/cluster.tf" - }, - "region": { - "endColumn": 2, - "endLine": 49, - "snippet": { - "text": "this" - }, - "startColumn": 1, - "startLine": 9 - } - } - } - ], - "ruleId": "aws_eks_no_cidr" - }, - { - "message": { - "text": "kms_key_id='' was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/msk/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 33, - "snippet": { - "text": "log" - }, - "startColumn": 1, - "startLine": 30 - } - } - } - ], - "ruleId": "aws_cloudwatch_log_encrypt" - }, - { - "message": { - "text": "block_public_acls=false was detected" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/msk/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 39, - "snippet": { - "text": "bucket" - }, - "startColumn": 1, - "startLine": 35 - } - } - } - ], - "ruleId": "aws_s3_block_public_acl" - }, - { - "message": { - "text": "block_public_acls=false was detected" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/msk/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 39, - "snippet": { - "text": "bucket" - }, - "startColumn": 1, - "startLine": 35 - } - } - } - ], - "ruleId": "aws_s3_block_public_policy" - }, - { - "message": { - "text": "Missing server_side_encryption_configuration was detected, Missing aws_s3_bucket_server_side_encryption_configuration was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/msk/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 39, - "snippet": { - "text": "bucket" - }, - "startColumn": 1, - "startLine": 35 - } - } - } - ], - "ruleId": "aws_s3_encrypt" - }, - { - "message": { - "text": "Missing server_side_encryption_configuration was detected, Missing aws_s3_bucket_server_side_encryption_configuration was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/msk/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 39, - "snippet": { - "text": "bucket" - }, - "startColumn": 1, - "startLine": 35 - } - } - } - ], - "ruleId": "aws_s3_encrypt" - }, - { - "message": { - "text": "storage_encrypted=false was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/mysql_coralogix/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 147, - "snippet": { - "text": "k8s_database" - }, - "startColumn": 1, - "startLine": 102 - } - } - } - ], - "ruleId": "aws_rds_encrypt_instance" - }, - { - "message": { - "text": "iam_database_authentication_enabled=False was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/mysql_coralogix/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 147, - "snippet": { - "text": "k8s_database" - }, - "startColumn": 1, - "startLine": 102 - } - } - } - ], - "ruleId": "aws_rds_iam_auth" - }, - { - "message": { - "text": "AWS Load balancer using insecure communications" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/private_link/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 68, - "snippet": { - "text": "pl_lb_listener" - }, - "startColumn": 1, - "startLine": 53 - } - } - } - ], - "ruleId": "aws_alb_https_only" - }, - { - "message": { - "text": "AWS Load balancer using insecure communications" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/private_link/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 115, - "snippet": { - "text": "pl_lb_listener_plain" - }, - "startColumn": 1, - "startLine": 100 - } - } - } - ], - "ruleId": "aws_alb_https_only" - }, - { - "message": { - "text": "storage_encrypted=false was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/rds/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 152, - "snippet": { - "text": "k8s_database" - }, - "startColumn": 1, - "startLine": 103 - } - } - } - ], - "ruleId": "aws_rds_encrypt_instance" - }, - { - "message": { - "text": "iam_database_authentication_enabled=False was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/rds/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 152, - "snippet": { - "text": "k8s_database" - }, - "startColumn": 1, - "startLine": 103 - } - } - } - ], - "ruleId": "aws_rds_iam_auth" - }, - { - "message": { - "text": "block_public_acls=false was detected" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/s3/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 28, - "snippet": { - "text": "default" - }, - "startColumn": 1, - "startLine": 8 - } - } - } - ], - "ruleId": "aws_s3_block_public_acl" - }, - { - "message": { - "text": "block_public_acls=false was detected" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/s3/module.tf" - }, - "region": { - "endColumn": 2, - "endLine": 28, - "snippet": { - "text": "default" - }, - "startColumn": 1, - "startLine": 8 - } - } - } - ], - "ruleId": "aws_s3_block_public_policy" - }, - { - "message": { - "text": "kms_key_id='' was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/omerz/Documents/analyzers_test/iac/aws/vpc/module2/examples/vpc-flow-logs/cloud-watch-logs.tf" - }, - "region": { - "endColumn": 2, - "endLine": 53, - "snippet": { - "text": "flow_log" - }, - "startColumn": 1, - "startLine": 51 - } - } - } - ], - "ruleId": "aws_cloudwatch_log_encrypt" - } - ] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/iac-scan/contains-iac-violations.sarif b/xray/commands/testdata/iac-scan/contains-iac-violations.sarif deleted file mode 100644 index f9ee53018..000000000 --- a/xray/commands/testdata/iac-scan/contains-iac-violations.sarif +++ /dev/null @@ -1,129 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Terraform scanner", - "rules": [], - "version": "" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "./tf_scanner", - "scan", - "scan.yaml" - ], - "workingDirectory": { - "uri": "file:///Users/ilya/Downloads/tf-scanner-main/src/dist/tf_scanner" - } - } - ], - "results": [ - { - "message": { - "text": "AWS Load balancer using insecure communications" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/ilya/Downloads/tf-scanner-main/tests/hcl/applicable/req_sw_terraform_aws_alb_https_only.tf" - }, - "region": { - "endColumn": 2, - "endLine": 12, - "snippet": { - "text": "vulnerable_example" - }, - "startColumn": 1, - "startLine": 1 - } - } - } - ], - "ruleId": "aws_alb_https_only" - }, - { - "message": { - "text": "authorization=NONE was detected" - }, - "level": "error", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/ilya/Downloads/tf-scanner-main/tests/hcl/applicable/req_sw_terraform_aws_api_gateway_auth.tf" - }, - "region": { - "endColumn": 2, - "endLine": 6, - "snippet": { - "text": "vulnerable_method" - }, - "startColumn": 1, - "startLine": 1 - } - } - } - ], - "ruleId": "aws_api_gateway_auth" - }, - { - "message": { - "text": "cache_data_encrypted=False was detected" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/ilya/Downloads/tf-scanner-main/tests/hcl/applicable/req_sw_terraform_aws_api_gateway_encrypt_cache.tf" - }, - "region": { - "endColumn": 2, - "endLine": 8, - "snippet": { - "text": "vulnerable_example" - }, - "startColumn": 1, - "startLine": 1 - } - } - } - ], - "ruleId": "aws_api_gateway_encrypt_cache" - }, - { - "message": { - "text": "security_policy!=TLS_1_2 was detected" - }, - "level": "note", - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/ilya/Downloads/tf-scanner-main/tests/hcl/applicable/req_sw_terraform_aws_api_gateway_tls_version.tf" - }, - "region": { - "endColumn": 2, - "endLine": 4, - "snippet": { - "text": "vulnerable_example" - }, - "startColumn": 1, - "startLine": 1 - } - } - } - ], - "ruleId": "aws_api_gateway_tls_version" - } - ] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/iac-scan/no-violations.sarif b/xray/commands/testdata/iac-scan/no-violations.sarif deleted file mode 100644 index 0edb478b5..000000000 --- a/xray/commands/testdata/iac-scan/no-violations.sarif +++ /dev/null @@ -1,30 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Terraform scanner", - "rules": [], - "version": "" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "./tf_scanner", - "scan", - "scan.yaml" - ], - "workingDirectory": { - "uri": "file:///Users/ilya/Downloads/tf-scanner-main/src/dist/tf_scanner" - } - } - ], - "results": [ - ] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/MavenWrapperDownloader.java b/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index b901097f2..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/maven-wrapper.jar b/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a55c0cd0092912bf49ae38b3a9e3fd0054..0000000000000000000000000000000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%a^cdh@^wLUlmIv6?_3=BvX8jKk92L=Y}7Jf5OGMfh` zBdR1wFCi-i5@`9km{isRb0O%TX+f~)KNaEz{rXQa89`YIF;EN&gN)cigu6mNh>?Cm zAO&Im2flv6D{jwm+y<%WsPe4!89n~KN|7}Cb{Z;XweER73r}Qp2 zz}WP4j}U0&(uD&9yGy6`!+_v-S(yG*iytsTR#x_Rc>=6u^vnRDnf1gP{#2>`ffrAC% zTZ5WQ@hAK;P;>kX{D)mIXe4%a5p=LO1xXH@8T?mz7Q@d)$3pL{{B!2{-v70L*o1AO+|n5beiw~ zk@(>m?T3{2k2c;NWc^`4@P&Z?BjxXJ@;x1qhn)9Mn*IFdt_J-dIqx5#d`NfyfX~m( zIS~5)MfZ2Uy?_4W`47i}u0ZgPh<{D|w_d#;D}Q&U$Q-G}xM1A@1f{#%A$jh6Qp&0hQ<0bPOM z-{1Wm&p%%#eb_?x7i;bol EfAhh=DF6Tf diff --git a/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/maven-wrapper.properties b/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 642d572ce..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/pom.xml b/xray/commands/testdata/maven-example-with-wrapper/multi1/pom.xml deleted file mode 100644 index e64e9c224..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi1/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - - org.jfrog.test - multi - 3.7-SNAPSHOT - - - multi1 - jar - Multi 1 - - - - apache - none - - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - - - - - org.apache.commons - commons-email - 1.1 - compile - - - org.codehaus.plexus - plexus-utils - 1.5.1 - - - javax.servlet.jsp - jsp-api - 2.1 - compile - - - commons-io - commons-io - 1.4 - - - org.springframework - spring-aop - 2.5.6 - - - - - org.testng - testng - jdk15 - 5.9 - test - - - - diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/src/main/java/artifactory/test/Multi1.java b/xray/commands/testdata/maven-example-with-wrapper/multi1/src/main/java/artifactory/test/Multi1.java deleted file mode 100644 index 8e766e7a1..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi1/src/main/java/artifactory/test/Multi1.java +++ /dev/null @@ -1,10 +0,0 @@ -package artifactory.test; - -/** - * Hello world! - */ -public class Multi1 { - public static void main(String[] args) { - System.out.println("Hello World!"); - } -} diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/src/test/java/artifactory/test/AppTest.java b/xray/commands/testdata/maven-example-with-wrapper/multi1/src/test/java/artifactory/test/AppTest.java deleted file mode 100644 index 442a3650e..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi1/src/test/java/artifactory/test/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package artifactory.test; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/classes/artifactory/test/Multi1.class b/xray/commands/testdata/maven-example-with-wrapper/multi1/target/classes/artifactory/test/Multi1.class deleted file mode 100644 index 5445dc277eff8c487f0a43917469538d23772f4b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 556 zcmZ`$$xZ@65Pi)y3!@+ih%0zP4^B)>JYc+-7!Tu;VDR9n8Cz^Jiy3-M_$)nW;=vE_ zql`6!2_eBgRCT?oe)X#B`{(luz!7#$6tHTbhPsZ1i8VAetZUd{D4fVZs#At+XRptY zI}0BKL&=eWxQhLOh;I47Bc$SlF8BI8l1cmr=G2oMGc+9@Df!4<6-Eq2;5*t!cN@1d<>$3hEjhQ>d#7|Js(*MpI8)g08DjFs@|OTw5EwW)9!+Bc+H zk#@m-nyi{~%)<=Yb5i8d$hFR*iP1)$mXVwcs2n<3gCd(eBcI>@0DDc-CfPy?7Eq+S vH7y{&M3I4Iln6;4AE#u5y&+S{z9TmyFewGEbFr?__1 diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst deleted file mode 100644 index bdb124978..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst +++ /dev/null @@ -1 +0,0 @@ -artifactory/test/Multi1.class diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst deleted file mode 100644 index 0db2a4947..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst +++ /dev/null @@ -1 +0,0 @@ -/Users/sarao/Desktop/project-examples/project-examples/maven-examples/maven-example/multi1/src/main/java/artifactory/test/Multi1.java diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst b/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst deleted file mode 100644 index 9d9d41444..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst +++ /dev/null @@ -1 +0,0 @@ -artifactory/test/AppTest.class diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst b/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst deleted file mode 100644 index c19985a9c..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst +++ /dev/null @@ -1 +0,0 @@ -/Users/sarao/Desktop/project-examples/project-examples/maven-examples/maven-example/multi1/src/test/java/artifactory/test/AppTest.java diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi1/target/test-classes/artifactory/test/AppTest.class b/xray/commands/testdata/maven-example-with-wrapper/multi1/target/test-classes/artifactory/test/AppTest.class deleted file mode 100644 index 2f2f5436fca8ba337314020b7e998af28e2f8fec..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 611 zcmZ`$%}&BV7@RGo)mlXn5D_&RO+XWS&>M!tka%jmKuGkqV8unCWV_Y)R(jHC;sf|l z#&4kqqu9gu*V&obZ$H1@J^-9x+ku6GjWruZ2L{$1q)@W4!C;+=kx+Gpe8uncd+rVR zsOL466r*0P+Ga2t;dQ`}@x>^(h=-j(ws>bildKF}d?@B%vQddFLe*wx%FPhEzqH zbedr-yTQ58#@s~eNOQZeF~_hzi>R6C{O47lExXvn7MYnv(BKj2<$i9iG2l@&S)4;f zAXQ7ogfS~u)i!o$?H0WVC^K!0;yiVAdJ}`Pb#V9s_Dq!lhoXKfAcr*aSfHvfMZv`) zb%e(fG82wvtR!5!#H~N)9mZug^#b#WI$9A$i!xBAn8j*>Kc=jwY4a87-_m<9u|JV^ Or=UcdE=@-a - - 4.0.0 - - org.jfrog.test - multi - 3.7-SNAPSHOT - - - - ${project.parent.version} - - - multi2 - 3.7-SNAPSHOT - jar - Multi 2 - - diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi2/src/main/java/artifactory/test/App.java b/xray/commands/testdata/maven-example-with-wrapper/multi2/src/main/java/artifactory/test/App.java deleted file mode 100644 index 56915fde1..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi2/src/main/java/artifactory/test/App.java +++ /dev/null @@ -1,13 +0,0 @@ -package artifactory.test; - -/** - * Hello world! - * - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi2/src/test/java/artifactory/test/AppTest.java b/xray/commands/testdata/maven-example-with-wrapper/multi2/src/test/java/artifactory/test/AppTest.java deleted file mode 100644 index 442a3650e..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi2/src/test/java/artifactory/test/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package artifactory.test; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi2/target/classes/artifactory/test/App.class b/xray/commands/testdata/maven-example-with-wrapper/multi2/target/classes/artifactory/test/App.class deleted file mode 100644 index aee0f83d72b563f24422acd795189eefc4c42b47..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 547 zcmZuu%SyvQ6g|^d9!6XH@~y3_>cVUU7ZpJSaS>Fg)P<{QI@T#krleD$pQQ^07k+>r zCElb$DKv|F=bm%#nR7EgzhB<~PH||XfU1QW>Lxa9Y+}p6wt*dn!nus3zF^3(d}RsEV0Y9c_QkbKt~W{WB++nSz%;PyU=RBY z&W#8H)p%5K&~F+zaL_=Lp}NcvLuu~ft~V6EUVu8&u@)iy2{j?2HnS|1dry8fxfVR6 zohqruBFtcnlBR%`t+kfziYD^(2FaHJwZo)nQRPx*l=H`*U~egHQ!J#QffYJCvj)nm qR9RRM!tka%jmKuGkqV8unCWV_Y)R(jHC;sf|l z#&4kqqu9gu*V&obZ$H1@J^-9x+ku6GjWruZ2L{$1q)@W4!C;+=kx+Gpe8uncd+rVR zsOL466r*0P+Ga2t;dQ`}@x>^(h=-j(ws>bildKF}d?@B%vQddFLe*wx%FPhEzqH zbedr-yTQ58#@s~eNOQZeF~_hzi>R6C{O47lExXvn7MYnv(BKj2<$i9iG2l@&S)4;f zAXQ7ogfS~u)i!o$?H0WVC^K!0;yiVAdJ}`Pb#V9s_Dq!lhoXKfAcr*aSfHvfMZv`) zb%e(fG82wvtR!5!#H~N)9mZug^#b#WI$9A$i!xBAn8j*>Kc=jwY4a87-_m<9u|JV^ Or=UcdE=@-a - 4.0.0 - - org.jfrog.test - multi - 3.7-SNAPSHOT - - - multi3 - war - Multi 3 - - - - - ${project.groupId} - multi1 - ${project.parent.version} - - - - - - hsqldb - hsqldb - 1.8.0.10 - runtime - - - - - javax.servlet - servlet-api - 2.5 - provided - - - - - - assembly - - - - maven-assembly-plugin - 2.2-beta-5 - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-war-plugin - - - false - - - - - - - - - diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/java/artifactory/test/Multi3.java b/xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/java/artifactory/test/Multi3.java deleted file mode 100644 index 76af503e0..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/java/artifactory/test/Multi3.java +++ /dev/null @@ -1,11 +0,0 @@ -package artifactory.test; - -/** - * Hello world! - */ -public class Multi3 { - public static void main(String[] args) { - new Multi1(); - System.out.println("Hello World!"); - } -} diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/webapp/WEB-INF/web.xml b/xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index f97cbaace..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi3/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - test-webapp - - \ No newline at end of file diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi3/src/test/java/artifactory/test/AppTest.java b/xray/commands/testdata/maven-example-with-wrapper/multi3/src/test/java/artifactory/test/AppTest.java deleted file mode 100644 index 442a3650e..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/multi3/src/test/java/artifactory/test/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package artifactory.test; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/xray/commands/testdata/maven-example-with-wrapper/multi3/target/classes/artifactory/test/Multi3.class b/xray/commands/testdata/maven-example-with-wrapper/multi3/target/classes/artifactory/test/Multi3.class deleted file mode 100644 index 6c6f52ec7b0cb9d9669d6e4b62ff0676eae46eaf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 602 zcmZ`$TT22#6#mBB>biMN?Vff4>!Bs=&FDpl9_#{!5lpa6>LH<^AJC7A z&aQz8HUsC(`OZ1t%y;JN`~4HZ3HEhFk=Ibr5kNkM6|6?Frehr&8a6d-F+@(KE!7!A zuzb*D2-TdfU`W=bEv`m`ws3EG+ae@WcRJi^a#wosFBnpfa>%e+=dO|uyrUd>rx+M)e26nOcZ)1faHGAcCyDvIw4r+{tN(^XN z&WIAZsU+!`H>5|AD!~V&IqP%G!wlM!S7gyJa^*#{KnWUsm$w37oM!tka%jmKuGkqV8unCWV_Y)R(jHC;sf|l z#&4kqqu9gu*V&obZ$H1@J^-9x+ku6GjWruZ2L{$1q)@W4!C;+=kx+Gpe8uncd+rVR zsOL466r*0P+Ga2t;dQ`}@x>^(h=-j(ws>bildKF}d?@B%vQddFLe*wx%FPhEzqH zbedr-yTQ58#@s~eNOQZeF~_hzi>R6C{O47lExXvn7MYnv(BKj2<$i9iG2l@&S)4;f zAXQ7ogfS~u)i!o$?H0WVC^K!0;yiVAdJ}`Pb#V9s_Dq!lhoXKfAcr*aSfHvfMZv`) zb%e(fG82wvtR!5!#H~N)9mZug^#b#WI$9A$i!xBAn8j*>Kc=jwY4a87-_m<9u|JV^ Or=UcdE=@-a \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/xray/commands/testdata/maven-example-with-wrapper/mvnw.cmd b/xray/commands/testdata/maven-example-with-wrapper/mvnw.cmd deleted file mode 100644 index 86115719e..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/xray/commands/testdata/maven-example-with-wrapper/pom.xml b/xray/commands/testdata/maven-example-with-wrapper/pom.xml deleted file mode 100644 index 353f50c99..000000000 --- a/xray/commands/testdata/maven-example-with-wrapper/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - 4.0.0 - org.jfrog.test - multi - 3.7-SNAPSHOT - pom - Simple Multi Modules Build - - - multi1 - multi2 - multi3 - - - - UTF-8 - 1.8 - 1.8 - - - - - junit - junit - 3.8.1 - test - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - false - - - - - - diff --git a/xray/commands/testdata/maven-example/.jfrog/projects/maven.yaml b/xray/commands/testdata/maven-example/.jfrog/projects/maven.yaml deleted file mode 100644 index fda779ec1..000000000 --- a/xray/commands/testdata/maven-example/.jfrog/projects/maven.yaml +++ /dev/null @@ -1,6 +0,0 @@ -version: 1 -type: maven -resolver: - serverId: ci-setup-cmdf - snapshotRepo: mavenmaven - releaseRepo: mavenmaven \ No newline at end of file diff --git a/xray/commands/testdata/maven-example/multi1/pom.xml b/xray/commands/testdata/maven-example/multi1/pom.xml deleted file mode 100644 index 52d9565c0..000000000 --- a/xray/commands/testdata/maven-example/multi1/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - - org.jfrog.test - multi - 3.7-SNAPSHOT - - - multi1 - jar - Multi 1 - - - - apache - none - - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - - - - - org.apache.commons - commons-email - 1.1 - compile - - - commons-io - commons-io - 1.4 - - - - - org.testng - testng - jdk15 - 5.9 - test - - - - diff --git a/xray/commands/testdata/maven-example/multi2/pom.xml b/xray/commands/testdata/maven-example/multi2/pom.xml deleted file mode 100644 index e29f1edaa..000000000 --- a/xray/commands/testdata/maven-example/multi2/pom.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - 4.0.0 - - org.jfrog.test - multi - 3.7-SNAPSHOT - - - - ${project.parent.version} - - - multi2 - 3.7-SNAPSHOT - jar - Multi 2 - - diff --git a/xray/commands/testdata/maven-example/multi3/pom.xml b/xray/commands/testdata/maven-example/multi3/pom.xml deleted file mode 100644 index bfe189bca..000000000 --- a/xray/commands/testdata/maven-example/multi3/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - - org.jfrog.test - multi - 3.7-SNAPSHOT - - - multi3 - war - Multi 3 - - - - - ${project.groupId} - multi1 - ${project.parent.version} - - - - - - hsqldb - hsqldb - 1.8.0.10 - runtime - - - - - javax.servlet - servlet-api - 2.5 - provided - - - - - - assembly - - - - maven-assembly-plugin - 2.2-beta-5 - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.apache.maven.plugins - maven-war-plugin - - - false - - - - - - - - - diff --git a/xray/commands/testdata/maven-example/pom.xml b/xray/commands/testdata/maven-example/pom.xml deleted file mode 100644 index 65d8f37e2..000000000 --- a/xray/commands/testdata/maven-example/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - 4.0.0 - org.jfrog.test - multi - 3.7-SNAPSHOT - pom - Simple Multi Modules Build - - - multi1 - multi2 - multi3 - - - - UTF-8 - 1.8 - 1.8 - - - - - junit - junit - 3.8.1 - test - - - diff --git a/xray/commands/testdata/npm-project/.jfrog/projects/npm.yaml b/xray/commands/testdata/npm-project/.jfrog/projects/npm.yaml deleted file mode 100644 index 0b6274932..000000000 --- a/xray/commands/testdata/npm-project/.jfrog/projects/npm.yaml +++ /dev/null @@ -1,5 +0,0 @@ -version: 1 -type: npm -resolver: - repo: npms - serverId: test \ No newline at end of file diff --git a/xray/commands/testdata/npm-project/package-lock.json b/xray/commands/testdata/npm-project/package-lock.json deleted file mode 100644 index e5ec08086..000000000 --- a/xray/commands/testdata/npm-project/package-lock.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "npm_test2", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "npm_test2", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "lightweight": "^0.1.0", - "underscore": "^1.13.6" - } - }, - "node_modules/lightweight": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/lightweight/-/lightweight-0.1.0.tgz", - "integrity": "sha512-10pYSQA9EJqZZnXDR0urhg8Z0Y1XnRfi41ZFj3ZFTKJ5PjRq82HzT7LKlPyxewy3w2WA2POfi3jQQn7Y53oPcQ==", - "bin": { - "lwt": "bin/lwt.js" - } - }, - "node_modules/underscore": { - "version": "1.13.6", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.6.tgz", - "integrity": "sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A==" - } - } -} \ No newline at end of file diff --git a/xray/commands/testdata/npm-project/package.json b/xray/commands/testdata/npm-project/package.json deleted file mode 100644 index 89229595e..000000000 --- a/xray/commands/testdata/npm-project/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "npm_test", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "dependencies": { - "lightweight": "^0.1.0", - "underscore": "^1.13.6" - } -} \ No newline at end of file diff --git a/xray/commands/testdata/npm-scripts/package.json b/xray/commands/testdata/npm-scripts/package.json deleted file mode 100644 index 44f906f6b..000000000 --- a/xray/commands/testdata/npm-scripts/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "npm-ignore-scripts", - "version": "1.0.0", - "scripts": { - "postinstall": "exit 1" - } -} diff --git a/xray/commands/testdata/npm/dependencies.json b/xray/commands/testdata/npm/dependencies.json deleted file mode 100644 index eadc8ca14..000000000 --- a/xray/commands/testdata/npm/dependencies.json +++ /dev/null @@ -1,447 +0,0 @@ -[ - { - "id": "react-dom:18.2.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "styled-jsx:5.0.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "jose:4.14.4", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "openid-client:5.4.2", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "yallist:4.0.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "lru-cache:6.0.0", - "openid-client:5.4.2", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "lru-cache:6.0.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "openid-client:5.4.2", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "picocolors:1.0.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "postcss:8.4.5", - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "@next/swc-darwin-arm64:12.0.10", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "react:18.2.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "react-dom:18.2.0", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ], - [ - "styled-jsx:5.0.0", - "next:12.0.10", - "npmexmaple:0.1.0" - ], - [ - "use-subscription:1.5.1", - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "uuid:8.3.2", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "oidc-token-hash:5.0.3", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "openid-client:5.4.2", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "pretty-format:3.8.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "preact-render-to-string:5.2.6", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "loose-envify:1.4.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "react-dom:18.2.0", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "scheduler:0.23.0", - "react-dom:18.2.0", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "react:18.2.0", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "@next/env:12.0.10", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "caniuse-lite:1.0.30001486", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "source-map-js:1.0.2", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "postcss:8.4.5", - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "regenerator-runtime:0.13.11", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "@babel/runtime:7.21.5", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "openid-client:5.4.2", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "js-tokens:4.0.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "loose-envify:1.4.0", - "react-dom:18.2.0", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "next-auth:4.22.1", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "next:12.0.10", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "nanoid:3.3.6", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "postcss:8.4.5", - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "@panva/hkdf:1.1.1", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "preact-render-to-string:5.2.6", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "preact:10.13.2", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "preact-render-to-string:5.2.6", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ], - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "scheduler:0.23.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "react-dom:18.2.0", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "postcss:8.4.5", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "use-subscription:1.5.1", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "@babel/runtime:7.21.5", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "cookie:0.5.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "object-assign:4.1.1", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "use-subscription:1.5.1", - "next:12.0.10", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "oauth:0.9.15", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - }, - { - "id": "object-hash:2.2.0", - "scopes": [ - "prod" - ], - "requestedBy": [ - [ - "openid-client:5.4.2", - "next-auth:4.22.1", - "npmexmaple:0.1.0" - ] - ] - } -] diff --git a/xray/commands/testdata/nuget/dependencies.json b/xray/commands/testdata/nuget/dependencies.json deleted file mode 100644 index cc8a07003..000000000 --- a/xray/commands/testdata/nuget/dependencies.json +++ /dev/null @@ -1,194 +0,0 @@ -{ - "modules": [ - { - "type": "nuget", - "id": "MsbuildExample", - "dependencies": [ - { - "id": "popper.js:1.14.0", - "requestedBy": [ - [ - "bootstrap:4.1.1", - "MsbuildExample" - ] - ], - "sha1": "d5d19f07320da701533fa3312ff9a1ab19226a58", - "md5": "ab6c0c4a4115189ec0f98365aa6d5f24" - }, - { - "id": "bootstrap:4.1.1", - "requestedBy": [ - [ - "MsbuildExample" - ] - ], - "sha1": "b7ed3361060a0340f320775fd1683bbd99c69a9e", - "md5": "0985d5cbfe518b73d0c2c6e1d88f3383" - }, - { - "id": "jQuery:3.0.0", - "requestedBy": [ - [ - "bootstrap:4.1.1", - "MsbuildExample" - ] - ], - "sha1": "9e33e5144cf5bf44209bf69eb7afd7055be4d084", - "md5": "396cfda081aa84129e4a250c4011c183" - }, - { - "id": "Microsoft.Bcl:1.1.10", - "requestedBy": [ - [ - "Microsoft.Net.Http:2.2.29", - "MsbuildExample" - ] - ], - "sha1": "70eee9600a89d2056280636105a385a0f4573737", - "md5": "ff7048162a09a686a1515922e28cf75e" - }, - { - "id": "Microsoft.Bcl.Build:1.0.14", - "requestedBy": [ - [ - "Microsoft.Bcl:1.1.10", - "Microsoft.Net.Http:2.2.29", - "MsbuildExample" - ], - [ - "Microsoft.Net.Http:2.2.29", - "MsbuildExample" - ] - ], - "sha1": "b8f2886356d67b2010bf3e5b31980270cba8a501", - "md5": "4589a330c8ca38a950280c276d566ee1" - }, - { - "id": "Microsoft.Net.Http:2.2.29", - "requestedBy": [ - [ - "MsbuildExample" - ] - ], - "sha1": "b4064674a5e08b9cdb8d5fa91b6574c22fe86894", - "md5": "6addd47c57094b7d67d5ebc0bf0b1a6f" - }, - { - "id": "Newtonsoft.Json:11.0.2", - "requestedBy": [ - [ - "MsbuildExample" - ] - ], - "sha1": "5703f14d06c5de46adc5b4699af3a4dacbb84956", - "md5": "cceef905d79cd7cd5d8e22ea68fe7fb6" - }, - { - "id": "NUnit:3.10.1", - "requestedBy": [ - [ - "MsbuildExample" - ] - ], - "sha1": "3023720a81a788cae5996b171be3b352b6e73b26", - "md5": "2060d814f22b1b640952674a4870c89a" - } - ] - }, - { - "type": "nuget", - "id": "MsbuildLibrary", - "dependencies": [ - { - "id": "Microsoft.Bcl.Build:1.0.14", - "requestedBy": [ - [ - "Microsoft.Bcl:1.1.10", - "Microsoft.Net.Http:2.2.29", - "MsbuildLibrary" - ], - [ - "Microsoft.Net.Http:2.2.29", - "MsbuildLibrary" - ] - ], - "sha1": "b8f2886356d67b2010bf3e5b31980270cba8a501", - "md5": "4589a330c8ca38a950280c276d566ee1" - }, - { - "id": "Microsoft.Net.Http:2.2.29", - "requestedBy": [ - [ - "MsbuildLibrary" - ] - ], - "sha1": "b4064674a5e08b9cdb8d5fa91b6574c22fe86894", - "md5": "6addd47c57094b7d67d5ebc0bf0b1a6f" - }, - { - "id": "Newtonsoft.Json:11.0.2", - "requestedBy": [ - [ - "MsbuildLibrary" - ] - ], - "sha1": "5703f14d06c5de46adc5b4699af3a4dacbb84956", - "md5": "cceef905d79cd7cd5d8e22ea68fe7fb6" - }, - { - "id": "NUnit:3.10.1", - "requestedBy": [ - [ - "MsbuildLibrary" - ] - ], - "sha1": "3023720a81a788cae5996b171be3b352b6e73b26", - "md5": "2060d814f22b1b640952674a4870c89a" - }, - { - "id": "popper.js:1.14.0", - "requestedBy": [ - [ - "bootstrap:4.1.1", - "MsbuildLibrary" - ] - ], - "sha1": "d5d19f07320da701533fa3312ff9a1ab19226a58", - "md5": "ab6c0c4a4115189ec0f98365aa6d5f24" - }, - { - "id": "bootstrap:4.1.1", - "requestedBy": [ - [ - "MsbuildLibrary" - ] - ], - "sha1": "b7ed3361060a0340f320775fd1683bbd99c69a9e", - "md5": "0985d5cbfe518b73d0c2c6e1d88f3383" - }, - { - "id": "jQuery:3.0.0", - "requestedBy": [ - [ - "bootstrap:4.1.1", - "MsbuildLibrary" - ] - ], - "sha1": "9e33e5144cf5bf44209bf69eb7afd7055be4d084", - "md5": "396cfda081aa84129e4a250c4011c183" - }, - { - "id": "Microsoft.Bcl:1.1.10", - "requestedBy": [ - [ - "Microsoft.Net.Http:2.2.29", - "MsbuildLibrary" - ] - ], - "sha1": "70eee9600a89d2056280636105a385a0f4573737", - "md5": "ff7048162a09a686a1515922e28cf75e" - } - ] - } - ] -} \ No newline at end of file diff --git a/xray/commands/testdata/nuget/expectedTree.json b/xray/commands/testdata/nuget/expectedTree.json deleted file mode 100644 index f05871fdd..000000000 --- a/xray/commands/testdata/nuget/expectedTree.json +++ /dev/null @@ -1,92 +0,0 @@ -[ - { - "component_id": "nuget://MsbuildExample", - "nodes": [ - { - "component_id": "nuget://bootstrap:4.1.1", - "nodes": [ - { - "component_id": "nuget://popper.js:1.14.0" - }, - { - "component_id": "nuget://jQuery:3.0.0" - } - ] - }, - { - "component_id": "nuget://Microsoft.Net.Http:2.2.29", - "nodes": [ - { - "component_id": "nuget://Microsoft.Bcl:1.1.10", - "nodes": [ - { - "component_id": "nuget://Microsoft.Bcl.Build:1.0.14" - } - ] - } - ] - }, - { - "component_id": "nuget://Newtonsoft.Json:11.0.2" - }, - { - "component_id": "nuget://NUnit:3.10.1" - } - ] - }, - { - "component_id": "nuget://MsbuildLibrary", - "nodes": [ - { - "component_id": "nuget://Microsoft.Net.Http:2.2.29", - "nodes": [ - { - "component_id": "nuget://Microsoft.Bcl:1.1.10", - "nodes": [ - { - "component_id": "nuget://Microsoft.Bcl.Build:1.0.14" - }, - { - "component_id": "nuget://Microsoft.Bcl.Build:1.0.14" - } - ] - }, - { - "component_id": "nuget://Microsoft.Bcl:1.1.10", - "nodes": [ - { - "component_id": "nuget://Microsoft.Bcl.Build:1.0.14" - }, - { - "component_id": "nuget://Microsoft.Bcl.Build:1.0.14" - } - ] - } - ] - }, - { - "component_id": "nuget://Newtonsoft.Json:11.0.2" - }, - { - "component_id": "nuget://NUnit:3.10.1" - }, - { - "component_id": "nuget://bootstrap:4.1.1", - "nodes": [ - { - "component_id": "nuget://popper.js:1.14.0" - }, - { - "component_id": "nuget://jQuery:3.0.0" - }, - { - "component_id": "nuget://popper.js:1.14.0" - }, - { - "component_id": "nuget://jQuery:3.0.0" - } - ] - } - ] - } -] \ No newline at end of file diff --git a/xray/commands/testdata/pip-project/requirementsproject/requirements.txt b/xray/commands/testdata/pip-project/requirementsproject/requirements.txt deleted file mode 100644 index 4210d548a..000000000 --- a/xray/commands/testdata/pip-project/requirementsproject/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -pexpect==4.7.0 \ No newline at end of file diff --git a/xray/commands/testdata/pip-project/setuppyproject/setup.py b/xray/commands/testdata/pip-project/setuppyproject/setup.py deleted file mode 100644 index 84bef86dd..000000000 --- a/xray/commands/testdata/pip-project/setuppyproject/setup.py +++ /dev/null @@ -1,9 +0,0 @@ -from setuptools import setup, find_packages - -setup( - name="pip-example", - version="1.2.3", - install_requires=[ - 'pexpect==4.8.0' - ], -) \ No newline at end of file diff --git a/xray/commands/testdata/pipenv-project/Pipfile b/xray/commands/testdata/pipenv-project/Pipfile deleted file mode 100644 index c5e7b6753..000000000 --- a/xray/commands/testdata/pipenv-project/Pipfile +++ /dev/null @@ -1,13 +0,0 @@ -[[source]] -url = "https://pypi.python.org/simple" -verify_ssl = true -name = "pypi" - -[packages] -toml = "==0.10.2" -pexpect = "==4.8.0" - -[dev-packages] - -[requires] -python_version = "*" diff --git a/xray/commands/testdata/poetry-project/my_poetry_project/__init__.py b/xray/commands/testdata/poetry-project/my_poetry_project/__init__.py deleted file mode 100644 index b794fd409..000000000 --- a/xray/commands/testdata/poetry-project/my_poetry_project/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = '0.1.0' diff --git a/xray/commands/testdata/poetry-project/poetry.lock b/xray/commands/testdata/poetry-project/poetry.lock deleted file mode 100644 index d627e76eb..000000000 --- a/xray/commands/testdata/poetry-project/poetry.lock +++ /dev/null @@ -1,169 +0,0 @@ -# This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand. - -[[package]] -name = "atomicwrites" -version = "1.4.1" -description = "Atomic file writes." -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "atomicwrites-1.4.1.tar.gz", hash = "sha256:81b2c9071a49367a7f770170e5eec8cb66567cfbbc8c73d20ce5ca4a8d71cf11"}, -] - -[[package]] -name = "attrs" -version = "23.1.0" -description = "Classes Without Boilerplate" -optional = false -python-versions = ">=3.7" -files = [ - {file = "attrs-23.1.0-py3-none-any.whl", hash = "sha256:1f28b4522cdc2fb4256ac1a020c78acf9cba2c6b461ccd2c126f3aa8e8335d04"}, - {file = "attrs-23.1.0.tar.gz", hash = "sha256:6279836d581513a26f1bf235f9acd333bc9115683f14f7e8fae46c98fc50e015"}, -] - -[package.extras] -cov = ["attrs[tests]", "coverage[toml] (>=5.3)"] -dev = ["attrs[docs,tests]", "pre-commit"] -docs = ["furo", "myst-parser", "sphinx", "sphinx-notfound-page", "sphinxcontrib-towncrier", "towncrier", "zope-interface"] -tests = ["attrs[tests-no-zope]", "zope-interface"] -tests-no-zope = ["cloudpickle", "hypothesis", "mypy (>=1.1.1)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "pytest-xdist[psutil]"] - -[[package]] -name = "colorama" -version = "0.4.6" -description = "Cross-platform colored terminal text." -optional = false -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" -files = [ - {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, - {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, -] - -[[package]] -name = "more-itertools" -version = "10.1.0" -description = "More routines for operating on iterables, beyond itertools" -optional = false -python-versions = ">=3.8" -files = [ - {file = "more-itertools-10.1.0.tar.gz", hash = "sha256:626c369fa0eb37bac0291bce8259b332fd59ac792fa5497b59837309cd5b114a"}, - {file = "more_itertools-10.1.0-py3-none-any.whl", hash = "sha256:64e0735fcfdc6f3464ea133afe8ea4483b1c5fe3a3d69852e6503b43a0b222e6"}, -] - -[[package]] -name = "numpy" -version = "1.26.1" -description = "Fundamental package for array computing in Python" -optional = false -python-versions = "<3.13,>=3.9" -files = [ - {file = "numpy-1.26.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:82e871307a6331b5f09efda3c22e03c095d957f04bf6bc1804f30048d0e5e7af"}, - {file = "numpy-1.26.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:cdd9ec98f0063d93baeb01aad472a1a0840dee302842a2746a7a8e92968f9575"}, - {file = "numpy-1.26.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d78f269e0c4fd365fc2992c00353e4530d274ba68f15e968d8bc3c69ce5f5244"}, - {file = "numpy-1.26.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8ab9163ca8aeb7fd32fe93866490654d2f7dda4e61bc6297bf72ce07fdc02f67"}, - {file = "numpy-1.26.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:78ca54b2f9daffa5f323f34cdf21e1d9779a54073f0018a3094ab907938331a2"}, - {file = "numpy-1.26.1-cp310-cp310-win32.whl", hash = "sha256:d1cfc92db6af1fd37a7bb58e55c8383b4aa1ba23d012bdbba26b4bcca45ac297"}, - {file = "numpy-1.26.1-cp310-cp310-win_amd64.whl", hash = "sha256:d2984cb6caaf05294b8466966627e80bf6c7afd273279077679cb010acb0e5ab"}, - {file = "numpy-1.26.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cd7837b2b734ca72959a1caf3309457a318c934abef7a43a14bb984e574bbb9a"}, - {file = "numpy-1.26.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1c59c046c31a43310ad0199d6299e59f57a289e22f0f36951ced1c9eac3665b9"}, - {file = "numpy-1.26.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d58e8c51a7cf43090d124d5073bc29ab2755822181fcad978b12e144e5e5a4b3"}, - {file = "numpy-1.26.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6081aed64714a18c72b168a9276095ef9155dd7888b9e74b5987808f0dd0a974"}, - {file = "numpy-1.26.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:97e5d6a9f0702c2863aaabf19f0d1b6c2628fbe476438ce0b5ce06e83085064c"}, - {file = "numpy-1.26.1-cp311-cp311-win32.whl", hash = "sha256:b9d45d1dbb9de84894cc50efece5b09939752a2d75aab3a8b0cef6f3a35ecd6b"}, - {file = "numpy-1.26.1-cp311-cp311-win_amd64.whl", hash = "sha256:3649d566e2fc067597125428db15d60eb42a4e0897fc48d28cb75dc2e0454e53"}, - {file = "numpy-1.26.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:1d1bd82d539607951cac963388534da3b7ea0e18b149a53cf883d8f699178c0f"}, - {file = "numpy-1.26.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:afd5ced4e5a96dac6725daeb5242a35494243f2239244fad10a90ce58b071d24"}, - {file = "numpy-1.26.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a03fb25610ef560a6201ff06df4f8105292ba56e7cdd196ea350d123fc32e24e"}, - {file = "numpy-1.26.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dcfaf015b79d1f9f9c9fd0731a907407dc3e45769262d657d754c3a028586124"}, - {file = "numpy-1.26.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:e509cbc488c735b43b5ffea175235cec24bbc57b227ef1acc691725beb230d1c"}, - {file = "numpy-1.26.1-cp312-cp312-win32.whl", hash = "sha256:af22f3d8e228d84d1c0c44c1fbdeb80f97a15a0abe4f080960393a00db733b66"}, - {file = "numpy-1.26.1-cp312-cp312-win_amd64.whl", hash = "sha256:9f42284ebf91bdf32fafac29d29d4c07e5e9d1af862ea73686581773ef9e73a7"}, - {file = "numpy-1.26.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:bb894accfd16b867d8643fc2ba6c8617c78ba2828051e9a69511644ce86ce83e"}, - {file = "numpy-1.26.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e44ccb93f30c75dfc0c3aa3ce38f33486a75ec9abadabd4e59f114994a9c4617"}, - {file = "numpy-1.26.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9696aa2e35cc41e398a6d42d147cf326f8f9d81befcb399bc1ed7ffea339b64e"}, - {file = "numpy-1.26.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5b411040beead47a228bde3b2241100454a6abde9df139ed087bd73fc0a4908"}, - {file = "numpy-1.26.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:1e11668d6f756ca5ef534b5be8653d16c5352cbb210a5c2a79ff288e937010d5"}, - {file = "numpy-1.26.1-cp39-cp39-win32.whl", hash = "sha256:d1d2c6b7dd618c41e202c59c1413ef9b2c8e8a15f5039e344af64195459e3104"}, - {file = "numpy-1.26.1-cp39-cp39-win_amd64.whl", hash = "sha256:59227c981d43425ca5e5c01094d59eb14e8772ce6975d4b2fc1e106a833d5ae2"}, - {file = "numpy-1.26.1-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:06934e1a22c54636a059215d6da99e23286424f316fddd979f5071093b648668"}, - {file = "numpy-1.26.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76ff661a867d9272cd2a99eed002470f46dbe0943a5ffd140f49be84f68ffc42"}, - {file = "numpy-1.26.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:6965888d65d2848e8768824ca8288db0a81263c1efccec881cb35a0d805fcd2f"}, - {file = "numpy-1.26.1.tar.gz", hash = "sha256:c8c6c72d4a9f831f328efb1312642a1cafafaa88981d9ab76368d50d07d93cbe"}, -] - -[[package]] -name = "packaging" -version = "23.2" -description = "Core utilities for Python packages" -optional = false -python-versions = ">=3.7" -files = [ - {file = "packaging-23.2-py3-none-any.whl", hash = "sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7"}, - {file = "packaging-23.2.tar.gz", hash = "sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5"}, -] - -[[package]] -name = "pluggy" -version = "0.13.1" -description = "plugin and hook calling mechanisms for python" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -files = [ - {file = "pluggy-0.13.1-py2.py3-none-any.whl", hash = "sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d"}, - {file = "pluggy-0.13.1.tar.gz", hash = "sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0"}, -] - -[package.extras] -dev = ["pre-commit", "tox"] - -[[package]] -name = "py" -version = "1.11.0" -description = "library with cross-python path, ini-parsing, io, code, log facilities" -optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -files = [ - {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, - {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, -] - -[[package]] -name = "pytest" -version = "5.4.3" -description = "pytest: simple powerful testing with Python" -optional = false -python-versions = ">=3.5" -files = [ - {file = "pytest-5.4.3-py3-none-any.whl", hash = "sha256:5c0db86b698e8f170ba4582a492248919255fcd4c79b1ee64ace34301fb589a1"}, - {file = "pytest-5.4.3.tar.gz", hash = "sha256:7979331bfcba207414f5e1263b5a0f8f521d0f457318836a7355531ed1a4c7d8"}, -] - -[package.dependencies] -atomicwrites = {version = ">=1.0", markers = "sys_platform == \"win32\""} -attrs = ">=17.4.0" -colorama = {version = "*", markers = "sys_platform == \"win32\""} -more-itertools = ">=4.0.0" -packaging = "*" -pluggy = ">=0.12,<1.0" -py = ">=1.5.0" -wcwidth = "*" - -[package.extras] -checkqa-mypy = ["mypy (==v0.761)"] -testing = ["argcomplete", "hypothesis (>=3.56)", "mock", "nose", "requests", "xmlschema"] - -[[package]] -name = "wcwidth" -version = "0.2.8" -description = "Measures the displayed width of unicode strings in a terminal" -optional = false -python-versions = "*" -files = [ - {file = "wcwidth-0.2.8-py2.py3-none-any.whl", hash = "sha256:77f719e01648ed600dfa5402c347481c0992263b81a027344f3e1ba25493a704"}, - {file = "wcwidth-0.2.8.tar.gz", hash = "sha256:8705c569999ffbb4f6a87c6d1b80f324bd6db952f5eb0b95bc07517f4c1813d4"}, -] - -[metadata] -lock-version = "2.0" -python-versions = ">=3.9,<3.13" -content-hash = "c71b73750693c3c89a13db5fa21920e241d9bd5a5e104e2ead175987c487dc9a" diff --git a/xray/commands/testdata/poetry-project/pyproject.toml b/xray/commands/testdata/poetry-project/pyproject.toml deleted file mode 100644 index d675caf01..000000000 --- a/xray/commands/testdata/poetry-project/pyproject.toml +++ /dev/null @@ -1,16 +0,0 @@ -[tool.poetry] -name = "my-poetry-project" -version = "0.1.0" -description = "" -authors = ["Tal Arian "] - -[tool.poetry.dependencies] -python = ">=3.9,<3.13" -numpy = "^1.26.0" - -[tool.poetry.dev-dependencies] -pytest = "^5.2" - -[build-system] -requires = ["poetry-core>=1.0.0"] -build-backend = "poetry.core.masonry.api" diff --git a/xray/commands/testdata/poetry-project/tests/__init__.py b/xray/commands/testdata/poetry-project/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/xray/commands/testdata/poetry-project/tests/test_my_poetry_project.py b/xray/commands/testdata/poetry-project/tests/test_my_poetry_project.py deleted file mode 100644 index 421e7d392..000000000 --- a/xray/commands/testdata/poetry-project/tests/test_my_poetry_project.py +++ /dev/null @@ -1,5 +0,0 @@ -from my_poetry_project import __version__ - - -def test_version(): - assert __version__ == '0.1.0' diff --git a/xray/commands/testdata/sast-scan/contains-sast-violations.sarif b/xray/commands/testdata/sast-scan/contains-sast-violations.sarif deleted file mode 100644 index d8b3c02e4..000000000 --- a/xray/commands/testdata/sast-scan/contains-sast-violations.sarif +++ /dev/null @@ -1,907 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "USAF", - "rules": [ - { - "id": "python-command-injection", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "78" - } - } - }, - "fullDescription": { - "text": "\nRemote Code Execution is a type of vulnerability that allows an attacker\nto execute arbitrary code on a remote computer or device.\nThis can allow the attacker to gain full control of the target system, potentially\nleading to sensitive information being compromised or unauthorized actions being performed.\n\nIn this query we look for user inputs that can flow directly into execution commands\nin Python. There are many types of Command Injection, so in the future we will make\nfine-tuning changes that will need to apply to this query in the future.\n", - "markdown": "\nRemote Code Execution is a type of vulnerability that allows an attacker\nto execute arbitrary code on a remote computer or device.\nThis can allow the attacker to gain full control of the target system, potentially\nleading to sensitive information being compromised or unauthorized actions being performed.\n\nIn this query we look for user inputs that can flow directly into execution commands\nin Python. There are many types of Command Injection, so in the future we will make\nfine-tuning changes that will need to apply to this query in the future.\n" - }, - "shortDescription": { - "text": "Command Injection" - } - }, - { - "id": "python-flask-debug", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "1295" - } - } - }, - "fullDescription": { - "text": "\n### Overview\nDebug mode in a Flask app is a feature that allows the developer to see detailed\nerror messages and tracebacks when an error occurs. This can be useful for debugging\nand troubleshooting, but it can also create a security vulnerability if the app is\ndeployed in debug mode. In debug mode, Flask will display detailed error messages and\ntracebacks to the user, even if the error is caused by malicious input.\nThis can provide attackers with valuable information about the app's internal workings\nand vulnerabilities, making it easier for them to exploit those vulnerabilities.\n\n### Query operation\nIn this query we look Flask applications that set the `debug` argument to `True`\n\n### Vulnerable example\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello():\n return 'Hello, World!'\n\nif __name__ == '__main__':\n app.run(debug=True)\n```\nIn this example, the Flask application is set to run in debug mode by passing\n`debug=True` as an argument to the `app.run()` function. This will make the application\nemit potentially sensitive information to the users.\n\n### Remediation\nWhen using `app.run`, omit the `debug` flag or set it to `False` -\n```diff\nif __name__ == '__main__':\n- app.run(debug=True)\n+ app.run()\n```\n", - "markdown": "\n### Overview\nDebug mode in a Flask app is a feature that allows the developer to see detailed\nerror messages and tracebacks when an error occurs. This can be useful for debugging\nand troubleshooting, but it can also create a security vulnerability if the app is\ndeployed in debug mode. In debug mode, Flask will display detailed error messages and\ntracebacks to the user, even if the error is caused by malicious input.\nThis can provide attackers with valuable information about the app's internal workings\nand vulnerabilities, making it easier for them to exploit those vulnerabilities.\n\n### Query operation\nIn this query we look Flask applications that set the `debug` argument to `True`\n\n### Vulnerable example\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello():\n return 'Hello, World!'\n\nif __name__ == '__main__':\n app.run(debug=True)\n```\nIn this example, the Flask application is set to run in debug mode by passing\n`debug=True` as an argument to the `app.run()` function. This will make the application\nemit potentially sensitive information to the users.\n\n### Remediation\nWhen using `app.run`, omit the `debug` flag or set it to `False` -\n```diff\nif __name__ == '__main__':\n- app.run(debug=True)\n+ app.run()\n```\n" - }, - "shortDescription": { - "text": "Flask Running in Debug" - } - }, - { - "id": "python-open-redirect", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "601" - } - } - }, - "fullDescription": { - "text": "\n### Overview\nAn open redirect is a type of vulnerability that occurs when a web application or website\nredirects a user to an arbitrary URL, without properly validating the destination URL.\nThis can allow an attacker to redirect a user to a malicious website via a trusted website,\npotentially tricking the user into providing sensitive information or downloading malware.\n\n### Query operation\nIn this query we look for redirections that are affected by any user input.\n\n### Vulnerable example\nIn the following example, the application has a route `/redirect`\nthat takes a query parameter `url` and performs a redirection to that URL\nusing Flask's redirect() function.\n```python\nfrom flask import Flask, request, redirect\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return \"\"\"\n

Welcome to Example App

\n
Click here to visit Google.\n \"\"\"\n\n@app.route('/redirect')\ndef redirect_to_external():\n url = request.args.get('url', '/')\n return redirect(url)\n\nif __name__ == '__main__':\n app.run()\n```\nThe vulnerability lies in the fact that the application does not validate or sanitize the\n`url` parameter, allowing an attacker to redirect users to malicious or unintended websites.\nAn attacker could exploit this vulnerability by modifying the `url` parameter to a different\nsite, such as:\n`http://localhost:5000/redirect?url=https://www.malicious.com`\n\n### Remediation\nBefore redirection, check whether the target URL leads to a trusted domain, for example by\nusing a whitelist -\n```python\ndef is_safe_url(url):\n # Whitelist trusted domains\n trusted_domains = ['https://www.google.com', 'https://www.example.com']\n\n # Check if the provided URL is in the trusted domains\n for domain in trusted_domains:\n if url.startswith(domain):\n return True\n\n return False\n```\n\n```diff\n@app.route('/redirect')\ndef redirect_to_external():\n url = request.args.get('url', '/')\n\n # Validate the URL to ensure it's a trusted destination\n+ if is_safe_url(url):\n+ return redirect(url)\n+ else:\n+ abort(400) # Bad Request\n```\n", - "markdown": "\n### Overview\nAn open redirect is a type of vulnerability that occurs when a web application or website\nredirects a user to an arbitrary URL, without properly validating the destination URL.\nThis can allow an attacker to redirect a user to a malicious website via a trusted website,\npotentially tricking the user into providing sensitive information or downloading malware.\n\n### Query operation\nIn this query we look for redirections that are affected by any user input.\n\n### Vulnerable example\nIn the following example, the application has a route `/redirect`\nthat takes a query parameter `url` and performs a redirection to that URL\nusing Flask's redirect() function.\n```python\nfrom flask import Flask, request, redirect\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return \"\"\"\n

Welcome to Example App

\n Click here to visit Google.\n \"\"\"\n\n@app.route('/redirect')\ndef redirect_to_external():\n url = request.args.get('url', '/')\n return redirect(url)\n\nif __name__ == '__main__':\n app.run()\n```\nThe vulnerability lies in the fact that the application does not validate or sanitize the\n`url` parameter, allowing an attacker to redirect users to malicious or unintended websites.\nAn attacker could exploit this vulnerability by modifying the `url` parameter to a different\nsite, such as:\n`http://localhost:5000/redirect?url=https://www.malicious.com`\n\n### Remediation\nBefore redirection, check whether the target URL leads to a trusted domain, for example by\nusing a whitelist -\n```python\ndef is_safe_url(url):\n # Whitelist trusted domains\n trusted_domains = ['https://www.google.com', 'https://www.example.com']\n\n # Check if the provided URL is in the trusted domains\n for domain in trusted_domains:\n if url.startswith(domain):\n return True\n\n return False\n```\n\n```diff\n@app.route('/redirect')\ndef redirect_to_external():\n url = request.args.get('url', '/')\n\n # Validate the URL to ensure it's a trusted destination\n+ if is_safe_url(url):\n+ return redirect(url)\n+ else:\n+ abort(400) # Bad Request\n```\n" - }, - "shortDescription": { - "text": "Open Redirect" - } - }, - { - "id": "python-parameter-injection", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "74" - } - } - }, - "fullDescription": { - "text": "\nRemote Code Execution is a type of vulnerability that allows an attacker\nto execute arbitrary code on a remote computer or device.\nThis can allow the attacker to gain full control of the target system, potentially\nleading to sensitive information being compromised or unauthorized actions being performed.\n\nIn this query we look for user inputs that can flow directly into execution commands\nin Python. There are many types of Command Injection, so in the future we will make\nfine-tuning changes that will need to apply to this query in the future.\n", - "markdown": "\nRemote Code Execution is a type of vulnerability that allows an attacker\nto execute arbitrary code on a remote computer or device.\nThis can allow the attacker to gain full control of the target system, potentially\nleading to sensitive information being compromised or unauthorized actions being performed.\n\nIn this query we look for user inputs that can flow directly into execution commands\nin Python. There are many types of Command Injection, so in the future we will make\nfine-tuning changes that will need to apply to this query in the future.\n" - }, - "shortDescription": { - "text": "Parameter Injection" - } - }, - { - "id": "python-path-traversal", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "22" - } - } - }, - "fullDescription": { - "text": "\n### Overview\nPath traversal, also known as directory traversal, is a type of vulnerability that allows an\nattacker to access files or directories on a computer or device that are outside of\nthe intended directory.\nAllowing arbitrary read access can allow the attacker to read sensitive files, such as\nconfiguration files or sensitive data, potentially leading data loss\nor even system compromise.\nAllowing arbitrary write access is more severe and in most cases leads to arbitrary code\nexecution, via editing important system files or sensitive data.\n\n### Query operation\nIn this query we look for user input that can flow un-sanitized as a path into file access\nfunctions\n(either read or write access)\n\n### Vulnerable example\n```python\nfrom flask import Flask, request, send_file\napp = Flask(__name__)\n\n@app.route('/files/')\ndef serve_file():\n filename = request.args.get('filename')\n basepath = 'static/files/'\n return send_file(basepath + filename)\n\nif __name__ == '__main__':\n app.run()\n```\nIn this example, the application has a route `/files/` that serves files from a directory\ncalled `static/files`. The vulnerability lies in the fact that the application does not\nproperly validate or sanitize the `filename` parameter, allowing an attacker to traverse\nbeyond the intended directory and access sensitive files on the server.\nAn attacker could exploit this vulnerability by manipulating the `filename` parameter\nand providing a relative path to access files outside of the `static/files` directory.\nFor example, they could craft a URL like this:\n`http://localhost:5000/files/?filename=../../../etc/passwd`\n\n### Remediation\nWhen possible, use inherently safe path functions such as `send_from_directory` that perform\nfilename escaping -\n```diff\n@app.route('/files/')\ndef serve_file():\n filename = request.args.get('filename')\n basepath = 'static/files/'\n- return send_file(basepath + filename)\n+ return send_from_directory(basepath, filename)\n```\nAlternatively, before accessing a potential path, check that the user's `filename` does not\nescape the intended path -\n```python\nfrom pathlib import Path\ndef is_escaping_path(basepath, userpath):\n try:\n Path(basepath).joinpath(userpath).resolve().relative_to(basepath.resolve())\n return False\n except ValueError:\n return True\n```\n\n```diff\n@app.route('/files/')\ndef serve_file():\n filename = request.args.get('filename')\n basepath = 'static/files/'\n+ if is_escaping_path(basepath, filename):\n+ abort(400) # Bad Request\n return send_file(basepath + filename)\n```\nAlternatively - use inherently safe\n", - "markdown": "\n### Overview\nPath traversal, also known as directory traversal, is a type of vulnerability that allows an\nattacker to access files or directories on a computer or device that are outside of\nthe intended directory.\nAllowing arbitrary read access can allow the attacker to read sensitive files, such as\nconfiguration files or sensitive data, potentially leading data loss\nor even system compromise.\nAllowing arbitrary write access is more severe and in most cases leads to arbitrary code\nexecution, via editing important system files or sensitive data.\n\n### Query operation\nIn this query we look for user input that can flow un-sanitized as a path into file access\nfunctions\n(either read or write access)\n\n### Vulnerable example\n```python\nfrom flask import Flask, request, send_file\napp = Flask(__name__)\n\n@app.route('/files/')\ndef serve_file():\n filename = request.args.get('filename')\n basepath = 'static/files/'\n return send_file(basepath + filename)\n\nif __name__ == '__main__':\n app.run()\n```\nIn this example, the application has a route `/files/` that serves files from a directory\ncalled `static/files`. The vulnerability lies in the fact that the application does not\nproperly validate or sanitize the `filename` parameter, allowing an attacker to traverse\nbeyond the intended directory and access sensitive files on the server.\nAn attacker could exploit this vulnerability by manipulating the `filename` parameter\nand providing a relative path to access files outside of the `static/files` directory.\nFor example, they could craft a URL like this:\n`http://localhost:5000/files/?filename=../../../etc/passwd`\n\n### Remediation\nWhen possible, use inherently safe path functions such as `send_from_directory` that perform\nfilename escaping -\n```diff\n@app.route('/files/')\ndef serve_file():\n filename = request.args.get('filename')\n basepath = 'static/files/'\n- return send_file(basepath + filename)\n+ return send_from_directory(basepath, filename)\n```\nAlternatively, before accessing a potential path, check that the user's `filename` does not\nescape the intended path -\n```python\nfrom pathlib import Path\ndef is_escaping_path(basepath, userpath):\n try:\n Path(basepath).joinpath(userpath).resolve().relative_to(basepath.resolve())\n return False\n except ValueError:\n return True\n```\n\n```diff\n@app.route('/files/')\ndef serve_file():\n filename = request.args.get('filename')\n basepath = 'static/files/'\n+ if is_escaping_path(basepath, filename):\n+ abort(400) # Bad Request\n return send_file(basepath + filename)\n```\nAlternatively - use inherently safe\n" - }, - "shortDescription": { - "text": "Path Traversal" - } - }, - { - "id": "python-sqli", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "89" - } - } - }, - "fullDescription": { - "text": "\n### Overview\nSQL injection is a type of vulnerability that allows an attacker to execute arbitrary SQL\ncommands on a database.\nThis can allow the attacker to gain access to sensitive information,\nsuch as user credentials or sensitive data, or to perform unauthorized actions,\nsuch as deleting or modifying data.\n\n### Query operation\nIn this query we check if a user input can flow un-sanitized into an SQL query.\n\n### Vulnerable example\n```python\nfrom flask import Flask, request\nimport sqlite3\n\napp = Flask(__name__)\n\n@app.route('/login', methods=['POST'])\ndef login():\n username = request.form.get('username')\n password = request.form.get('password')\n\n # Vulnerable SQL query\n query = f\"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'\"\n\n # Execute the query\n conn = sqlite3.connect('database.db')\n cursor = conn.cursor()\n cursor.execute(query)\n user = cursor.fetchone()\n conn.close()\n\n if user:\n return 'Login successful'\n else:\n return 'Login failed'\n\nif __name__ == '__main__':\n app.run()\n```\nIn this example, the application accepts a `username` and `password` from a login form via a\nPOST request. The SQL query is constructed using string concatenation, which makes it\nvulnerable to SQL injection attacks.\n\nAn attacker can exploit this vulnerability by entering `' OR 1=1 --` as the `username`.\nThe resulting query would become -\n```sql\nSELECT * FROM users WHERE username = '' OR 1=1 --' AND password = ''\n```\nwhich will always evaluate to TRUE, leading to an authentication bypass\nsince the attacker has no valid credentials.\n\n### Remediation\nReplace the vulnerable string concatenation with a parameterized query\nusing `?` placeholders -\n```diff\n@app.route('/login', methods=['POST'])\n def login():\n username = request.form.get('username')\n password = request.form.get('password')\n\n # Vulnerable SQL query\n- query = f\"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'\"\n+ query = \"SELECT * FROM users WHERE username = ? AND password = ?\"\n\n # Execute the query\n conn = sqlite3.connect('database.db')\n cursor = conn.cursor()\n- cursor.execute(query)\n+ cursor.execute(query, (username, password))\n user = cursor.fetchone()\n conn.close()\n\n if user:\n return 'Login successful'\n else:\n return 'Login failed'\n```\n", - "markdown": "\n### Overview\nSQL injection is a type of vulnerability that allows an attacker to execute arbitrary SQL\ncommands on a database.\nThis can allow the attacker to gain access to sensitive information,\nsuch as user credentials or sensitive data, or to perform unauthorized actions,\nsuch as deleting or modifying data.\n\n### Query operation\nIn this query we check if a user input can flow un-sanitized into an SQL query.\n\n### Vulnerable example\n```python\nfrom flask import Flask, request\nimport sqlite3\n\napp = Flask(__name__)\n\n@app.route('/login', methods=['POST'])\ndef login():\n username = request.form.get('username')\n password = request.form.get('password')\n\n # Vulnerable SQL query\n query = f\"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'\"\n\n # Execute the query\n conn = sqlite3.connect('database.db')\n cursor = conn.cursor()\n cursor.execute(query)\n user = cursor.fetchone()\n conn.close()\n\n if user:\n return 'Login successful'\n else:\n return 'Login failed'\n\nif __name__ == '__main__':\n app.run()\n```\nIn this example, the application accepts a `username` and `password` from a login form via a\nPOST request. The SQL query is constructed using string concatenation, which makes it\nvulnerable to SQL injection attacks.\n\nAn attacker can exploit this vulnerability by entering `' OR 1=1 --` as the `username`.\nThe resulting query would become -\n```sql\nSELECT * FROM users WHERE username = '' OR 1=1 --' AND password = ''\n```\nwhich will always evaluate to TRUE, leading to an authentication bypass\nsince the attacker has no valid credentials.\n\n### Remediation\nReplace the vulnerable string concatenation with a parameterized query\nusing `?` placeholders -\n```diff\n@app.route('/login', methods=['POST'])\n def login():\n username = request.form.get('username')\n password = request.form.get('password')\n\n # Vulnerable SQL query\n- query = f\"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'\"\n+ query = \"SELECT * FROM users WHERE username = ? AND password = ?\"\n\n # Execute the query\n conn = sqlite3.connect('database.db')\n cursor = conn.cursor()\n- cursor.execute(query)\n+ cursor.execute(query, (username, password))\n user = cursor.fetchone()\n conn.close()\n\n if user:\n return 'Login successful'\n else:\n return 'Login failed'\n```\n" - }, - "shortDescription": { - "text": "SQL Injection" - } - }, - { - "id": "python-stack-trace-exposure", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "209" - } - } - }, - "fullDescription": { - "text": "\n### Overview\nStack trace exposure is a type of security vulnerability that occurs when a program reveals\nsensitive information, such as the names and locations of internal files and variables,\nin error messages or other diagnostic output. This can happen when a program crashes or\nencounters an error, and the stack trace (a record of the program's call stack at the time\nof the error) is included in the output. Stack trace exposure can provide attackers with\nvaluable information about a program's internal workings and vulnerabilities, making it\neasier for them to exploit those vulnerabilities and gain unauthorized access\nto the system.\n\n### Query operation\nIn this query we look for any stack trace information flowing into the output.\n\n### Vulnerable example\n```python\nimport traceback\n\ndef my_function():\n try:\n # Some code that may raise an exception\n raise ValueError('Something went wrong')\n except ValueError as e:\n traceback.print_tb(e.__traceback__)\n\nmy_function()\n```\nIn this example, the `my_function()` function intentionally raises\na `ValueError` exception.\nThe `traceback.print_tb()` function is then used to print the stack trace\nwhen the exception is caught. The vulnerability lies in using `traceback.print_tb()`\nto output the stack trace directly to the console or any other output stream.\nIf this code were part of a web application or exposed through an API,\nthe stack trace would be exposed in the server logs or potentially returned\nas part of an error response to the client.\n\n### Remediation\nLog the exception to a logging framework or file, instead of outputting directly to the\nconsole-\n\n```python\ndef log_exception(exception):\n logging.exception('An exception occurred', exc_info=exception)\n```\n\n```diff\ndef my_function():\n try:\n # Some code that may raise an exception\n raise ValueError('Something went wrong')\n except ValueError as e:\n- traceback.print_tb(e.__traceback__)\n+ log_exception(e)\n```\n", - "markdown": "\n### Overview\nStack trace exposure is a type of security vulnerability that occurs when a program reveals\nsensitive information, such as the names and locations of internal files and variables,\nin error messages or other diagnostic output. This can happen when a program crashes or\nencounters an error, and the stack trace (a record of the program's call stack at the time\nof the error) is included in the output. Stack trace exposure can provide attackers with\nvaluable information about a program's internal workings and vulnerabilities, making it\neasier for them to exploit those vulnerabilities and gain unauthorized access\nto the system.\n\n### Query operation\nIn this query we look for any stack trace information flowing into the output.\n\n### Vulnerable example\n```python\nimport traceback\n\ndef my_function():\n try:\n # Some code that may raise an exception\n raise ValueError('Something went wrong')\n except ValueError as e:\n traceback.print_tb(e.__traceback__)\n\nmy_function()\n```\nIn this example, the `my_function()` function intentionally raises\na `ValueError` exception.\nThe `traceback.print_tb()` function is then used to print the stack trace\nwhen the exception is caught. The vulnerability lies in using `traceback.print_tb()`\nto output the stack trace directly to the console or any other output stream.\nIf this code were part of a web application or exposed through an API,\nthe stack trace would be exposed in the server logs or potentially returned\nas part of an error response to the client.\n\n### Remediation\nLog the exception to a logging framework or file, instead of outputting directly to the\nconsole-\n\n```python\ndef log_exception(exception):\n logging.exception('An exception occurred', exc_info=exception)\n```\n\n```diff\ndef my_function():\n try:\n # Some code that may raise an exception\n raise ValueError('Something went wrong')\n except ValueError as e:\n- traceback.print_tb(e.__traceback__)\n+ log_exception(e)\n```\n" - }, - "shortDescription": { - "text": "Stack Trace Exposure" - } - }, - { - "id": "python-unsafe-deserialization", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "502" - } - } - }, - "fullDescription": { - "text": "\n### Overview\nUnsafe deserialization is a security vulnerability that occurs when a program deserializes\nuntrusted data with a potentially dangerous deserializer.\nDeserialization is the process of converting serialized data (data that\nhas been converted into a format that can be easily transmitted or stored) back into its\noriginal form. In some (\"unsafe\") serialization protocols, if an attacker is able to\nmanipulate the serialized data, they may be able to execute arbitrary code or perform other\nmalicious actions when the data is deserialized.\n\n### Query operation\nIn this query we look for user input that can flow un-sanitized to potentially unsafe\ndeserialization methods\n\n### Vulnerable example\n```python\nimport yaml\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\n@app.route('/process', methods=['POST'])\ndef process():\n data = request.get_data()\n\n # Vulnerable deserialization\n obj = yaml.load(data)\n\n # Process the deserialized object (for simplicity, we're just printing it)\n print(obj)\n\n return 'Data processed'\n\nif __name__ == '__main__':\n app.run()\n```\nIn this example, the application exposes a `/process` endpoint that accepts data via a POST\nrequest. The vulnerable code uses the `yaml.load()` function\nto deserialize the received data.\nThe vulnerability lies in the fact that the `yaml` module can execute arbitrary code\nduring the deserialization process.\nAn attacker can exploit this by crafting a malicious payload\nthat executes arbitrary code when the `yaml.load()` function is called.\n\n### Remediation\nUse deserialization routines that are known to handle untrusted data securely, such as\n`yaml.safe_load`. It is highly recommended to use the `json` module for serialization, as it\ndeserializes untrusted data securely.\n\n```diff\n@app.route('/process', methods=['POST'])\ndef process():\n data = request.get_data()\n\n # Safe deserialization\n- obj = yaml.load(data)\n+ obj = yaml.safe_load(data)\n\n # Process the deserialized object (for simplicity, we're just printing it)\n print(obj)\n\n return 'Data processed'\n```\n", - "markdown": "\n### Overview\nUnsafe deserialization is a security vulnerability that occurs when a program deserializes\nuntrusted data with a potentially dangerous deserializer.\nDeserialization is the process of converting serialized data (data that\nhas been converted into a format that can be easily transmitted or stored) back into its\noriginal form. In some (\"unsafe\") serialization protocols, if an attacker is able to\nmanipulate the serialized data, they may be able to execute arbitrary code or perform other\nmalicious actions when the data is deserialized.\n\n### Query operation\nIn this query we look for user input that can flow un-sanitized to potentially unsafe\ndeserialization methods\n\n### Vulnerable example\n```python\nimport yaml\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\n@app.route('/process', methods=['POST'])\ndef process():\n data = request.get_data()\n\n # Vulnerable deserialization\n obj = yaml.load(data)\n\n # Process the deserialized object (for simplicity, we're just printing it)\n print(obj)\n\n return 'Data processed'\n\nif __name__ == '__main__':\n app.run()\n```\nIn this example, the application exposes a `/process` endpoint that accepts data via a POST\nrequest. The vulnerable code uses the `yaml.load()` function\nto deserialize the received data.\nThe vulnerability lies in the fact that the `yaml` module can execute arbitrary code\nduring the deserialization process.\nAn attacker can exploit this by crafting a malicious payload\nthat executes arbitrary code when the `yaml.load()` function is called.\n\n### Remediation\nUse deserialization routines that are known to handle untrusted data securely, such as\n`yaml.safe_load`. It is highly recommended to use the `json` module for serialization, as it\ndeserializes untrusted data securely.\n\n```diff\n@app.route('/process', methods=['POST'])\ndef process():\n data = request.get_data()\n\n # Safe deserialization\n- obj = yaml.load(data)\n+ obj = yaml.safe_load(data)\n\n # Process the deserialized object (for simplicity, we're just printing it)\n print(obj)\n\n return 'Data processed'\n```\n" - }, - "shortDescription": { - "text": "Unsafe Deserialization" - } - }, - { - "id": "python-xss", - "defaultConfiguration": { - "parameters": { - "properties": { - "CWE": "79" - } - } - }, - "fullDescription": { - "text": "\n### Overview\nXSS, or Cross-Site Scripting, is a type of vulnerability that allows an attacker to\ninject malicious code into a website or web application.\nThis can allow the attacker to steal sensitive information from users, such as their\ncookies or login credentials, or to perform unauthorized actions on their behalf.\n\n### Query operation\nIn the query we look for any user input that flows into\na potential output of the application.\n\n### Vulnerable example\nIn the following example, the Flask application takes a user-supplied parameter (`name`)\nfrom the query string and renders it directly into an HTML template using the\n`render_template_string` function. The issue is that\nthe user input is not properly sanitized or escaped, making it vulnerable to XSS attacks.\n```python\nfrom flask import Flask, request, render_template_string\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n name = request.args.get('name', 'Guest')\n message = f'Hello, {name}!'\n return render_template_string('

{}

'.format(message))\n\nif __name__ == '__main__':\napp.run()\n```\nAn attacker can exploit this vulnerability by injecting malicious JavaScript code into the\n`name` parameter. For instance, they could modify the URL to include the following payload:\n`http://localhost:5000/?name=`\n\n### Remediation\nWhen rendering templates, use parametrized variable assignments (which are automatically\nescaped) instead of direct string manipulation -\n```diff\n@app.route('/')\ndef index():\n name = request.args.get('name', 'Guest')\n message = f'Hello, {name}!'\n- return render_template_string('

{}

'.format(message))\n+ return render_template_string('

{{ message }}

', message=message)\n```\n", - "markdown": "\n### Overview\nXSS, or Cross-Site Scripting, is a type of vulnerability that allows an attacker to\ninject malicious code into a website or web application.\nThis can allow the attacker to steal sensitive information from users, such as their\ncookies or login credentials, or to perform unauthorized actions on their behalf.\n\n### Query operation\nIn the query we look for any user input that flows into\na potential output of the application.\n\n### Vulnerable example\nIn the following example, the Flask application takes a user-supplied parameter (`name`)\nfrom the query string and renders it directly into an HTML template using the\n`render_template_string` function. The issue is that\nthe user input is not properly sanitized or escaped, making it vulnerable to XSS attacks.\n```python\nfrom flask import Flask, request, render_template_string\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n name = request.args.get('name', 'Guest')\n message = f'Hello, {name}!'\n return render_template_string('

{}

'.format(message))\n\nif __name__ == '__main__':\napp.run()\n```\nAn attacker can exploit this vulnerability by injecting malicious JavaScript code into the\n`name` parameter. For instance, they could modify the URL to include the following payload:\n`http://localhost:5000/?name=`\n\n### Remediation\nWhen rendering templates, use parametrized variable assignments (which are automatically\nescaped) instead of direct string manipulation -\n```diff\n@app.route('/')\ndef index():\n name = request.args.get('name', 'Guest')\n message = f'Hello, {name}!'\n- return render_template_string('

{}

'.format(message))\n+ return render_template_string('

{{ message }}

', message=message)\n```\n" - }, - "shortDescription": { - "text": "XSS Vulnerability" - } - } - ] - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "/Users/assafa/.jfrog/dependencies/analyzerManager/zd_scanner/scanner", - "scan", - "/var/folders/xv/th4cksxn7jv9wjrdnn1h4tj00000gq/T/jfrog.cli.temp.-1693477603-3697552683/results.sarif" - ], - "workingDirectory": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat" - } - } - ], - "results": [ - { - "message": { - "text": "SQL Injection" - }, - "codeFlows": [ - { - "threadFlows": [ - { - "locations": [ - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 28, - "endLine": 9, - "snippet": { - "text": "request.form" - }, - "startColumn": 16, - "startLine": 9 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 32, - "endLine": 9, - "snippet": { - "text": "request.form.get" - }, - "startColumn": 16, - "startLine": 9 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 44, - "endLine": 9, - "snippet": { - "text": "request.form.get(\"username\")" - }, - "startColumn": 16, - "startLine": 9 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 13, - "endLine": 9, - "snippet": { - "text": "username" - }, - "startColumn": 5, - "startLine": 9 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 31, - "endLine": 20, - "snippet": { - "text": "(username, password)" - }, - "startColumn": 11, - "startLine": 20 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 31, - "endLine": 20, - "snippet": { - "text": "\"SELECT id, username, access_level FROM user WHERE username = '%s' AND password = '%s'\"\n % (username, password)" - }, - "startColumn": 9, - "startLine": 19 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 10, - "endLine": 18, - "snippet": { - "text": "query" - }, - "startColumn": 5, - "startLine": 18 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 39, - "endLine": 22, - "snippet": { - "text": "query_db(query, [], True)" - }, - "startColumn": 14, - "startLine": 22 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.__init__.query_db" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/__init__.py" - }, - "region": { - "endColumn": 19, - "endLine": 10, - "snippet": { - "text": "query" - }, - "startColumn": 14, - "startLine": 10 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.__init__.query_db" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/__init__.py" - }, - "region": { - "endColumn": 49, - "endLine": 14, - "snippet": { - "text": "conn.cursor().execute(query, args)" - }, - "startColumn": 15, - "startLine": 14 - } - } - } - } - ] - } - ] - } - ], - "level": "error", - "locations": [ - { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.__init__.query_db" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/__init__.py" - }, - "region": { - "endColumn": 49, - "endLine": 14, - "snippet": { - "text": "conn.cursor().execute(query, args)" - }, - "startColumn": 15, - "startLine": 14 - } - } - } - ], - "ruleId": "python-sqli" - }, - { - "message": { - "text": "SQL Injection" - }, - "codeFlows": [ - { - "threadFlows": [ - { - "locations": [ - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 28, - "endLine": 10, - "snippet": { - "text": "request.form" - }, - "startColumn": 16, - "startLine": 10 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 32, - "endLine": 10, - "snippet": { - "text": "request.form.get" - }, - "startColumn": 16, - "startLine": 10 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 44, - "endLine": 10, - "snippet": { - "text": "request.form.get(\"password\")" - }, - "startColumn": 16, - "startLine": 10 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 13, - "endLine": 10, - "snippet": { - "text": "password" - }, - "startColumn": 5, - "startLine": 10 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 31, - "endLine": 20, - "snippet": { - "text": "(username, password)" - }, - "startColumn": 11, - "startLine": 20 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 31, - "endLine": 20, - "snippet": { - "text": "\"SELECT id, username, access_level FROM user WHERE username = '%s' AND password = '%s'\"\n % (username, password)" - }, - "startColumn": 9, - "startLine": 19 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 10, - "endLine": 18, - "snippet": { - "text": "query" - }, - "startColumn": 5, - "startLine": 18 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 39, - "endLine": 22, - "snippet": { - "text": "query_db(query, [], True)" - }, - "startColumn": 14, - "startLine": 22 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.__init__.query_db" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/__init__.py" - }, - "region": { - "endColumn": 19, - "endLine": 10, - "snippet": { - "text": "query" - }, - "startColumn": 14, - "startLine": 10 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.__init__.query_db" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/__init__.py" - }, - "region": { - "endColumn": 49, - "endLine": 14, - "snippet": { - "text": "conn.cursor().execute(query, args)" - }, - "startColumn": 15, - "startLine": 14 - } - } - } - } - ] - } - ] - } - ], - "level": "error", - "locations": [ - { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.__init__.query_db" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/__init__.py" - }, - "region": { - "endColumn": 49, - "endLine": 14, - "snippet": { - "text": "conn.cursor().execute(query, args)" - }, - "startColumn": 15, - "startLine": 14 - } - } - } - ], - "ruleId": "python-sqli" - }, - { - "message": { - "text": "Open Redirect" - }, - "codeFlows": [ - { - "threadFlows": [ - { - "locations": [ - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login_and_redirect" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 23, - "endLine": 33, - "snippet": { - "text": "request.args" - }, - "startColumn": 11, - "startLine": 33 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login_and_redirect" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 27, - "endLine": 33, - "snippet": { - "text": "request.args.get" - }, - "startColumn": 11, - "startLine": 33 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login_and_redirect" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 34, - "endLine": 33, - "snippet": { - "text": "request.args.get(\"url\")" - }, - "startColumn": 11, - "startLine": 33 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login_and_redirect" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 8, - "endLine": 33, - "snippet": { - "text": "url" - }, - "startColumn": 5, - "startLine": 33 - } - } - } - }, - { - "location": { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login_and_redirect" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 29, - "endLine": 46, - "snippet": { - "text": "redirect(url)" - }, - "startColumn": 16, - "startLine": 46 - } - } - } - } - ] - } - ] - } - ], - "level": "note", - "locations": [ - { - "logicalLocations": [ - { - "fullyQualifiedName": "flask_webgoat.auth.login_and_redirect" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/flask_webgoat/auth.py" - }, - "region": { - "endColumn": 29, - "endLine": 46, - "snippet": { - "text": "redirect(url)" - }, - "startColumn": 16, - "startLine": 46 - } - } - } - ], - "ruleId": "python-open-redirect" - }, - { - "message": { - "text": "Flask Running in Debug" - }, - "locations": [ - { - "logicalLocations": [ - { - "fullyQualifiedName": "run" - } - ], - "physicalLocation": { - "artifactLocation": { - "uri": "file:///Users/assafa/Documents/code/flask-webgoat/run.py" - }, - "region": { - "endColumn": 24, - "endLine": 15, - "snippet": { - "text": "app.run(debug=True)" - }, - "startColumn": 5, - "startLine": 15 - } - } - } - ], - "ruleId": "python-flask-debug" - } - ] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/sast-scan/no-violations.sarif b/xray/commands/testdata/sast-scan/no-violations.sarif deleted file mode 100644 index ed129e6e0..000000000 --- a/xray/commands/testdata/sast-scan/no-violations.sarif +++ /dev/null @@ -1,28 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "USAF", - "rules": [] - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "/Users/assafa/.jfrog/dependencies/analyzerManager/zd_scanner/scanner", - "scan", - "/var/folders/xv/th4cksxn7jv9wjrdnn1h4tj00000gq/T/jfrog.cli.temp.-1693477603-3697552683/results.sarif" - ], - "workingDirectory": { - "uri": "file:///Users/assafa/Documents/code/terraform" - } - } - ], - "results": [] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/secrets-scan/contain-secrets.sarif b/xray/commands/testdata/secrets-scan/contain-secrets.sarif deleted file mode 100644 index af3f378eb..000000000 --- a/xray/commands/testdata/secrets-scan/contain-secrets.sarif +++ /dev/null @@ -1,234 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Terraform scanner", - "rules": [ - { - "id": "entropy", - "shortDescription": { - "text": "Scanner for entropy" - } - } - ], - "version": "" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "./secrets_scanner", - "scan", - "sec_config_example.yaml" - ], - "workingDirectory": { - "uri": "secrets_scanner" - } - } - ], - "results": [ - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.nodejs.hardcoded-secrets/applicable_base64.js" - }, - "region": { - "endColumn": 118, - "endLine": 1, - "snippet": { - "text": "2VTHzn1mKZ/n9apD5P6nxsajSQh8QhmyyKvUIRoZWAHCB8lSbBm3YWx5nOdZ1zPEOaA0zIZy1eFgHgfB2HkfAdVrbQj19kagXDVe" - }, - "startColumn": 18, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy" - }, - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.nodejs.hardcoded-secrets/applicable_base64.js.approval.json" - }, - "region": { - "endColumn": 195, - "endLine": 1, - "snippet": { - "text": "2VTHzn1mKZ/n9apD5P6nxsajSQh8QhmyyKvUIRoZWAHCB8lSbBm3YWx5nOdZ1zPEOaA0zIZy1eFgHgfB2HkfAdVrbQj19kagXDVe" - }, - "startColumn": 95, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy" - }, - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.nodejs.hardcoded-secrets/applicable_hex.js" - }, - "region": { - "endColumn": 138, - "endLine": 1, - "snippet": { - "text": "0159392e31dc912156e1cc6eab32a3d7df7154aecdf2ffe7d66f10da0d5706f7d9ba3183a366389112819b728b20026d04a4f6304da649beefc7fe49" - }, - "startColumn": 18, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy" - }, - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.nodejs.hardcoded-secrets/applicable_hex.js.approval.json" - }, - "region": { - "endColumn": 215, - "endLine": 1, - "snippet": { - "text": "0159392e31dc912156e1cc6eab32a3d7df7154aecdf2ffe7d66f10da0d5706f7d9ba3183a366389112819b728b20026d04a4f6304da649beefc7fe49" - }, - "startColumn": 95, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy" - }, - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.python.hardcoded-secrets/applicable_base64.py" - }, - "region": { - "endColumn": 112, - "endLine": 1, - "snippet": { - "text": "2VTHzn1mKZ/n9apD5P6nxsajSQh8QhmyyKvUIRoZWAHCB8lSbBm3YWx5nOdZ1zPEOaA0zIZy1eFgHgfB2HkfAdVrbQj19kagXDVe" - }, - "startColumn": 12, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy" - }, - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.python.hardcoded-secrets/applicable_base64.py.approval.json" - }, - "region": { - "endColumn": 191, - "endLine": 1, - "snippet": { - "text": "2VTHzn1mKZ/n9apD5P6nxsajSQh8QhmyyKvUIRoZWAHCB8lSbBm3YWx5nOdZ1zPEOaA0zIZy1eFgHgfB2HkfAdVrbQj19kagXDVe" - }, - "startColumn": 91, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy" - }, - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.python.hardcoded-secrets/applicable_hex.py" - }, - "region": { - "endColumn": 132, - "endLine": 1, - "snippet": { - "text": "0159392e31dc912156e1cc6eab32a3d7df7154aecdf2ffe7d66f10da0d5706f7d9ba3183a366389112819b728b20026d04a4f6304da649beefc7fe49" - }, - "startColumn": 12, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy" - }, - { - "message": { - "text": "Hardcoded secrets were found in source files" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "file://secrets_scanner/tests/req.python.hardcoded-secrets/applicable_hex.py.approval.json" - }, - "region": { - "endColumn": 211, - "endLine": 1, - "snippet": { - "text": "0159392e31dc912156e1cc6eab32a3d7df7154aecdf2ffe7d66f10da0d5706f7d9ba3183a366389112819b728b20026d04a4f6304da649beefc7fe49" - }, - "startColumn": 91, - "startLine": 1 - } - } - } - ], - "ruleId": "entropy", - "suppressions": [ - { - "kind": "inSource" - } - ] - } - ] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/secrets-scan/no-secrets.sarif b/xray/commands/testdata/secrets-scan/no-secrets.sarif deleted file mode 100644 index 8b0ae50d4..000000000 --- a/xray/commands/testdata/secrets-scan/no-secrets.sarif +++ /dev/null @@ -1,29 +0,0 @@ -{ - "runs": [ - { - "tool": { - "driver": { - "name": "JFrog Terraform scanner", - "rules": [], - "version": "" - } - }, - "invocations": [ - { - "executionSuccessful": true, - "arguments": [ - "mac_arm/secrets_scanner/secrets_scanner", - "scan", - "sec_config_example.yaml" - ], - "workingDirectory": { - "uri": "file:///am_versions_for_leap" - } - } - ], - "results": [] - } - ], - "version": "2.1.0", - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/cos02/schemas/sarif-schema-2.1.0.json" -} \ No newline at end of file diff --git a/xray/commands/testdata/yarn-project/.yarn/releases/yarn-1.22.21.cjs b/xray/commands/testdata/yarn-project/.yarn/releases/yarn-1.22.21.cjs deleted file mode 100755 index 118a2a2e0..000000000 --- a/xray/commands/testdata/yarn-project/.yarn/releases/yarn-1.22.21.cjs +++ /dev/null @@ -1,147513 +0,0 @@ -#!/usr/bin/env node -module.exports = -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // identity function for calling harmony imports with the correct context -/******/ __webpack_require__.i = function(value) { return value; }; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); -/******/ } -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 517); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports) { - -module.exports = require("path"); - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (immutable) */ __webpack_exports__["a"] = __extends; -/* unused harmony export __assign */ -/* unused harmony export __rest */ -/* unused harmony export __decorate */ -/* unused harmony export __param */ -/* unused harmony export __metadata */ -/* unused harmony export __awaiter */ -/* unused harmony export __generator */ -/* unused harmony export __exportStar */ -/* unused harmony export __values */ -/* unused harmony export __read */ -/* unused harmony export __spread */ -/* unused harmony export __await */ -/* unused harmony export __asyncGenerator */ -/* unused harmony export __asyncDelegator */ -/* unused harmony export __asyncValues */ -/* unused harmony export __makeTemplateObject */ -/* unused harmony export __importStar */ -/* unused harmony export __importDefault */ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -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 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) - t[p[i]] = s[p[i]]; - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.__esModule = true; - -var _promise = __webpack_require__(224); - -var _promise2 = _interopRequireDefault(_promise); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function (fn) { - return function () { - var gen = fn.apply(this, arguments); - return new _promise2.default(function (resolve, reject) { - function step(key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - return _promise2.default.resolve(value).then(function (value) { - step("next", value); - }, function (err) { - step("throw", err); - }); - } - } - - return step("next"); - }); - }; -}; - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - -module.exports = require("util"); - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - -module.exports = require("fs"); - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getFirstSuitableFolder = exports.readFirstAvailableStream = exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.unlink = exports.glob = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.open = exports.readFileBuffer = exports.lockQueue = exports.constants = undefined; - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); -} - -let buildActionsForCopy = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { - - // - let build = (() => { - var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { - const src = data.src, - dest = data.dest, - type = data.type; - - const onFresh = data.onFresh || noop; - const onDone = data.onDone || noop; - - // TODO https://github.com/yarnpkg/yarn/issues/3751 - // related to bundled dependencies handling - if (files.has(dest.toLowerCase())) { - reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`); - } else { - files.add(dest.toLowerCase()); - } - - if (type === 'symlink') { - yield mkdirp((_path || _load_path()).default.dirname(dest)); - onFresh(); - actions.symlink.push({ - dest, - linkname: src - }); - onDone(); - return; - } - - if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { - // ignored file - return; - } - - const srcStat = yield lstat(src); - let srcFiles; - - if (srcStat.isDirectory()) { - srcFiles = yield readdir(src); - } - - let destStat; - try { - // try accessing the destination - destStat = yield lstat(dest); - } catch (e) { - // proceed if destination doesn't exist, otherwise error - if (e.code !== 'ENOENT') { - throw e; - } - } - - // if destination exists - if (destStat) { - const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); - const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); - const bothFiles = srcStat.isFile() && destStat.isFile(); - - // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving - // us modes that aren't valid. investigate this, it's generally safe to proceed. - - /* if (srcStat.mode !== destStat.mode) { - try { - await access(dest, srcStat.mode); - } catch (err) {} - } */ - - if (bothFiles && artifactFiles.has(dest)) { - // this file gets changed during build, likely by a custom install script. Don't bother checking it. - onDone(); - reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); - return; - } - - if (bothFiles && srcStat.size === destStat.size && (0, (_fsNormalized || _load_fsNormalized()).fileDatesEqual)(srcStat.mtime, destStat.mtime)) { - // we can safely assume this is the same file - onDone(); - reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime)); - return; - } - - if (bothSymlinks) { - const srcReallink = yield readlink(src); - if (srcReallink === (yield readlink(dest))) { - // if both symlinks are the same then we can continue on - onDone(); - reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); - return; - } - } - - if (bothFolders) { - // mark files that aren't in this folder as possibly extraneous - const destFiles = yield readdir(dest); - invariant(srcFiles, 'src files not initialised'); - - for (var _iterator4 = destFiles, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { - var _ref6; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref6 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref6 = _i4.value; - } - - const file = _ref6; - - if (srcFiles.indexOf(file) < 0) { - const loc = (_path || _load_path()).default.join(dest, file); - possibleExtraneous.add(loc); - - if ((yield lstat(loc)).isDirectory()) { - for (var _iterator5 = yield readdir(loc), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { - var _ref7; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref7 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref7 = _i5.value; - } - - const file = _ref7; - - possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); - } - } - } - } - } - } - - if (destStat && destStat.isSymbolicLink()) { - yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); - destStat = null; - } - - if (srcStat.isSymbolicLink()) { - onFresh(); - const linkname = yield readlink(src); - actions.symlink.push({ - dest, - linkname - }); - onDone(); - } else if (srcStat.isDirectory()) { - if (!destStat) { - reporter.verbose(reporter.lang('verboseFileFolder', dest)); - yield mkdirp(dest); - } - - const destParts = dest.split((_path || _load_path()).default.sep); - while (destParts.length) { - files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); - destParts.pop(); - } - - // push all files to queue - invariant(srcFiles, 'src files not initialised'); - let remaining = srcFiles.length; - if (!remaining) { - onDone(); - } - for (var _iterator6 = srcFiles, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) { - var _ref8; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref8 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref8 = _i6.value; - } - - const file = _ref8; - - queue.push({ - dest: (_path || _load_path()).default.join(dest, file), - onFresh, - onDone: function (_onDone) { - function onDone() { - return _onDone.apply(this, arguments); - } - - onDone.toString = function () { - return _onDone.toString(); - }; - - return onDone; - }(function () { - if (--remaining === 0) { - onDone(); - } - }), - src: (_path || _load_path()).default.join(src, file) - }); - } - } else if (srcStat.isFile()) { - onFresh(); - actions.file.push({ - src, - dest, - atime: srcStat.atime, - mtime: srcStat.mtime, - mode: srcStat.mode - }); - onDone(); - } else { - throw new Error(`unsure how to copy this: ${src}`); - } - }); - - return function build(_x5) { - return _ref5.apply(this, arguments); - }; - })(); - - const artifactFiles = new Set(events.artifactFiles || []); - const files = new Set(); - - // initialise events - for (var _iterator = queue, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - const item = _ref2; - - const onDone = item.onDone; - item.onDone = function () { - events.onProgress(item.dest); - if (onDone) { - onDone(); - } - }; - } - events.onStart(queue.length); - - // start building actions - const actions = { - file: [], - symlink: [], - link: [] - }; - - // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items - // at a time due to the requirement to push items onto the queue - while (queue.length) { - const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); - yield Promise.all(items.map(build)); - } - - // simulate the existence of some files to prevent considering them extraneous - for (var _iterator2 = artifactFiles, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { - var _ref3; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } - - const file = _ref3; - - if (possibleExtraneous.has(file)) { - reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); - possibleExtraneous.delete(file); - } - } - - for (var _iterator3 = possibleExtraneous, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { - var _ref4; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } - - const loc = _ref4; - - if (files.has(loc.toLowerCase())) { - possibleExtraneous.delete(loc); - } - } - - return actions; - }); - - return function buildActionsForCopy(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); - -let buildActionsForHardlink = (() => { - var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, events, possibleExtraneous, reporter) { - - // - let build = (() => { - var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { - const src = data.src, - dest = data.dest; - - const onFresh = data.onFresh || noop; - const onDone = data.onDone || noop; - if (files.has(dest.toLowerCase())) { - // Fixes issue https://github.com/yarnpkg/yarn/issues/2734 - // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1, - // package-linker passes that modules A1 and B1 need to be hardlinked, - // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case - // an exception. - onDone(); - return; - } - files.add(dest.toLowerCase()); - - if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { - // ignored file - return; - } - - const srcStat = yield lstat(src); - let srcFiles; - - if (srcStat.isDirectory()) { - srcFiles = yield readdir(src); - } - - const destExists = yield exists(dest); - if (destExists) { - const destStat = yield lstat(dest); - - const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink(); - const bothFolders = srcStat.isDirectory() && destStat.isDirectory(); - const bothFiles = srcStat.isFile() && destStat.isFile(); - - if (srcStat.mode !== destStat.mode) { - try { - yield access(dest, srcStat.mode); - } catch (err) { - // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving - // us modes that aren't valid. investigate this, it's generally safe to proceed. - reporter.verbose(err); - } - } - - if (bothFiles && artifactFiles.has(dest)) { - // this file gets changed during build, likely by a custom install script. Don't bother checking it. - onDone(); - reporter.verbose(reporter.lang('verboseFileSkipArtifact', src)); - return; - } - - // correct hardlink - if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) { - onDone(); - reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino)); - return; - } - - if (bothSymlinks) { - const srcReallink = yield readlink(src); - if (srcReallink === (yield readlink(dest))) { - // if both symlinks are the same then we can continue on - onDone(); - reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink)); - return; - } - } - - if (bothFolders) { - // mark files that aren't in this folder as possibly extraneous - const destFiles = yield readdir(dest); - invariant(srcFiles, 'src files not initialised'); - - for (var _iterator10 = destFiles, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) { - var _ref14; - - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref14 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref14 = _i10.value; - } - - const file = _ref14; - - if (srcFiles.indexOf(file) < 0) { - const loc = (_path || _load_path()).default.join(dest, file); - possibleExtraneous.add(loc); - - if ((yield lstat(loc)).isDirectory()) { - for (var _iterator11 = yield readdir(loc), _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) { - var _ref15; - - if (_isArray11) { - if (_i11 >= _iterator11.length) break; - _ref15 = _iterator11[_i11++]; - } else { - _i11 = _iterator11.next(); - if (_i11.done) break; - _ref15 = _i11.value; - } - - const file = _ref15; - - possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); - } - } - } - } - } - } - - if (srcStat.isSymbolicLink()) { - onFresh(); - const linkname = yield readlink(src); - actions.symlink.push({ - dest, - linkname - }); - onDone(); - } else if (srcStat.isDirectory()) { - reporter.verbose(reporter.lang('verboseFileFolder', dest)); - yield mkdirp(dest); - - const destParts = dest.split((_path || _load_path()).default.sep); - while (destParts.length) { - files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); - destParts.pop(); - } - - // push all files to queue - invariant(srcFiles, 'src files not initialised'); - let remaining = srcFiles.length; - if (!remaining) { - onDone(); - } - for (var _iterator12 = srcFiles, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) { - var _ref16; - - if (_isArray12) { - if (_i12 >= _iterator12.length) break; - _ref16 = _iterator12[_i12++]; - } else { - _i12 = _iterator12.next(); - if (_i12.done) break; - _ref16 = _i12.value; - } - - const file = _ref16; - - queue.push({ - onFresh, - src: (_path || _load_path()).default.join(src, file), - dest: (_path || _load_path()).default.join(dest, file), - onDone: function (_onDone2) { - function onDone() { - return _onDone2.apply(this, arguments); - } - - onDone.toString = function () { - return _onDone2.toString(); - }; - - return onDone; - }(function () { - if (--remaining === 0) { - onDone(); - } - }) - }); - } - } else if (srcStat.isFile()) { - onFresh(); - actions.link.push({ - src, - dest, - removeDest: destExists - }); - onDone(); - } else { - throw new Error(`unsure how to copy this: ${src}`); - } - }); - - return function build(_x10) { - return _ref13.apply(this, arguments); - }; - })(); - - const artifactFiles = new Set(events.artifactFiles || []); - const files = new Set(); - - // initialise events - for (var _iterator7 = queue, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) { - var _ref10; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref10 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref10 = _i7.value; - } - - const item = _ref10; - - const onDone = item.onDone || noop; - item.onDone = function () { - events.onProgress(item.dest); - onDone(); - }; - } - events.onStart(queue.length); - - // start building actions - const actions = { - file: [], - symlink: [], - link: [] - }; - - // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items - // at a time due to the requirement to push items onto the queue - while (queue.length) { - const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS); - yield Promise.all(items.map(build)); - } - - // simulate the existence of some files to prevent considering them extraneous - for (var _iterator8 = artifactFiles, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) { - var _ref11; - - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref11 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref11 = _i8.value; - } - - const file = _ref11; - - if (possibleExtraneous.has(file)) { - reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file)); - possibleExtraneous.delete(file); - } - } - - for (var _iterator9 = possibleExtraneous, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) { - var _ref12; - - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref12 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref12 = _i9.value; - } - - const loc = _ref12; - - if (files.has(loc.toLowerCase())) { - possibleExtraneous.delete(loc); - } - } - - return actions; - }); - - return function buildActionsForHardlink(_x6, _x7, _x8, _x9) { - return _ref9.apply(this, arguments); - }; -})(); - -let copyBulk = exports.copyBulk = (() => { - var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { - const events = { - onStart: _events && _events.onStart || noop, - onProgress: _events && _events.onProgress || noop, - possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), - ignoreBasenames: _events && _events.ignoreBasenames || [], - artifactFiles: _events && _events.artifactFiles || [] - }; - - const actions = yield buildActionsForCopy(queue, events, events.possibleExtraneous, reporter); - events.onStart(actions.file.length + actions.symlink.length + actions.link.length); - - const fileActions = actions.file; - - const currentlyWriting = new Map(); - - yield (_promise || _load_promise()).queue(fileActions, (() => { - var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { - let writePromise; - while (writePromise = currentlyWriting.get(data.dest)) { - yield writePromise; - } - - reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest)); - const copier = (0, (_fsNormalized || _load_fsNormalized()).copyFile)(data, function () { - return currentlyWriting.delete(data.dest); - }); - currentlyWriting.set(data.dest, copier); - events.onProgress(data.dest); - return copier; - }); - - return function (_x14) { - return _ref18.apply(this, arguments); - }; - })(), CONCURRENT_QUEUE_ITEMS); - - // we need to copy symlinks last as they could reference files we were copying - const symlinkActions = actions.symlink; - yield (_promise || _load_promise()).queue(symlinkActions, function (data) { - const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); - reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); - return symlink(linkname, data.dest); - }); - }); - - return function copyBulk(_x11, _x12, _x13) { - return _ref17.apply(this, arguments); - }; -})(); - -let hardlinkBulk = exports.hardlinkBulk = (() => { - var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { - const events = { - onStart: _events && _events.onStart || noop, - onProgress: _events && _events.onProgress || noop, - possibleExtraneous: _events ? _events.possibleExtraneous : new Set(), - artifactFiles: _events && _events.artifactFiles || [], - ignoreBasenames: [] - }; - - const actions = yield buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter); - events.onStart(actions.file.length + actions.symlink.length + actions.link.length); - - const fileActions = actions.link; - - yield (_promise || _load_promise()).queue(fileActions, (() => { - var _ref20 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { - reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest)); - if (data.removeDest) { - yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(data.dest); - } - yield link(data.src, data.dest); - }); - - return function (_x18) { - return _ref20.apply(this, arguments); - }; - })(), CONCURRENT_QUEUE_ITEMS); - - // we need to copy symlinks last as they could reference files we were copying - const symlinkActions = actions.symlink; - yield (_promise || _load_promise()).queue(symlinkActions, function (data) { - const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); - reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); - return symlink(linkname, data.dest); - }); - }); - - return function hardlinkBulk(_x15, _x16, _x17) { - return _ref19.apply(this, arguments); - }; -})(); - -let readFileAny = exports.readFileAny = (() => { - var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) { - for (var _iterator13 = files, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) { - var _ref22; - - if (_isArray13) { - if (_i13 >= _iterator13.length) break; - _ref22 = _iterator13[_i13++]; - } else { - _i13 = _iterator13.next(); - if (_i13.done) break; - _ref22 = _i13.value; - } - - const file = _ref22; - - if (yield exists(file)) { - return readFile(file); - } - } - return null; - }); - - return function readFileAny(_x19) { - return _ref21.apply(this, arguments); - }; -})(); - -let readJson = exports.readJson = (() => { - var _ref23 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { - return (yield readJsonAndFile(loc)).object; - }); - - return function readJson(_x20) { - return _ref23.apply(this, arguments); - }; -})(); - -let readJsonAndFile = exports.readJsonAndFile = (() => { - var _ref24 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { - const file = yield readFile(loc); - try { - return { - object: (0, (_map || _load_map()).default)(JSON.parse(stripBOM(file))), - content: file - }; - } catch (err) { - err.message = `${loc}: ${err.message}`; - throw err; - } - }); - - return function readJsonAndFile(_x21) { - return _ref24.apply(this, arguments); - }; -})(); - -let find = exports.find = (() => { - var _ref25 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) { - const parts = dir.split((_path || _load_path()).default.sep); - - while (parts.length) { - const loc = parts.concat(filename).join((_path || _load_path()).default.sep); - - if (yield exists(loc)) { - return loc; - } else { - parts.pop(); - } - } - - return false; - }); - - return function find(_x22, _x23) { - return _ref25.apply(this, arguments); - }; -})(); - -let symlink = exports.symlink = (() => { - var _ref26 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { - if (process.platform !== 'win32') { - // use relative paths otherwise which will be retained if the directory is moved - src = (_path || _load_path()).default.relative((_path || _load_path()).default.dirname(dest), src); - // When path.relative returns an empty string for the current directory, we should instead use - // '.', which is a valid fs.symlink target. - src = src || '.'; - } - - try { - const stats = yield lstat(dest); - if (stats.isSymbolicLink()) { - const resolved = dest; - if (resolved === src) { - return; - } - } - } catch (err) { - if (err.code !== 'ENOENT') { - throw err; - } - } - - // We use rimraf for unlink which never throws an ENOENT on missing target - yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dest); - - if (process.platform === 'win32') { - // use directory junctions if possible on win32, this requires absolute paths - yield fsSymlink(src, dest, 'junction'); - } else { - yield fsSymlink(src, dest); - } - }); - - return function symlink(_x24, _x25) { - return _ref26.apply(this, arguments); - }; -})(); - -let walk = exports.walk = (() => { - var _ref27 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir, ignoreBasenames = new Set()) { - let files = []; - - let filenames = yield readdir(dir); - if (ignoreBasenames.size) { - filenames = filenames.filter(function (name) { - return !ignoreBasenames.has(name); - }); - } - - for (var _iterator14 = filenames, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) { - var _ref28; - - if (_isArray14) { - if (_i14 >= _iterator14.length) break; - _ref28 = _iterator14[_i14++]; - } else { - _i14 = _iterator14.next(); - if (_i14.done) break; - _ref28 = _i14.value; - } - - const name = _ref28; - - const relative = relativeDir ? (_path || _load_path()).default.join(relativeDir, name) : name; - const loc = (_path || _load_path()).default.join(dir, name); - const stat = yield lstat(loc); - - files.push({ - relative, - basename: name, - absolute: loc, - mtime: +stat.mtime - }); - - if (stat.isDirectory()) { - files = files.concat((yield walk(loc, relative, ignoreBasenames))); - } - } - - return files; - }); - - return function walk(_x26, _x27) { - return _ref27.apply(this, arguments); - }; -})(); - -let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => { - var _ref29 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { - const stat = yield lstat(loc); - const size = stat.size, - blockSize = stat.blksize; - - - return Math.ceil(size / blockSize) * blockSize; - }); - - return function getFileSizeOnDisk(_x28) { - return _ref29.apply(this, arguments); - }; -})(); - -let getEolFromFile = (() => { - var _ref30 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) { - if (!(yield exists(path))) { - return undefined; - } - - const buffer = yield readFileBuffer(path); - - for (let i = 0; i < buffer.length; ++i) { - if (buffer[i] === cr) { - return '\r\n'; - } - if (buffer[i] === lf) { - return '\n'; - } - } - return undefined; - }); - - return function getEolFromFile(_x29) { - return _ref30.apply(this, arguments); - }; -})(); - -let writeFilePreservingEol = exports.writeFilePreservingEol = (() => { - var _ref31 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) { - const eol = (yield getEolFromFile(path)) || (_os || _load_os()).default.EOL; - if (eol !== '\n') { - data = data.replace(/\n/g, eol); - } - yield writeFile(path, data); - }); - - return function writeFilePreservingEol(_x30, _x31) { - return _ref31.apply(this, arguments); - }; -})(); - -let hardlinksWork = exports.hardlinksWork = (() => { - var _ref32 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) { - const filename = 'test-file' + Math.random(); - const file = (_path || _load_path()).default.join(dir, filename); - const fileLink = (_path || _load_path()).default.join(dir, filename + '-link'); - try { - yield writeFile(file, 'test'); - yield link(file, fileLink); - } catch (err) { - return false; - } finally { - yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(file); - yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(fileLink); - } - return true; - }); - - return function hardlinksWork(_x32) { - return _ref32.apply(this, arguments); - }; -})(); - -// not a strict polyfill for Node's fs.mkdtemp - - -let makeTempDir = exports.makeTempDir = (() => { - var _ref33 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) { - const dir = (_path || _load_path()).default.join((_os || _load_os()).default.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`); - yield (0, (_fsNormalized || _load_fsNormalized()).unlink)(dir); - yield mkdirp(dir); - return dir; - }); - - return function makeTempDir(_x33) { - return _ref33.apply(this, arguments); - }; -})(); - -let readFirstAvailableStream = exports.readFirstAvailableStream = (() => { - var _ref34 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths) { - for (var _iterator15 = paths, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) { - var _ref35; - - if (_isArray15) { - if (_i15 >= _iterator15.length) break; - _ref35 = _iterator15[_i15++]; - } else { - _i15 = _iterator15.next(); - if (_i15.done) break; - _ref35 = _i15.value; - } - - const path = _ref35; - - try { - const fd = yield open(path, 'r'); - return (_fs || _load_fs()).default.createReadStream(path, { fd }); - } catch (err) { - // Try the next one - } - } - return null; - }); - - return function readFirstAvailableStream(_x34) { - return _ref34.apply(this, arguments); - }; -})(); - -let getFirstSuitableFolder = exports.getFirstSuitableFolder = (() => { - var _ref36 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths, mode = constants.W_OK | constants.X_OK) { - const result = { - skipped: [], - folder: null - }; - - for (var _iterator16 = paths, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : _iterator16[Symbol.iterator]();;) { - var _ref37; - - if (_isArray16) { - if (_i16 >= _iterator16.length) break; - _ref37 = _iterator16[_i16++]; - } else { - _i16 = _iterator16.next(); - if (_i16.done) break; - _ref37 = _i16.value; - } - - const folder = _ref37; - - try { - yield mkdirp(folder); - yield access(folder, mode); - - result.folder = folder; - - return result; - } catch (error) { - result.skipped.push({ - error, - folder - }); - } - } - return result; - }); - - return function getFirstSuitableFolder(_x35) { - return _ref36.apply(this, arguments); - }; -})(); - -exports.copy = copy; -exports.readFile = readFile; -exports.readFileRaw = readFileRaw; -exports.normalizeOS = normalizeOS; - -var _fs; - -function _load_fs() { - return _fs = _interopRequireDefault(__webpack_require__(4)); -} - -var _glob; - -function _load_glob() { - return _glob = _interopRequireDefault(__webpack_require__(99)); -} - -var _os; - -function _load_os() { - return _os = _interopRequireDefault(__webpack_require__(42)); -} - -var _path; - -function _load_path() { - return _path = _interopRequireDefault(__webpack_require__(0)); -} - -var _blockingQueue; - -function _load_blockingQueue() { - return _blockingQueue = _interopRequireDefault(__webpack_require__(110)); -} - -var _promise; - -function _load_promise() { - return _promise = _interopRequireWildcard(__webpack_require__(51)); -} - -var _promise2; - -function _load_promise2() { - return _promise2 = __webpack_require__(51); -} - -var _map; - -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(30)); -} - -var _fsNormalized; - -function _load_fsNormalized() { - return _fsNormalized = __webpack_require__(216); -} - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const constants = exports.constants = typeof (_fs || _load_fs()).default.constants !== 'undefined' ? (_fs || _load_fs()).default.constants : { - R_OK: (_fs || _load_fs()).default.R_OK, - W_OK: (_fs || _load_fs()).default.W_OK, - X_OK: (_fs || _load_fs()).default.X_OK -}; - -const lockQueue = exports.lockQueue = new (_blockingQueue || _load_blockingQueue()).default('fs lock'); - -const readFileBuffer = exports.readFileBuffer = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readFile); -const open = exports.open = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.open); -const writeFile = exports.writeFile = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.writeFile); -const readlink = exports.readlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readlink); -const realpath = exports.realpath = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.realpath); -const readdir = exports.readdir = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readdir); -const rename = exports.rename = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.rename); -const access = exports.access = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.access); -const stat = exports.stat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.stat); -const mkdirp = exports.mkdirp = (0, (_promise2 || _load_promise2()).promisify)(__webpack_require__(145)); -const exists = exports.exists = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.exists, true); -const lstat = exports.lstat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.lstat); -const chmod = exports.chmod = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.chmod); -const link = exports.link = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.link); -const glob = exports.glob = (0, (_promise2 || _load_promise2()).promisify)((_glob || _load_glob()).default); -exports.unlink = (_fsNormalized || _load_fsNormalized()).unlink; - -// fs.copyFile uses the native file copying instructions on the system, performing much better -// than any JS-based solution and consumes fewer resources. Repeated testing to fine tune the -// concurrency level revealed 128 as the sweet spot on a quad-core, 16 CPU Intel system with SSD. - -const CONCURRENT_QUEUE_ITEMS = (_fs || _load_fs()).default.copyFile ? 128 : 4; - -const fsSymlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.symlink); -const invariant = __webpack_require__(9); -const stripBOM = __webpack_require__(160); - -const noop = () => {}; - -function copy(src, dest, reporter) { - return copyBulk([{ src, dest }], reporter); -} - -function _readFile(loc, encoding) { - return new Promise((resolve, reject) => { - (_fs || _load_fs()).default.readFile(loc, encoding, function (err, content) { - if (err) { - reject(err); - } else { - resolve(content); - } - }); - }); -} - -function readFile(loc) { - return _readFile(loc, 'utf8').then(normalizeOS); -} - -function readFileRaw(loc) { - return _readFile(loc, 'binary'); -} - -function normalizeOS(body) { - return body.replace(/\r\n/g, '\n'); -} - -const cr = '\r'.charCodeAt(0); -const lf = '\n'.charCodeAt(0); - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -class MessageError extends Error { - constructor(msg, code) { - super(msg); - this.code = code; - } - -} - -exports.MessageError = MessageError; -class ProcessSpawnError extends MessageError { - constructor(msg, code, process) { - super(msg, code); - this.process = process; - } - -} - -exports.ProcessSpawnError = ProcessSpawnError; -class SecurityError extends MessageError {} - -exports.SecurityError = SecurityError; -class ProcessTermError extends MessageError {} - -exports.ProcessTermError = ProcessTermError; -class ResponseError extends Error { - constructor(msg, responseCode) { - super(msg); - this.responseCode = responseCode; - } - -} - -exports.ResponseError = ResponseError; -class OneTimePasswordError extends Error { - constructor(notice) { - super(); - this.notice = notice; - } - -} -exports.OneTimePasswordError = OneTimePasswordError; - -/***/ }), -/* 7 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscriber; }); -/* unused harmony export SafeSubscriber */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_isFunction__ = __webpack_require__(154); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Observer__ = __webpack_require__(420); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Subscription__ = __webpack_require__(25); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__internal_symbol_rxSubscriber__ = __webpack_require__(321); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__config__ = __webpack_require__(186); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__util_hostReportError__ = __webpack_require__(323); -/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ - - - - - - - -var Subscriber = /*@__PURE__*/ (function (_super) { - __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](Subscriber, _super); - function Subscriber(destinationOrNext, error, complete) { - var _this = _super.call(this) || this; - _this.syncErrorValue = null; - _this.syncErrorThrown = false; - _this.syncErrorThrowable = false; - _this.isStopped = false; - _this._parentSubscription = null; - switch (arguments.length) { - case 0: - _this.destination = __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]; - break; - case 1: - if (!destinationOrNext) { - _this.destination = __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]; - break; - } - if (typeof destinationOrNext === 'object') { - if (destinationOrNext instanceof Subscriber) { - _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; - _this.destination = destinationOrNext; - destinationOrNext.add(_this); - } - else { - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext); - } - break; - } - default: - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); - break; - } - return _this; - } - Subscriber.prototype[__WEBPACK_IMPORTED_MODULE_4__internal_symbol_rxSubscriber__["a" /* rxSubscriber */]] = function () { return this; }; - Subscriber.create = function (next, error, complete) { - var subscriber = new Subscriber(next, error, complete); - subscriber.syncErrorThrowable = false; - return subscriber; - }; - Subscriber.prototype.next = function (value) { - if (!this.isStopped) { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (!this.isStopped) { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (!this.isStopped) { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - this.destination.error(err); - this.unsubscribe(); - }; - Subscriber.prototype._complete = function () { - this.destination.complete(); - this.unsubscribe(); - }; - Subscriber.prototype._unsubscribeAndRecycle = function () { - var _a = this, _parent = _a._parent, _parents = _a._parents; - this._parent = null; - this._parents = null; - this.unsubscribe(); - this.closed = false; - this.isStopped = false; - this._parent = _parent; - this._parents = _parents; - this._parentSubscription = null; - return this; - }; - return Subscriber; -}(__WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */])); - -var SafeSubscriber = /*@__PURE__*/ (function (_super) { - __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](SafeSubscriber, _super); - function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { - var _this = _super.call(this) || this; - _this._parentSubscriber = _parentSubscriber; - var next; - var context = _this; - if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isFunction__["a" /* isFunction */])(observerOrNext)) { - next = observerOrNext; - } - else if (observerOrNext) { - next = observerOrNext.next; - error = observerOrNext.error; - complete = observerOrNext.complete; - if (observerOrNext !== __WEBPACK_IMPORTED_MODULE_2__Observer__["a" /* empty */]) { - context = Object.create(observerOrNext); - if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isFunction__["a" /* isFunction */])(context.unsubscribe)) { - _this.add(context.unsubscribe.bind(context)); - } - context.unsubscribe = _this.unsubscribe.bind(_this); - } - } - _this._context = context; - _this._next = next; - _this._error = error; - _this._complete = complete; - return _this; - } - SafeSubscriber.prototype.next = function (value) { - if (!this.isStopped && this._next) { - var _parentSubscriber = this._parentSubscriber; - if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._next, value); - } - else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - var useDeprecatedSynchronousErrorHandling = __WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling; - if (this._error) { - if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._error, err); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, this._error, err); - this.unsubscribe(); - } - } - else if (!_parentSubscriber.syncErrorThrowable) { - this.unsubscribe(); - if (useDeprecatedSynchronousErrorHandling) { - throw err; - } - __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); - } - else { - if (useDeprecatedSynchronousErrorHandling) { - _parentSubscriber.syncErrorValue = err; - _parentSubscriber.syncErrorThrown = true; - } - else { - __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); - } - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.complete = function () { - var _this = this; - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - if (this._complete) { - var wrappedComplete = function () { return _this._complete.call(_this._context); }; - if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(wrappedComplete); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, wrappedComplete); - this.unsubscribe(); - } - } - else { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { - try { - fn.call(this._context, value); - } - catch (err) { - this.unsubscribe(); - if (__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); - } - } - }; - SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { - if (!__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { - throw new Error('bad call'); - } - try { - fn.call(this._context, value); - } - catch (err) { - if (__WEBPACK_IMPORTED_MODULE_5__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { - parent.syncErrorValue = err; - parent.syncErrorThrown = true; - return true; - } - else { - __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_6__util_hostReportError__["a" /* hostReportError */])(err); - return true; - } - } - return false; - }; - SafeSubscriber.prototype._unsubscribe = function () { - var _parentSubscriber = this._parentSubscriber; - this._context = null; - this._parentSubscriber = null; - _parentSubscriber.unsubscribe(); - }; - return SafeSubscriber; -}(Subscriber)); - -//# sourceMappingURL=Subscriber.js.map - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getPathKey = getPathKey; -const os = __webpack_require__(42); -const path = __webpack_require__(0); -const userHome = __webpack_require__(67).default; - -var _require = __webpack_require__(222); - -const getCacheDir = _require.getCacheDir, - getConfigDir = _require.getConfigDir, - getDataDir = _require.getDataDir; - -const isWebpackBundle = __webpack_require__(278); - -const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']; -const OWNED_DEPENDENCY_TYPES = exports.OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies']; - -const RESOLUTIONS = exports.RESOLUTIONS = 'resolutions'; -const MANIFEST_FIELDS = exports.MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES]; - -const SUPPORTED_NODE_VERSIONS = exports.SUPPORTED_NODE_VERSIONS = '^4.8.0 || ^5.7.0 || ^6.2.2 || >=8.0.0'; - -const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com'; -const NPM_REGISTRY_RE = exports.NPM_REGISTRY_RE = /https?:\/\/registry\.npmjs\.org/g; - -const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/'; -const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh'; -const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi'; - -const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version'; - -// cache version, bump whenever we make backwards incompatible changes -const CACHE_VERSION = exports.CACHE_VERSION = 6; - -// lockfile version, bump whenever we make backwards incompatible changes -const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1; - -// max amount of network requests to perform concurrently -const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8; - -// HTTP timeout used when downloading packages -const NETWORK_TIMEOUT = exports.NETWORK_TIMEOUT = 30 * 1000; // in milliseconds - -// max amount of child processes to execute concurrently -const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5; - -const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid']; - -function getPreferredCacheDirectories() { - const preferredCacheDirectories = [getCacheDir()]; - - if (process.getuid) { - // $FlowFixMe: process.getuid exists, dammit - preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache-${process.getuid()}`)); - } - - preferredCacheDirectories.push(path.join(os.tmpdir(), `.yarn-cache`)); - - return preferredCacheDirectories; -} - -const PREFERRED_MODULE_CACHE_DIRECTORIES = exports.PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories(); -const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getConfigDir(); -const DATA_DIRECTORY = exports.DATA_DIRECTORY = getDataDir(); -const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(DATA_DIRECTORY, 'link'); -const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(DATA_DIRECTORY, 'global'); - -const NODE_BIN_PATH = exports.NODE_BIN_PATH = process.execPath; -const YARN_BIN_PATH = exports.YARN_BIN_PATH = getYarnBinPath(); - -// Webpack needs to be configured with node.__dirname/__filename = false -function getYarnBinPath() { - if (isWebpackBundle) { - return __filename; - } else { - return path.join(__dirname, '..', 'bin', 'yarn.js'); - } -} - -const NODE_MODULES_FOLDER = exports.NODE_MODULES_FOLDER = 'node_modules'; -const NODE_PACKAGE_JSON = exports.NODE_PACKAGE_JSON = 'package.json'; - -const PNP_FILENAME = exports.PNP_FILENAME = '.pnp.js'; - -const POSIX_GLOBAL_PREFIX = exports.POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`; -const FALLBACK_GLOBAL_PREFIX = exports.FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.yarn'); - -const META_FOLDER = exports.META_FOLDER = '.yarn-meta'; -const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity'; -const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock'; -const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json'; -const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz'; -const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean'; - -const NPM_LOCK_FILENAME = exports.NPM_LOCK_FILENAME = 'package-lock.json'; -const NPM_SHRINKWRAP_FILENAME = exports.NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json'; - -const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' '; -const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997; -const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance'; - -const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env); - -function getPathKey(platform, env) { - let pathKey = 'PATH'; - - // windows calls its path "Path" usually, but this is not guaranteed. - if (platform === 'win32') { - pathKey = 'Path'; - - for (const key in env) { - if (key.toLowerCase() === 'path') { - pathKey = key; - } - } - } - - return pathKey; -} - -const VERSION_COLOR_SCHEME = exports.VERSION_COLOR_SCHEME = { - major: 'red', - premajor: 'red', - minor: 'yellow', - preminor: 'yellow', - patch: 'green', - prepatch: 'green', - prerelease: 'red', - unchanged: 'white', - unknown: 'red' -}; - -/***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - - -/** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ - -var NODE_ENV = process.env.NODE_ENV; - -var invariant = function(condition, format, a, b, c, d, e, f) { - if (NODE_ENV !== 'production') { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - } - - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; - } - - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } -}; - -module.exports = invariant; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var YAMLException = __webpack_require__(55); - -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'defaultStyle', - 'styleAliases' -]; - -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; - -function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; -} - -function Type(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} - -module.exports = Type; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports) { - -module.exports = require("crypto"); - -/***/ }), -/* 12 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Observable; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util_canReportError__ = __webpack_require__(322); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_toSubscriber__ = __webpack_require__(932); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__internal_symbol_observable__ = __webpack_require__(118); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util_pipe__ = __webpack_require__(324); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__config__ = __webpack_require__(186); -/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_internal_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ - - - - - -var Observable = /*@__PURE__*/ (function () { - function Observable(subscribe) { - this._isScalar = false; - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var operator = this.operator; - var sink = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_toSubscriber__["a" /* toSubscriber */])(observerOrNext, error, complete); - if (operator) { - operator.call(sink, this.source); - } - else { - sink.add(this.source || (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? - this._subscribe(sink) : - this._trySubscribe(sink)); - } - if (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { - if (sink.syncErrorThrowable) { - sink.syncErrorThrowable = false; - if (sink.syncErrorThrown) { - throw sink.syncErrorValue; - } - } - } - return sink; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - if (__WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].useDeprecatedSynchronousErrorHandling) { - sink.syncErrorThrown = true; - sink.syncErrorValue = err; - } - if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__util_canReportError__["a" /* canReportError */])(sink)) { - sink.error(err); - } - else { - console.warn(err); - } - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscription; - subscription = _this.subscribe(function (value) { - try { - next(value); - } - catch (err) { - reject(err); - if (subscription) { - subscription.unsubscribe(); - } - } - }, reject, resolve); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var source = this.source; - return source && source.subscribe(subscriber); - }; - Observable.prototype[__WEBPACK_IMPORTED_MODULE_2__internal_symbol_observable__["a" /* observable */]] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - if (operations.length === 0) { - return this; - } - return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_pipe__["b" /* pipeFromArray */])(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; -}()); - -function getPromiseCtor(promiseCtor) { - if (!promiseCtor) { - promiseCtor = __WEBPACK_IMPORTED_MODULE_4__config__["a" /* config */].Promise || Promise; - } - if (!promiseCtor) { - throw new Error('no Promise impl found'); - } - return promiseCtor; -} -//# sourceMappingURL=Observable.js.map - - -/***/ }), -/* 13 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OuterSubscriber; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Subscriber__ = __webpack_require__(7); -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ - - -var OuterSubscriber = /*@__PURE__*/ (function (_super) { - __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](OuterSubscriber, _super); - function OuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - OuterSubscriber.prototype.notifyError = function (error, innerSub) { - this.destination.error(error); - }; - OuterSubscriber.prototype.notifyComplete = function (innerSub) { - this.destination.complete(); - }; - return OuterSubscriber; -}(__WEBPACK_IMPORTED_MODULE_1__Subscriber__["a" /* Subscriber */])); - -//# sourceMappingURL=OuterSubscriber.js.map - - -/***/ }), -/* 14 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (immutable) */ __webpack_exports__["a"] = subscribeToResult; -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__InnerSubscriber__ = __webpack_require__(84); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__subscribeTo__ = __webpack_require__(446); -/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo PURE_IMPORTS_END */ - - -function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) { - if (destination === void 0) { - destination = new __WEBPACK_IMPORTED_MODULE_0__InnerSubscriber__["a" /* InnerSubscriber */](outerSubscriber, outerValue, outerIndex); - } - if (destination.closed) { - return; - } - return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__subscribeTo__["a" /* subscribeTo */])(result)(destination); -} -//# sourceMappingURL=subscribeToResult.js.map - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* eslint-disable node/no-deprecated-api */ - - - -var buffer = __webpack_require__(64) -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright (c) 2012, Mark Cavage. All rights reserved. -// Copyright 2015 Joyent, Inc. - -var assert = __webpack_require__(29); -var Stream = __webpack_require__(23).Stream; -var util = __webpack_require__(3); - - -///--- Globals - -/* JSSTYLED */ -var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; - - -///--- Internal - -function _capitalize(str) { - return (str.charAt(0).toUpperCase() + str.slice(1)); -} - -function _toss(name, expected, oper, arg, actual) { - throw new assert.AssertionError({ - message: util.format('%s (%s) is required', name, expected), - actual: (actual === undefined) ? typeof (arg) : actual(arg), - expected: expected, - operator: oper || '===', - stackStartFunction: _toss.caller - }); -} - -function _getClass(arg) { - return (Object.prototype.toString.call(arg).slice(8, -1)); -} - -function noop() { - // Why even bother with asserts? -} - - -///--- Exports - -var types = { - bool: { - check: function (arg) { return typeof (arg) === 'boolean'; } - }, - func: { - check: function (arg) { return typeof (arg) === 'function'; } - }, - string: { - check: function (arg) { return typeof (arg) === 'string'; } - }, - object: { - check: function (arg) { - return typeof (arg) === 'object' && arg !== null; - } - }, - number: { - check: function (arg) { - return typeof (arg) === 'number' && !isNaN(arg); - } - }, - finite: { - check: function (arg) { - return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); - } - }, - buffer: { - check: function (arg) { return Buffer.isBuffer(arg); }, - operator: 'Buffer.isBuffer' - }, - array: { - check: function (arg) { return Array.isArray(arg); }, - operator: 'Array.isArray' - }, - stream: { - check: function (arg) { return arg instanceof Stream; }, - operator: 'instanceof', - actual: _getClass - }, - date: { - check: function (arg) { return arg instanceof Date; }, - operator: 'instanceof', - actual: _getClass - }, - regexp: { - check: function (arg) { return arg instanceof RegExp; }, - operator: 'instanceof', - actual: _getClass - }, - uuid: { - check: function (arg) { - return typeof (arg) === 'string' && UUID_REGEXP.test(arg); - }, - operator: 'isUUID' - } -}; - -function _setExports(ndebug) { - var keys = Object.keys(types); - var out; - - /* re-export standard assert */ - if (process.env.NODE_NDEBUG) { - out = noop; - } else { - out = function (arg, msg) { - if (!arg) { - _toss(msg, 'true', arg); - } - }; - } - - /* standard checks */ - keys.forEach(function (k) { - if (ndebug) { - out[k] = noop; - return; - } - var type = types[k]; - out[k] = function (arg, msg) { - if (!type.check(arg)) { - _toss(msg, k, type.operator, arg, type.actual); - } - }; - }); - - /* optional checks */ - keys.forEach(function (k) { - var name = 'optional' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; - } - var type = types[k]; - out[name] = function (arg, msg) { - if (arg === undefined || arg === null) { - return; - } - if (!type.check(arg)) { - _toss(msg, k, type.operator, arg, type.actual); - } - }; - }); - - /* arrayOf checks */ - keys.forEach(function (k) { - var name = 'arrayOf' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; - } - var type = types[k]; - var expected = '[' + k + ']'; - out[name] = function (arg, msg) { - if (!Array.isArray(arg)) { - _toss(msg, expected, type.operator, arg, type.actual); - } - var i; - for (i = 0; i < arg.length; i++) { - if (!type.check(arg[i])) { - _toss(msg, expected, type.operator, arg, type.actual); - } - } - }; - }); - - /* optionalArrayOf checks */ - keys.forEach(function (k) { - var name = 'optionalArrayOf' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; - } - var type = types[k]; - var expected = '[' + k + ']'; - out[name] = function (arg, msg) { - if (arg === undefined || arg === null) { - return; - } - if (!Array.isArray(arg)) { - _toss(msg, expected, type.operator, arg, type.actual); - } - var i; - for (i = 0; i < arg.length; i++) { - if (!type.check(arg[i])) { - _toss(msg, expected, type.operator, arg, type.actual); - } - } - }; - }); - - /* re-export built-in assertions */ - Object.keys(assert).forEach(function (k) { - if (k === 'AssertionError') { - out[k] = assert[k]; - return; - } - if (ndebug) { - out[k] = noop; - return; - } - out[k] = assert[k]; - }); - - /* export ourselves (for unit tests _only_) */ - out._setExports = _setExports; - - return out; -} - -module.exports = _setExports(process.env.NODE_NDEBUG); - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self - // eslint-disable-next-line no-new-func - : Function('return this')(); -if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.sortAlpha = sortAlpha; -exports.sortOptionsByFlags = sortOptionsByFlags; -exports.entries = entries; -exports.removePrefix = removePrefix; -exports.removeSuffix = removeSuffix; -exports.addSuffix = addSuffix; -exports.hyphenate = hyphenate; -exports.camelCase = camelCase; -exports.compareSortedArrays = compareSortedArrays; -exports.sleep = sleep; -const _camelCase = __webpack_require__(227); - -function sortAlpha(a, b) { - // sort alphabetically in a deterministic way - const shortLen = Math.min(a.length, b.length); - for (let i = 0; i < shortLen; i++) { - const aChar = a.charCodeAt(i); - const bChar = b.charCodeAt(i); - if (aChar !== bChar) { - return aChar - bChar; - } - } - return a.length - b.length; -} - -function sortOptionsByFlags(a, b) { - const aOpt = a.flags.replace(/-/g, ''); - const bOpt = b.flags.replace(/-/g, ''); - return sortAlpha(aOpt, bOpt); -} - -function entries(obj) { - const entries = []; - if (obj) { - for (const key in obj) { - entries.push([key, obj[key]]); - } - } - return entries; -} - -function removePrefix(pattern, prefix) { - if (pattern.startsWith(prefix)) { - pattern = pattern.slice(prefix.length); - } - - return pattern; -} - -function removeSuffix(pattern, suffix) { - if (pattern.endsWith(suffix)) { - return pattern.slice(0, -suffix.length); - } - - return pattern; -} - -function addSuffix(pattern, suffix) { - if (!pattern.endsWith(suffix)) { - return pattern + suffix; - } - - return pattern; -} - -function hyphenate(str) { - return str.replace(/[A-Z]/g, match => { - return '-' + match.charAt(0).toLowerCase(); - }); -} - -function camelCase(str) { - if (/[A-Z]/.test(str)) { - return null; - } else { - return _camelCase(str); - } -} - -function compareSortedArrays(array1, array2) { - if (array1.length !== array2.length) { - return false; - } - for (let i = 0, len = array1.length; i < len; i++) { - if (array1[i] !== array2[i]) { - return false; - } - } - return true; -} - -function sleep(ms) { - return new Promise(resolve => { - setTimeout(resolve, ms); - }); -} - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.stringify = exports.parse = undefined; - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); -} - -var _parse; - -function _load_parse() { - return _parse = __webpack_require__(106); -} - -Object.defineProperty(exports, 'parse', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_parse || _load_parse()).default; - } -}); - -var _stringify; - -function _load_stringify() { - return _stringify = __webpack_require__(200); -} - -Object.defineProperty(exports, 'stringify', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_stringify || _load_stringify()).default; - } -}); -exports.implodeEntry = implodeEntry; -exports.explodeEntry = explodeEntry; - -var _misc; - -function _load_misc() { - return _misc = __webpack_require__(18); -} - -var _normalizePattern; - -function _load_normalizePattern() { - return _normalizePattern = __webpack_require__(37); -} - -var _parse2; - -function _load_parse2() { - return _parse2 = _interopRequireDefault(__webpack_require__(106)); -} - -var _constants; - -function _load_constants() { - return _constants = __webpack_require__(8); -} - -var _fs; - -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(5)); -} - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const invariant = __webpack_require__(9); - -const path = __webpack_require__(0); -const ssri = __webpack_require__(65); - -function getName(pattern) { - return (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern).name; -} - -function blankObjectUndefined(obj) { - return obj && Object.keys(obj).length ? obj : undefined; -} - -function keyForRemote(remote) { - return remote.resolved || (remote.reference && remote.hash ? `${remote.reference}#${remote.hash}` : null); -} - -function serializeIntegrity(integrity) { - // We need this because `Integrity.toString()` does not use sorting to ensure a stable string output - // See https://git.io/vx2Hy - return integrity.toString().split(' ').sort().join(' '); -} - -function implodeEntry(pattern, obj) { - const inferredName = getName(pattern); - const integrity = obj.integrity ? serializeIntegrity(obj.integrity) : ''; - const imploded = { - name: inferredName === obj.name ? undefined : obj.name, - version: obj.version, - uid: obj.uid === obj.version ? undefined : obj.uid, - resolved: obj.resolved, - registry: obj.registry === 'npm' ? undefined : obj.registry, - dependencies: blankObjectUndefined(obj.dependencies), - optionalDependencies: blankObjectUndefined(obj.optionalDependencies), - permissions: blankObjectUndefined(obj.permissions), - prebuiltVariants: blankObjectUndefined(obj.prebuiltVariants) - }; - if (integrity) { - imploded.integrity = integrity; - } - return imploded; -} - -function explodeEntry(pattern, obj) { - obj.optionalDependencies = obj.optionalDependencies || {}; - obj.dependencies = obj.dependencies || {}; - obj.uid = obj.uid || obj.version; - obj.permissions = obj.permissions || {}; - obj.registry = obj.registry || 'npm'; - obj.name = obj.name || getName(pattern); - const integrity = obj.integrity; - if (integrity && integrity.isIntegrity) { - obj.integrity = ssri.parse(integrity); - } - return obj; -} - -class Lockfile { - constructor({ cache, source, parseResultType } = {}) { - this.source = source || ''; - this.cache = cache; - this.parseResultType = parseResultType; - } - - // source string if the `cache` was parsed - - - // if true, we're parsing an old yarn file and need to update integrity fields - hasEntriesExistWithoutIntegrity() { - if (!this.cache) { - return false; - } - - for (const key in this.cache) { - // $FlowFixMe - `this.cache` is clearly defined at this point - if (!/^.*@(file:|http)/.test(key) && this.cache[key] && !this.cache[key].integrity) { - return true; - } - } - - return false; - } - - static fromDirectory(dir, reporter) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // read the manifest in this directory - const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME); - - let lockfile; - let rawLockfile = ''; - let parseResult; - - if (yield (_fs || _load_fs()).exists(lockfileLoc)) { - rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc); - parseResult = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc); - - if (reporter) { - if (parseResult.type === 'merge') { - reporter.info(reporter.lang('lockfileMerged')); - } else if (parseResult.type === 'conflict') { - reporter.warn(reporter.lang('lockfileConflict')); - } - } - - lockfile = parseResult.object; - } else if (reporter) { - reporter.info(reporter.lang('noLockfileFound')); - } - - if (lockfile && lockfile.__metadata) { - const lockfilev2 = lockfile; - lockfile = {}; - } - - return new Lockfile({ cache: lockfile, source: rawLockfile, parseResultType: parseResult && parseResult.type }); - })(); - } - - getLocked(pattern) { - const cache = this.cache; - if (!cache) { - return undefined; - } - - const shrunk = pattern in cache && cache[pattern]; - - if (typeof shrunk === 'string') { - return this.getLocked(shrunk); - } else if (shrunk) { - explodeEntry(pattern, shrunk); - return shrunk; - } - - return undefined; - } - - removePattern(pattern) { - const cache = this.cache; - if (!cache) { - return; - } - delete cache[pattern]; - } - - getLockfile(patterns) { - const lockfile = {}; - const seen = new Map(); - - // order by name so that lockfile manifest is assigned to the first dependency with this manifest - // the others that have the same remoteKey will just refer to the first - // ordering allows for consistency in lockfile when it is serialized - const sortedPatternsKeys = Object.keys(patterns).sort((_misc || _load_misc()).sortAlpha); - - for (var _iterator = sortedPatternsKeys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - const pattern = _ref; - - const pkg = patterns[pattern]; - const remote = pkg._remote, - ref = pkg._reference; - - invariant(ref, 'Package is missing a reference'); - invariant(remote, 'Package is missing a remote'); - - const remoteKey = keyForRemote(remote); - const seenPattern = remoteKey && seen.get(remoteKey); - if (seenPattern) { - // no point in duplicating it - lockfile[pattern] = seenPattern; - - // if we're relying on our name being inferred and two of the patterns have - // different inferred names then we need to set it - if (!seenPattern.name && getName(pattern) !== pkg.name) { - seenPattern.name = pkg.name; - } - continue; - } - const obj = implodeEntry(pattern, { - name: pkg.name, - version: pkg.version, - uid: pkg._uid, - resolved: remote.resolved, - integrity: remote.integrity, - registry: remote.registry, - dependencies: pkg.dependencies, - peerDependencies: pkg.peerDependencies, - optionalDependencies: pkg.optionalDependencies, - permissions: ref.permissions, - prebuiltVariants: pkg.prebuiltVariants - }); - - lockfile[pattern] = obj; - - if (remoteKey) { - seen.set(remoteKey, obj); - } - } - - return lockfile; - } -} -exports.default = Lockfile; - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.__esModule = true; - -var _assign = __webpack_require__(559); - -var _assign2 = _interopRequireDefault(_assign); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = _assign2.default || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; -}; - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -var store = __webpack_require__(133)('wks'); -var uid = __webpack_require__(137); -var Symbol = __webpack_require__(17).Symbol; -var USE_SYMBOL = typeof Symbol == 'function'; - -var $exports = module.exports = function (name) { - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); -}; - -$exports.store = store; - - -/***/ }), -/* 22 */ -/***/ (function(module, exports) { - -exports = module.exports = SemVer; - -// The debug function is excluded entirely from the minified version. -/* nomin */ var debug; -/* nomin */ if (typeof process === 'object' && - /* nomin */ process.env && - /* nomin */ process.env.NODE_DEBUG && - /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) - /* nomin */ debug = function() { - /* nomin */ var args = Array.prototype.slice.call(arguments, 0); - /* nomin */ args.unshift('SEMVER'); - /* nomin */ console.log.apply(console, args); - /* nomin */ }; -/* nomin */ else - /* nomin */ debug = function() {}; - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0'; - -var MAX_LENGTH = 256; -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16; - -// The actual regexps go on exports.re -var re = exports.re = []; -var src = exports.src = []; -var R = 0; - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++; -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; -var NUMERICIDENTIFIERLOOSE = R++; -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; - - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++; -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; - - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++; -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')'; - -var MAINVERSIONLOOSE = R++; -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++; -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - -var PRERELEASEIDENTIFIERLOOSE = R++; -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++; -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; - -var PRERELEASELOOSE = R++; -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++; -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++; -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; - - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++; -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?'; - -src[FULL] = '^' + FULLPLAIN + '$'; - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?'; - -var LOOSE = R++; -src[LOOSE] = '^' + LOOSEPLAIN + '$'; - -var GTLT = R++; -src[GTLT] = '((?:<|>)?=?)'; - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++; -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; -var XRANGEIDENTIFIER = R++; -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; - -var XRANGEPLAIN = R++; -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?'; - -var XRANGEPLAINLOOSE = R++; -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?'; - -var XRANGE = R++; -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; -var XRANGELOOSE = R++; -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++; -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])'; - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++; -src[LONETILDE] = '(?:~>?)'; - -var TILDETRIM = R++; -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); -var tildeTrimReplace = '$1~'; - -var TILDE = R++; -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; -var TILDELOOSE = R++; -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++; -src[LONECARET] = '(?:\\^)'; - -var CARETTRIM = R++; -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); -var caretTrimReplace = '$1^'; - -var CARET = R++; -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; -var CARETLOOSE = R++; -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++; -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; -var COMPARATOR = R++; -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; - - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++; -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); -var comparatorTrimReplace = '$1$2$3'; - - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++; -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$'; - -var HYPHENRANGELOOSE = R++; -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$'; - -// Star ranges basically just allow anything at all. -var STAR = R++; -src[STAR] = '(<|>)?=?\\s*\\*'; - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]); - if (!re[i]) - re[i] = new RegExp(src[i]); -} - -exports.parse = parse; -function parse(version, loose) { - if (version instanceof SemVer) - return version; - - if (typeof version !== 'string') - return null; - - if (version.length > MAX_LENGTH) - return null; - - var r = loose ? re[LOOSE] : re[FULL]; - if (!r.test(version)) - return null; - - try { - return new SemVer(version, loose); - } catch (er) { - return null; - } -} - -exports.valid = valid; -function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; -} - - -exports.clean = clean; -function clean(version, loose) { - var s = parse(version.trim().replace(/^[=v]+/, ''), loose); - return s ? s.version : null; -} - -exports.SemVer = SemVer; - -function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) - return version; - else - version = version.version; - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version); - } - - if (version.length > MAX_LENGTH) - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - - if (!(this instanceof SemVer)) - return new SemVer(version, loose); - - debug('SemVer', version, loose); - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); - - if (!m) - throw new TypeError('Invalid Version: ' + version); - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) - throw new TypeError('Invalid major version') - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) - throw new TypeError('Invalid minor version') - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) - throw new TypeError('Invalid patch version') - - // numberify any prerelease numeric ids - if (!m[4]) - this.prerelease = []; - else - this.prerelease = m[4].split('.').map(function(id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) - return num; - } - return id; - }); - - this.build = m[5] ? m[5].split('.') : []; - this.format(); -} - -SemVer.prototype.format = function() { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) - this.version += '-' + this.prerelease.join('.'); - return this.version; -}; - -SemVer.prototype.toString = function() { - return this.version; -}; - -SemVer.prototype.compare = function(other) { - debug('SemVer.compare', this.version, this.loose, other); - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return this.compareMain(other) || this.comparePre(other); -}; - -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch); -}; - -SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) - return -1; - else if (!this.prerelease.length && other.prerelease.length) - return 1; - else if (!this.prerelease.length && !other.prerelease.length) - return 0; - - var i = 0; - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - debug('prerelease compare', i, a, b); - if (a === undefined && b === undefined) - return 0; - else if (b === undefined) - return 1; - else if (a === undefined) - return -1; - else if (a === b) - continue; - else - return compareIdentifiers(a, b); - } while (++i); -}; - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function(release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break; - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break; - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) - this.major++; - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) - this.minor++; - this.patch = 0; - this.prerelease = []; - break; - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) - this.patch++; - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) - this.prerelease = [0]; - else { - var i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) // didn't increment anything - this.prerelease.push(0); - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) - this.prerelease = [identifier, 0]; - } else - this.prerelease = [identifier, 0]; - } - break; - - default: - throw new Error('invalid increment argument: ' + release); - } - this.format(); - this.raw = this.version; - return this; -}; - -exports.inc = inc; -function inc(version, release, loose, identifier) { - if (typeof(loose) === 'string') { - identifier = loose; - loose = undefined; - } - - try { - return new SemVer(version, loose).inc(release, identifier).version; - } catch (er) { - return null; - } -} - -exports.diff = diff; -function diff(version1, version2) { - if (eq(version1, version2)) { - return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - if (v1.prerelease.length || v2.prerelease.length) { - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return 'pre'+key; - } - } - } - return 'prerelease'; - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return key; - } - } - } - } -} - -exports.compareIdentifiers = compareIdentifiers; - -var numeric = /^[0-9]+$/; -function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return (anum && !bnum) ? -1 : - (bnum && !anum) ? 1 : - a < b ? -1 : - a > b ? 1 : - 0; -} - -exports.rcompareIdentifiers = rcompareIdentifiers; -function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); -} - -exports.major = major; -function major(a, loose) { - return new SemVer(a, loose).major; -} - -exports.minor = minor; -function minor(a, loose) { - return new SemVer(a, loose).minor; -} - -exports.patch = patch; -function patch(a, loose) { - return new SemVer(a, loose).patch; -} - -exports.compare = compare; -function compare(a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)); -} - -exports.compareLoose = compareLoose; -function compareLoose(a, b) { - return compare(a, b, true); -} - -exports.rcompare = rcompare; -function rcompare(a, b, loose) { - return compare(b, a, loose); -} - -exports.sort = sort; -function sort(list, loose) { - return list.sort(function(a, b) { - return exports.compare(a, b, loose); - }); -} - -exports.rsort = rsort; -function rsort(list, loose) { - return list.sort(function(a, b) { - return exports.rcompare(a, b, loose); - }); -} - -exports.gt = gt; -function gt(a, b, loose) { - return compare(a, b, loose) > 0; -} - -exports.lt = lt; -function lt(a, b, loose) { - return compare(a, b, loose) < 0; -} - -exports.eq = eq; -function eq(a, b, loose) { - return compare(a, b, loose) === 0; -} - -exports.neq = neq; -function neq(a, b, loose) { - return compare(a, b, loose) !== 0; -} - -exports.gte = gte; -function gte(a, b, loose) { - return compare(a, b, loose) >= 0; -} - -exports.lte = lte; -function lte(a, b, loose) { - return compare(a, b, loose) <= 0; -} - -exports.cmp = cmp; -function cmp(a, op, b, loose) { - var ret; - switch (op) { - case '===': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a === b; - break; - case '!==': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a !== b; - break; - case '': case '=': case '==': ret = eq(a, b, loose); break; - case '!=': ret = neq(a, b, loose); break; - case '>': ret = gt(a, b, loose); break; - case '>=': ret = gte(a, b, loose); break; - case '<': ret = lt(a, b, loose); break; - case '<=': ret = lte(a, b, loose); break; - default: throw new TypeError('Invalid operator: ' + op); - } - return ret; -} - -exports.Comparator = Comparator; -function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) - return comp; - else - comp = comp.value; - } - - if (!(this instanceof Comparator)) - return new Comparator(comp, loose); - - debug('comparator', comp, loose); - this.loose = loose; - this.parse(comp); - - if (this.semver === ANY) - this.value = ''; - else - this.value = this.operator + this.semver.version; - - debug('comp', this); -} - -var ANY = {}; -Comparator.prototype.parse = function(comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); - - if (!m) - throw new TypeError('Invalid comparator: ' + comp); - - this.operator = m[1]; - if (this.operator === '=') - this.operator = ''; - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) - this.semver = ANY; - else - this.semver = new SemVer(m[2], this.loose); -}; - -Comparator.prototype.toString = function() { - return this.value; -}; - -Comparator.prototype.test = function(version) { - debug('Comparator.test', version, this.loose); - - if (this.semver === ANY) - return true; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - return cmp(version, this.operator, this.semver, this.loose); -}; - -Comparator.prototype.intersects = function(comp, loose) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required'); - } - - var rangeTmp; - - if (this.operator === '') { - rangeTmp = new Range(comp.value, loose); - return satisfies(this.value, rangeTmp, loose); - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, loose); - return satisfies(comp.semver, rangeTmp, loose); - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - var sameSemVer = this.semver.version === comp.semver.version; - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, loose) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')); - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, loose) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')); - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; -}; - - -exports.Range = Range; -function Range(range, loose) { - if (range instanceof Range) { - if (range.loose === loose) { - return range; - } else { - return new Range(range.raw, loose); - } - } - - if (range instanceof Comparator) { - return new Range(range.value, loose); - } - - if (!(this instanceof Range)) - return new Range(range, loose); - - this.loose = loose; - - // First, split based on boolean or || - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function(range) { - return this.parseRange(range.trim()); - }, this).filter(function(c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); - } - - this.format(); -} - -Range.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; -}; - -Range.prototype.toString = function() { - return this.range; -}; - -Range.prototype.parseRange = function(range) { - var loose = this.loose; - range = range.trim(); - debug('range', range, loose); - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - debug('comparator trim', range, re[COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function(comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function(comp) { - return !!comp.match(compRe); - }); - } - set = set.map(function(comp) { - return new Comparator(comp, loose); - }); - - return set; -}; - -Range.prototype.intersects = function(range, loose) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required'); - } - - return this.set.some(function(thisComparators) { - return thisComparators.every(function(thisComparator) { - return range.set.some(function(rangeComparators) { - return rangeComparators.every(function(rangeComparator) { - return thisComparator.intersects(rangeComparator, loose); - }); - }); - }); - }); -}; - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, loose) { - return new Range(range, loose).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(' ').trim().split(' '); - }); -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator(comp, loose) { - debug('comp', comp); - comp = replaceCarets(comp, loose); - debug('caret', comp); - comp = replaceTildes(comp, loose); - debug('tildes', comp); - comp = replaceXRanges(comp, loose); - debug('xrange', comp); - comp = replaceStars(comp, loose); - debug('stars', comp); - return comp; -} - -function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); -} - -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - - debug('tilde return', ret); - return ret; - }); -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} - -function replaceCaret(comp, loose) { - debug('caret', comp, loose); - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0'; - } else { - debug('no pr'); - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0'; - } - - debug('caret return', ret); - return ret; - }); -} - -function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} - -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - - if (gtlt === '=' && anyX) - gtlt = ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // replace X with 0 - if (xm) - m = 0; - if (xp) - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) - M = +M + 1; - else - m = +m + 1; - } - - ret = gtlt + M + '.' + m + '.' + p; - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - } - - debug('xRange return', ret); - - return ret; - }); -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0'; - else - from = '>=' + from; - - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; - - return (from + ' ' + to).trim(); -} - - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; - } - return false; -}; - -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; - } - - if (version.prerelease.length) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (var i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === ANY) - continue; - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) - return true; - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false; - } - - return true; -} - -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; - } - return range.test(version); -} - -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - var max = null; - var maxSV = null; - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, loose) - if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) - max = v; - maxSV = new SemVer(max, loose); - } - } - }) - return max; -} - -exports.minSatisfying = minSatisfying; -function minSatisfying(versions, range, loose) { - var min = null; - var minSV = null; - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, loose) - if (!min || minSV.compare(v) === 1) { // compare(min, v, true) - min = v; - minSV = new SemVer(min, loose); - } - } - }) - return min; -} - -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); -} - -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); - - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; - - var high = null; - var low = null; - - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; -} - -exports.prerelease = prerelease; -function prerelease(version, loose) { - var parsed = parse(version, loose); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; -} - -exports.intersects = intersects; -function intersects(r1, r2, loose) { - r1 = new Range(r1, loose) - r2 = new Range(r2, loose) - return r1.intersects(r2) -} - -exports.coerce = coerce; -function coerce(version) { - if (version instanceof SemVer) - return version; - - if (typeof version !== 'string') - return null; - - var match = version.match(re[COERCE]); - - if (match == null) - return null; - - return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); -} - - -/***/ }), -/* 23 */ -/***/ (function(module, exports) { - -module.exports = require("stream"); - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - -module.exports = require("url"); - -/***/ }), -/* 25 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscription; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__util_isArray__ = __webpack_require__(41); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_isObject__ = __webpack_require__(444); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util_isFunction__ = __webpack_require__(154); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util_tryCatch__ = __webpack_require__(57); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__util_errorObject__ = __webpack_require__(48); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__ = __webpack_require__(441); -/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_tryCatch,_util_errorObject,_util_UnsubscriptionError PURE_IMPORTS_END */ - - - - - - -var Subscription = /*@__PURE__*/ (function () { - function Subscription(unsubscribe) { - this.closed = false; - this._parent = null; - this._parents = null; - this._subscriptions = null; - if (unsubscribe) { - this._unsubscribe = unsubscribe; - } - } - Subscription.prototype.unsubscribe = function () { - var hasErrors = false; - var errors; - if (this.closed) { - return; - } - var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; - this.closed = true; - this._parent = null; - this._parents = null; - this._subscriptions = null; - var index = -1; - var len = _parents ? _parents.length : 0; - while (_parent) { - _parent.remove(this); - _parent = ++index < len && _parents[index] || null; - } - if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util_isFunction__["a" /* isFunction */])(_unsubscribe)) { - var trial = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_tryCatch__["a" /* tryCatch */])(_unsubscribe).call(this); - if (trial === __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */]) { - hasErrors = true; - errors = errors || (__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */] ? - flattenUnsubscriptionErrors(__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e.errors) : [__WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e]); - } - } - if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__util_isArray__["a" /* isArray */])(_subscriptions)) { - index = -1; - len = _subscriptions.length; - while (++index < len) { - var sub = _subscriptions[index]; - if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util_isObject__["a" /* isObject */])(sub)) { - var trial = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__util_tryCatch__["a" /* tryCatch */])(sub.unsubscribe).call(sub); - if (trial === __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */]) { - hasErrors = true; - errors = errors || []; - var err = __WEBPACK_IMPORTED_MODULE_4__util_errorObject__["a" /* errorObject */].e; - if (err instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */]) { - errors = errors.concat(flattenUnsubscriptionErrors(err.errors)); - } - else { - errors.push(err); - } - } - } - } - } - if (hasErrors) { - throw new __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */](errors); - } - }; - Subscription.prototype.add = function (teardown) { - if (!teardown || (teardown === Subscription.EMPTY)) { - return Subscription.EMPTY; - } - if (teardown === this) { - return this; - } - var subscription = teardown; - switch (typeof teardown) { - case 'function': - subscription = new Subscription(teardown); - case 'object': - if (subscription.closed || typeof subscription.unsubscribe !== 'function') { - return subscription; - } - else if (this.closed) { - subscription.unsubscribe(); - return subscription; - } - else if (typeof subscription._addParent !== 'function') { - var tmp = subscription; - subscription = new Subscription(); - subscription._subscriptions = [tmp]; - } - break; - default: - throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); - } - var subscriptions = this._subscriptions || (this._subscriptions = []); - subscriptions.push(subscription); - subscription._addParent(this); - return subscription; - }; - Subscription.prototype.remove = function (subscription) { - var subscriptions = this._subscriptions; - if (subscriptions) { - var subscriptionIndex = subscriptions.indexOf(subscription); - if (subscriptionIndex !== -1) { - subscriptions.splice(subscriptionIndex, 1); - } - } - }; - Subscription.prototype._addParent = function (parent) { - var _a = this, _parent = _a._parent, _parents = _a._parents; - if (!_parent || _parent === parent) { - this._parent = parent; - } - else if (!_parents) { - this._parents = [parent]; - } - else if (_parents.indexOf(parent) === -1) { - _parents.push(parent); - } - }; - Subscription.EMPTY = (function (empty) { - empty.closed = true; - return empty; - }(new Subscription())); - return Subscription; -}()); - -function flattenUnsubscriptionErrors(errors) { - return errors.reduce(function (errs, err) { return errs.concat((err instanceof __WEBPACK_IMPORTED_MODULE_5__util_UnsubscriptionError__["a" /* UnsubscriptionError */]) ? err.errors : err); }, []); -} -//# sourceMappingURL=Subscription.js.map - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright 2015 Joyent, Inc. - -module.exports = { - bufferSplit: bufferSplit, - addRSAMissing: addRSAMissing, - calculateDSAPublic: calculateDSAPublic, - calculateED25519Public: calculateED25519Public, - calculateX25519Public: calculateX25519Public, - mpNormalize: mpNormalize, - mpDenormalize: mpDenormalize, - ecNormalize: ecNormalize, - countZeros: countZeros, - assertCompatible: assertCompatible, - isCompatible: isCompatible, - opensslKeyDeriv: opensslKeyDeriv, - opensshCipherInfo: opensshCipherInfo, - publicFromPrivateECDSA: publicFromPrivateECDSA, - zeroPadToLength: zeroPadToLength, - writeBitString: writeBitString, - readBitString: readBitString -}; - -var assert = __webpack_require__(16); -var Buffer = __webpack_require__(15).Buffer; -var PrivateKey = __webpack_require__(33); -var Key = __webpack_require__(28); -var crypto = __webpack_require__(11); -var algs = __webpack_require__(32); -var asn1 = __webpack_require__(66); - -var ec, jsbn; -var nacl; - -var MAX_CLASS_DEPTH = 3; - -function isCompatible(obj, klass, needVer) { - if (obj === null || typeof (obj) !== 'object') - return (false); - if (needVer === undefined) - needVer = klass.prototype._sshpkApiVersion; - if (obj instanceof klass && - klass.prototype._sshpkApiVersion[0] == needVer[0]) - return (true); - var proto = Object.getPrototypeOf(obj); - var depth = 0; - while (proto.constructor.name !== klass.name) { - proto = Object.getPrototypeOf(proto); - if (!proto || ++depth > MAX_CLASS_DEPTH) - return (false); - } - if (proto.constructor.name !== klass.name) - return (false); - var ver = proto._sshpkApiVersion; - if (ver === undefined) - ver = klass._oldVersionDetect(obj); - if (ver[0] != needVer[0] || ver[1] < needVer[1]) - return (false); - return (true); -} - -function assertCompatible(obj, klass, needVer, name) { - if (name === undefined) - name = 'object'; - assert.ok(obj, name + ' must not be null'); - assert.object(obj, name + ' must be an object'); - if (needVer === undefined) - needVer = klass.prototype._sshpkApiVersion; - if (obj instanceof klass && - klass.prototype._sshpkApiVersion[0] == needVer[0]) - return; - var proto = Object.getPrototypeOf(obj); - var depth = 0; - while (proto.constructor.name !== klass.name) { - proto = Object.getPrototypeOf(proto); - assert.ok(proto && ++depth <= MAX_CLASS_DEPTH, - name + ' must be a ' + klass.name + ' instance'); - } - assert.strictEqual(proto.constructor.name, klass.name, - name + ' must be a ' + klass.name + ' instance'); - var ver = proto._sshpkApiVersion; - if (ver === undefined) - ver = klass._oldVersionDetect(obj); - assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1], - name + ' must be compatible with ' + klass.name + ' klass ' + - 'version ' + needVer[0] + '.' + needVer[1]); -} - -var CIPHER_LEN = { - 'des-ede3-cbc': { key: 7, iv: 8 }, - 'aes-128-cbc': { key: 16, iv: 16 } -}; -var PKCS5_SALT_LEN = 8; - -function opensslKeyDeriv(cipher, salt, passphrase, count) { - assert.buffer(salt, 'salt'); - assert.buffer(passphrase, 'passphrase'); - assert.number(count, 'iteration count'); - - var clen = CIPHER_LEN[cipher]; - assert.object(clen, 'supported cipher'); - - salt = salt.slice(0, PKCS5_SALT_LEN); - - var D, D_prev, bufs; - var material = Buffer.alloc(0); - while (material.length < clen.key + clen.iv) { - bufs = []; - if (D_prev) - bufs.push(D_prev); - bufs.push(passphrase); - bufs.push(salt); - D = Buffer.concat(bufs); - for (var j = 0; j < count; ++j) - D = crypto.createHash('md5').update(D).digest(); - material = Buffer.concat([material, D]); - D_prev = D; - } - - return ({ - key: material.slice(0, clen.key), - iv: material.slice(clen.key, clen.key + clen.iv) - }); -} - -/* Count leading zero bits on a buffer */ -function countZeros(buf) { - var o = 0, obit = 8; - while (o < buf.length) { - var mask = (1 << obit); - if ((buf[o] & mask) === mask) - break; - obit--; - if (obit < 0) { - o++; - obit = 8; - } - } - return (o*8 + (8 - obit) - 1); -} - -function bufferSplit(buf, chr) { - assert.buffer(buf); - assert.string(chr); - - var parts = []; - var lastPart = 0; - var matches = 0; - for (var i = 0; i < buf.length; ++i) { - if (buf[i] === chr.charCodeAt(matches)) - ++matches; - else if (buf[i] === chr.charCodeAt(0)) - matches = 1; - else - matches = 0; - - if (matches >= chr.length) { - var newPart = i + 1; - parts.push(buf.slice(lastPart, newPart - matches)); - lastPart = newPart; - matches = 0; - } - } - if (lastPart <= buf.length) - parts.push(buf.slice(lastPart, buf.length)); - - return (parts); -} - -function ecNormalize(buf, addZero) { - assert.buffer(buf); - if (buf[0] === 0x00 && buf[1] === 0x04) { - if (addZero) - return (buf); - return (buf.slice(1)); - } else if (buf[0] === 0x04) { - if (!addZero) - return (buf); - } else { - while (buf[0] === 0x00) - buf = buf.slice(1); - if (buf[0] === 0x02 || buf[0] === 0x03) - throw (new Error('Compressed elliptic curve points ' + - 'are not supported')); - if (buf[0] !== 0x04) - throw (new Error('Not a valid elliptic curve point')); - if (!addZero) - return (buf); - } - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x0; - buf.copy(b, 1); - return (b); -} - -function readBitString(der, tag) { - if (tag === undefined) - tag = asn1.Ber.BitString; - var buf = der.readString(tag, true); - assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' + - 'not supported (0x' + buf[0].toString(16) + ')'); - return (buf.slice(1)); -} - -function writeBitString(der, buf, tag) { - if (tag === undefined) - tag = asn1.Ber.BitString; - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x00; - buf.copy(b, 1); - der.writeBuffer(b, tag); -} - -function mpNormalize(buf) { - assert.buffer(buf); - while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00) - buf = buf.slice(1); - if ((buf[0] & 0x80) === 0x80) { - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x00; - buf.copy(b, 1); - buf = b; - } - return (buf); -} - -function mpDenormalize(buf) { - assert.buffer(buf); - while (buf.length > 1 && buf[0] === 0x00) - buf = buf.slice(1); - return (buf); -} - -function zeroPadToLength(buf, len) { - assert.buffer(buf); - assert.number(len); - while (buf.length > len) { - assert.equal(buf[0], 0x00); - buf = buf.slice(1); - } - while (buf.length < len) { - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x00; - buf.copy(b, 1); - buf = b; - } - return (buf); -} - -function bigintToMpBuf(bigint) { - var buf = Buffer.from(bigint.toByteArray()); - buf = mpNormalize(buf); - return (buf); -} - -function calculateDSAPublic(g, p, x) { - assert.buffer(g); - assert.buffer(p); - assert.buffer(x); - try { - var bigInt = __webpack_require__(81).BigInteger; - } catch (e) { - throw (new Error('To load a PKCS#8 format DSA private key, ' + - 'the node jsbn library is required.')); - } - g = new bigInt(g); - p = new bigInt(p); - x = new bigInt(x); - var y = g.modPow(x, p); - var ybuf = bigintToMpBuf(y); - return (ybuf); -} - -function calculateED25519Public(k) { - assert.buffer(k); - - if (nacl === undefined) - nacl = __webpack_require__(76); - - var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k)); - return (Buffer.from(kp.publicKey)); -} - -function calculateX25519Public(k) { - assert.buffer(k); - - if (nacl === undefined) - nacl = __webpack_require__(76); - - var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k)); - return (Buffer.from(kp.publicKey)); -} - -function addRSAMissing(key) { - assert.object(key); - assertCompatible(key, PrivateKey, [1, 1]); - try { - var bigInt = __webpack_require__(81).BigInteger; - } catch (e) { - throw (new Error('To write a PEM private key from ' + - 'this source, the node jsbn lib is required.')); - } - - var d = new bigInt(key.part.d.data); - var buf; - - if (!key.part.dmodp) { - var p = new bigInt(key.part.p.data); - var dmodp = d.mod(p.subtract(1)); - - buf = bigintToMpBuf(dmodp); - key.part.dmodp = {name: 'dmodp', data: buf}; - key.parts.push(key.part.dmodp); - } - if (!key.part.dmodq) { - var q = new bigInt(key.part.q.data); - var dmodq = d.mod(q.subtract(1)); - - buf = bigintToMpBuf(dmodq); - key.part.dmodq = {name: 'dmodq', data: buf}; - key.parts.push(key.part.dmodq); - } -} - -function publicFromPrivateECDSA(curveName, priv) { - assert.string(curveName, 'curveName'); - assert.buffer(priv); - if (ec === undefined) - ec = __webpack_require__(139); - if (jsbn === undefined) - jsbn = __webpack_require__(81).BigInteger; - var params = algs.curves[curveName]; - var p = new jsbn(params.p); - var a = new jsbn(params.a); - var b = new jsbn(params.b); - var curve = new ec.ECCurveFp(p, a, b); - var G = curve.decodePointHex(params.G.toString('hex')); - - var d = new jsbn(mpNormalize(priv)); - var pub = G.multiply(d); - pub = Buffer.from(curve.encodePointHex(pub), 'hex'); - - var parts = []; - parts.push({name: 'curve', data: Buffer.from(curveName)}); - parts.push({name: 'Q', data: pub}); - - var key = new Key({type: 'ecdsa', curve: curve, parts: parts}); - return (key); -} - -function opensshCipherInfo(cipher) { - var inf = {}; - switch (cipher) { - case '3des-cbc': - inf.keySize = 24; - inf.blockSize = 8; - inf.opensslName = 'des-ede3-cbc'; - break; - case 'blowfish-cbc': - inf.keySize = 16; - inf.blockSize = 8; - inf.opensslName = 'bf-cbc'; - break; - case 'aes128-cbc': - case 'aes128-ctr': - case 'aes128-gcm@openssh.com': - inf.keySize = 16; - inf.blockSize = 16; - inf.opensslName = 'aes-128-' + cipher.slice(7, 10); - break; - case 'aes192-cbc': - case 'aes192-ctr': - case 'aes192-gcm@openssh.com': - inf.keySize = 24; - inf.blockSize = 16; - inf.opensslName = 'aes-192-' + cipher.slice(7, 10); - break; - case 'aes256-cbc': - case 'aes256-ctr': - case 'aes256-gcm@openssh.com': - inf.keySize = 32; - inf.blockSize = 16; - inf.opensslName = 'aes-256-' + cipher.slice(7, 10); - break; - default: - throw (new Error( - 'Unsupported openssl cipher "' + cipher + '"')); - } - return (inf); -} - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const escapeStringRegexp = __webpack_require__(382); -const ansiStyles = __webpack_require__(474); -const stdoutColor = __webpack_require__(566).stdout; - -const template = __webpack_require__(567); - -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); - -const styles = Object.create(null); - -function applyOptions(obj, options) { - options = options || {}; - - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} - -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = Chalk; - - return chalk.template; - } - - applyOptions(this, options); -} - -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} - -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} - -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; - -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } - - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } - - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, styles); - -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder._empty = _empty; - - const self = this; - - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); - - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); - - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; - - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto - - return builder; -} - -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); - - if (argsLen === 0) { - return ''; - } - - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } - - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } - - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } - - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; - - return str; -} - -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } - - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; - - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } - - return template(chalk, parts.join('')); -} - -Object.defineProperties(Chalk.prototype, styles); - -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright 2017 Joyent, Inc. - -module.exports = Key; - -var assert = __webpack_require__(16); -var algs = __webpack_require__(32); -var crypto = __webpack_require__(11); -var Fingerprint = __webpack_require__(156); -var Signature = __webpack_require__(75); -var DiffieHellman = __webpack_require__(325).DiffieHellman; -var errs = __webpack_require__(74); -var utils = __webpack_require__(26); -var PrivateKey = __webpack_require__(33); -var edCompat; - -try { - edCompat = __webpack_require__(454); -} catch (e) { - /* Just continue through, and bail out if we try to use it. */ -} - -var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var KeyParseError = errs.KeyParseError; - -var formats = {}; -formats['auto'] = __webpack_require__(455); -formats['pem'] = __webpack_require__(86); -formats['pkcs1'] = __webpack_require__(327); -formats['pkcs8'] = __webpack_require__(157); -formats['rfc4253'] = __webpack_require__(103); -formats['ssh'] = __webpack_require__(456); -formats['ssh-private'] = __webpack_require__(193); -formats['openssh'] = formats['ssh-private']; -formats['dnssec'] = __webpack_require__(326); - -function Key(opts) { - assert.object(opts, 'options'); - assert.arrayOfObject(opts.parts, 'options.parts'); - assert.string(opts.type, 'options.type'); - assert.optionalString(opts.comment, 'options.comment'); - - var algInfo = algs.info[opts.type]; - if (typeof (algInfo) !== 'object') - throw (new InvalidAlgorithmError(opts.type)); - - var partLookup = {}; - for (var i = 0; i < opts.parts.length; ++i) { - var part = opts.parts[i]; - partLookup[part.name] = part; - } - - this.type = opts.type; - this.parts = opts.parts; - this.part = partLookup; - this.comment = undefined; - this.source = opts.source; - - /* for speeding up hashing/fingerprint operations */ - this._rfc4253Cache = opts._rfc4253Cache; - this._hashCache = {}; - - var sz; - this.curve = undefined; - if (this.type === 'ecdsa') { - var curve = this.part.curve.data.toString(); - this.curve = curve; - sz = algs.curves[curve].size; - } else if (this.type === 'ed25519' || this.type === 'curve25519') { - sz = 256; - this.curve = 'curve25519'; - } else { - var szPart = this.part[algInfo.sizePart]; - sz = szPart.data.length; - sz = sz * 8 - utils.countZeros(szPart.data); - } - this.size = sz; -} - -Key.formats = formats; - -Key.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'ssh'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); - - if (format === 'rfc4253') { - if (this._rfc4253Cache === undefined) - this._rfc4253Cache = formats['rfc4253'].write(this); - return (this._rfc4253Cache); - } - - return (formats[format].write(this, options)); -}; - -Key.prototype.toString = function (format, options) { - return (this.toBuffer(format, options).toString()); -}; - -Key.prototype.hash = function (algo) { - assert.string(algo, 'algorithm'); - algo = algo.toLowerCase(); - if (algs.hashAlgs[algo] === undefined) - throw (new InvalidAlgorithmError(algo)); - - if (this._hashCache[algo]) - return (this._hashCache[algo]); - var hash = crypto.createHash(algo). - update(this.toBuffer('rfc4253')).digest(); - this._hashCache[algo] = hash; - return (hash); -}; - -Key.prototype.fingerprint = function (algo) { - if (algo === undefined) - algo = 'sha256'; - assert.string(algo, 'algorithm'); - var opts = { - type: 'key', - hash: this.hash(algo), - algorithm: algo - }; - return (new Fingerprint(opts)); -}; - -Key.prototype.defaultHashAlgorithm = function () { - var hashAlgo = 'sha1'; - if (this.type === 'rsa') - hashAlgo = 'sha256'; - if (this.type === 'dsa' && this.size > 1024) - hashAlgo = 'sha256'; - if (this.type === 'ed25519') - hashAlgo = 'sha512'; - if (this.type === 'ecdsa') { - if (this.size <= 256) - hashAlgo = 'sha256'; - else if (this.size <= 384) - hashAlgo = 'sha384'; - else - hashAlgo = 'sha512'; - } - return (hashAlgo); -}; - -Key.prototype.createVerify = function (hashAlgo) { - if (hashAlgo === undefined) - hashAlgo = this.defaultHashAlgorithm(); - assert.string(hashAlgo, 'hash algorithm'); - - /* ED25519 is not supported by OpenSSL, use a javascript impl. */ - if (this.type === 'ed25519' && edCompat !== undefined) - return (new edCompat.Verifier(this, hashAlgo)); - if (this.type === 'curve25519') - throw (new Error('Curve25519 keys are not suitable for ' + - 'signing or verification')); - - var v, nm, err; - try { - nm = hashAlgo.toUpperCase(); - v = crypto.createVerify(nm); - } catch (e) { - err = e; - } - if (v === undefined || (err instanceof Error && - err.message.match(/Unknown message digest/))) { - nm = 'RSA-'; - nm += hashAlgo.toUpperCase(); - v = crypto.createVerify(nm); - } - assert.ok(v, 'failed to create verifier'); - var oldVerify = v.verify.bind(v); - var key = this.toBuffer('pkcs8'); - var curve = this.curve; - var self = this; - v.verify = function (signature, fmt) { - if (Signature.isSignature(signature, [2, 0])) { - if (signature.type !== self.type) - return (false); - if (signature.hashAlgorithm && - signature.hashAlgorithm !== hashAlgo) - return (false); - if (signature.curve && self.type === 'ecdsa' && - signature.curve !== curve) - return (false); - return (oldVerify(key, signature.toBuffer('asn1'))); - - } else if (typeof (signature) === 'string' || - Buffer.isBuffer(signature)) { - return (oldVerify(key, signature, fmt)); - - /* - * Avoid doing this on valid arguments, walking the prototype - * chain can be quite slow. - */ - } else if (Signature.isSignature(signature, [1, 0])) { - throw (new Error('signature was created by too old ' + - 'a version of sshpk and cannot be verified')); - - } else { - throw (new TypeError('signature must be a string, ' + - 'Buffer, or Signature object')); - } - }; - return (v); -}; - -Key.prototype.createDiffieHellman = function () { - if (this.type === 'rsa') - throw (new Error('RSA keys do not support Diffie-Hellman')); - - return (new DiffieHellman(this)); -}; -Key.prototype.createDH = Key.prototype.createDiffieHellman; - -Key.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; - - assert.object(formats[format], 'formats[format]'); - - try { - var k = formats[format].read(data, options); - if (k instanceof PrivateKey) - k = k.toPublic(); - if (!k.comment) - k.comment = options.filename; - return (k); - } catch (e) { - if (e.name === 'KeyEncryptedError') - throw (e); - throw (new KeyParseError(options.filename, format, e)); - } -}; - -Key.isKey = function (obj, ver) { - return (utils.isCompatible(obj, Key, ver)); -}; - -/* - * API versions for Key: - * [1,0] -- initial ver, may take Signature for createVerify or may not - * [1,1] -- added pkcs1, pkcs8 formats - * [1,2] -- added auto, ssh-private, openssh formats - * [1,3] -- added defaultHashAlgorithm - * [1,4] -- added ed support, createDH - * [1,5] -- first explicitly tagged version - * [1,6] -- changed ed25519 part names - */ -Key.prototype._sshpkApiVersion = [1, 6]; - -Key._oldVersionDetect = function (obj) { - assert.func(obj.toBuffer); - assert.func(obj.fingerprint); - if (obj.createDH) - return ([1, 4]); - if (obj.defaultHashAlgorithm) - return ([1, 3]); - if (obj.formats['auto']) - return ([1, 2]); - if (obj.formats['pkcs1']) - return ([1, 1]); - return ([1, 0]); -}; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports) { - -module.exports = require("assert"); - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = nullify; -function nullify(obj = {}) { - if (Array.isArray(obj)) { - for (var _iterator = obj, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - const item = _ref; - - nullify(item); - } - } else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') { - Object.setPrototypeOf(obj, null); - - // for..in can only be applied to 'object', not 'function' - if (typeof obj === 'object') { - for (const key in obj) { - nullify(obj[key]); - } - } - } - - return obj; -} - -/***/ }), -/* 31 */ -/***/ (function(module, exports) { - -var core = module.exports = { version: '2.5.7' }; -if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright 2015 Joyent, Inc. - -var Buffer = __webpack_require__(15).Buffer; - -var algInfo = { - 'dsa': { - parts: ['p', 'q', 'g', 'y'], - sizePart: 'p' - }, - 'rsa': { - parts: ['e', 'n'], - sizePart: 'n' - }, - 'ecdsa': { - parts: ['curve', 'Q'], - sizePart: 'Q' - }, - 'ed25519': { - parts: ['A'], - sizePart: 'A' - } -}; -algInfo['curve25519'] = algInfo['ed25519']; - -var algPrivInfo = { - 'dsa': { - parts: ['p', 'q', 'g', 'y', 'x'] - }, - 'rsa': { - parts: ['n', 'e', 'd', 'iqmp', 'p', 'q'] - }, - 'ecdsa': { - parts: ['curve', 'Q', 'd'] - }, - 'ed25519': { - parts: ['A', 'k'] - } -}; -algPrivInfo['curve25519'] = algPrivInfo['ed25519']; - -var hashAlgs = { - 'md5': true, - 'sha1': true, - 'sha256': true, - 'sha384': true, - 'sha512': true -}; - -/* - * Taken from - * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf - */ -var curves = { - 'nistp256': { - size: 256, - pkcs8oid: '1.2.840.10045.3.1.7', - p: Buffer.from(('00' + - 'ffffffff 00000001 00000000 00000000' + - '00000000 ffffffff ffffffff ffffffff'). - replace(/ /g, ''), 'hex'), - a: Buffer.from(('00' + - 'FFFFFFFF 00000001 00000000 00000000' + - '00000000 FFFFFFFF FFFFFFFF FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: Buffer.from(( - '5ac635d8 aa3a93e7 b3ebbd55 769886bc' + - '651d06b0 cc53b0f6 3bce3c3e 27d2604b'). - replace(/ /g, ''), 'hex'), - s: Buffer.from(('00' + - 'c49d3608 86e70493 6a6678e1 139d26b7' + - '819f7e90'). - replace(/ /g, ''), 'hex'), - n: Buffer.from(('00' + - 'ffffffff 00000000 ffffffff ffffffff' + - 'bce6faad a7179e84 f3b9cac2 fc632551'). - replace(/ /g, ''), 'hex'), - G: Buffer.from(('04' + - '6b17d1f2 e12c4247 f8bce6e5 63a440f2' + - '77037d81 2deb33a0 f4a13945 d898c296' + - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' + - '2bce3357 6b315ece cbb64068 37bf51f5'). - replace(/ /g, ''), 'hex') - }, - 'nistp384': { - size: 384, - pkcs8oid: '1.3.132.0.34', - p: Buffer.from(('00' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff fffffffe' + - 'ffffffff 00000000 00000000 ffffffff'). - replace(/ /g, ''), 'hex'), - a: Buffer.from(('00' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' + - 'FFFFFFFF 00000000 00000000 FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: Buffer.from(( - 'b3312fa7 e23ee7e4 988e056b e3f82d19' + - '181d9c6e fe814112 0314088f 5013875a' + - 'c656398d 8a2ed19d 2a85c8ed d3ec2aef'). - replace(/ /g, ''), 'hex'), - s: Buffer.from(('00' + - 'a335926a a319a27a 1d00896a 6773a482' + - '7acdac73'). - replace(/ /g, ''), 'hex'), - n: Buffer.from(('00' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff c7634d81 f4372ddf' + - '581a0db2 48b0a77a ecec196a ccc52973'). - replace(/ /g, ''), 'hex'), - G: Buffer.from(('04' + - 'aa87ca22 be8b0537 8eb1c71e f320ad74' + - '6e1d3b62 8ba79b98 59f741e0 82542a38' + - '5502f25d bf55296c 3a545e38 72760ab7' + - '3617de4a 96262c6f 5d9e98bf 9292dc29' + - 'f8f41dbd 289a147c e9da3113 b5f0b8c0' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'). - replace(/ /g, ''), 'hex') - }, - 'nistp521': { - size: 521, - pkcs8oid: '1.3.132.0.35', - p: Buffer.from(( - '01ffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffff').replace(/ /g, ''), 'hex'), - a: Buffer.from(('01FF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: Buffer.from(('51' + - '953eb961 8e1c9a1f 929a21a0 b68540ee' + - 'a2da725b 99b315f3 b8b48991 8ef109e1' + - '56193951 ec7e937b 1652c0bd 3bb1bf07' + - '3573df88 3d2c34f1 ef451fd4 6b503f00'). - replace(/ /g, ''), 'hex'), - s: Buffer.from(('00' + - 'd09e8800 291cb853 96cc6717 393284aa' + - 'a0da64ba').replace(/ /g, ''), 'hex'), - n: Buffer.from(('01ff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff fffffffa' + - '51868783 bf2f966b 7fcc0148 f709a5d0' + - '3bb5c9b8 899c47ae bb6fb71e 91386409'). - replace(/ /g, ''), 'hex'), - G: Buffer.from(('04' + - '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' + - '9c648139 053fb521 f828af60 6b4d3dba' + - 'a14b5e77 efe75928 fe1dc127 a2ffa8de' + - '3348b3c1 856a429b f97e7e31 c2e5bd66' + - '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' + - '98f54449 579b4468 17afbd17 273e662c' + - '97ee7299 5ef42640 c550b901 3fad0761' + - '353c7086 a272c240 88be9476 9fd16650'). - replace(/ /g, ''), 'hex') - } -}; - -module.exports = { - info: algInfo, - privInfo: algPrivInfo, - hashAlgs: hashAlgs, - curves: curves -}; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright 2017 Joyent, Inc. - -module.exports = PrivateKey; - -var assert = __webpack_require__(16); -var Buffer = __webpack_require__(15).Buffer; -var algs = __webpack_require__(32); -var crypto = __webpack_require__(11); -var Fingerprint = __webpack_require__(156); -var Signature = __webpack_require__(75); -var errs = __webpack_require__(74); -var util = __webpack_require__(3); -var utils = __webpack_require__(26); -var dhe = __webpack_require__(325); -var generateECDSA = dhe.generateECDSA; -var generateED25519 = dhe.generateED25519; -var edCompat; -var nacl; - -try { - edCompat = __webpack_require__(454); -} catch (e) { - /* Just continue through, and bail out if we try to use it. */ -} - -var Key = __webpack_require__(28); - -var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var KeyParseError = errs.KeyParseError; -var KeyEncryptedError = errs.KeyEncryptedError; - -var formats = {}; -formats['auto'] = __webpack_require__(455); -formats['pem'] = __webpack_require__(86); -formats['pkcs1'] = __webpack_require__(327); -formats['pkcs8'] = __webpack_require__(157); -formats['rfc4253'] = __webpack_require__(103); -formats['ssh-private'] = __webpack_require__(193); -formats['openssh'] = formats['ssh-private']; -formats['ssh'] = formats['ssh-private']; -formats['dnssec'] = __webpack_require__(326); - -function PrivateKey(opts) { - assert.object(opts, 'options'); - Key.call(this, opts); - - this._pubCache = undefined; -} -util.inherits(PrivateKey, Key); - -PrivateKey.formats = formats; - -PrivateKey.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'pkcs1'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); - - return (formats[format].write(this, options)); -}; - -PrivateKey.prototype.hash = function (algo) { - return (this.toPublic().hash(algo)); -}; - -PrivateKey.prototype.toPublic = function () { - if (this._pubCache) - return (this._pubCache); - - var algInfo = algs.info[this.type]; - var pubParts = []; - for (var i = 0; i < algInfo.parts.length; ++i) { - var p = algInfo.parts[i]; - pubParts.push(this.part[p]); - } - - this._pubCache = new Key({ - type: this.type, - source: this, - parts: pubParts - }); - if (this.comment) - this._pubCache.comment = this.comment; - return (this._pubCache); -}; - -PrivateKey.prototype.derive = function (newType) { - assert.string(newType, 'type'); - var priv, pub, pair; - - if (this.type === 'ed25519' && newType === 'curve25519') { - if (nacl === undefined) - nacl = __webpack_require__(76); - - priv = this.part.k.data; - if (priv[0] === 0x00) - priv = priv.slice(1); - - pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv)); - pub = Buffer.from(pair.publicKey); - - return (new PrivateKey({ - type: 'curve25519', - parts: [ - { name: 'A', data: utils.mpNormalize(pub) }, - { name: 'k', data: utils.mpNormalize(priv) } - ] - })); - } else if (this.type === 'curve25519' && newType === 'ed25519') { - if (nacl === undefined) - nacl = __webpack_require__(76); - - priv = this.part.k.data; - if (priv[0] === 0x00) - priv = priv.slice(1); - - pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv)); - pub = Buffer.from(pair.publicKey); - - return (new PrivateKey({ - type: 'ed25519', - parts: [ - { name: 'A', data: utils.mpNormalize(pub) }, - { name: 'k', data: utils.mpNormalize(priv) } - ] - })); - } - throw (new Error('Key derivation not supported from ' + this.type + - ' to ' + newType)); -}; - -PrivateKey.prototype.createVerify = function (hashAlgo) { - return (this.toPublic().createVerify(hashAlgo)); -}; - -PrivateKey.prototype.createSign = function (hashAlgo) { - if (hashAlgo === undefined) - hashAlgo = this.defaultHashAlgorithm(); - assert.string(hashAlgo, 'hash algorithm'); - - /* ED25519 is not supported by OpenSSL, use a javascript impl. */ - if (this.type === 'ed25519' && edCompat !== undefined) - return (new edCompat.Signer(this, hashAlgo)); - if (this.type === 'curve25519') - throw (new Error('Curve25519 keys are not suitable for ' + - 'signing or verification')); - - var v, nm, err; - try { - nm = hashAlgo.toUpperCase(); - v = crypto.createSign(nm); - } catch (e) { - err = e; - } - if (v === undefined || (err instanceof Error && - err.message.match(/Unknown message digest/))) { - nm = 'RSA-'; - nm += hashAlgo.toUpperCase(); - v = crypto.createSign(nm); - } - assert.ok(v, 'failed to create verifier'); - var oldSign = v.sign.bind(v); - var key = this.toBuffer('pkcs1'); - var type = this.type; - var curve = this.curve; - v.sign = function () { - var sig = oldSign(key); - if (typeof (sig) === 'string') - sig = Buffer.from(sig, 'binary'); - sig = Signature.parse(sig, type, 'asn1'); - sig.hashAlgorithm = hashAlgo; - sig.curve = curve; - return (sig); - }; - return (v); -}; - -PrivateKey.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; - - assert.object(formats[format], 'formats[format]'); - - try { - var k = formats[format].read(data, options); - assert.ok(k instanceof PrivateKey, 'key is not a private key'); - if (!k.comment) - k.comment = options.filename; - return (k); - } catch (e) { - if (e.name === 'KeyEncryptedError') - throw (e); - throw (new KeyParseError(options.filename, format, e)); - } -}; - -PrivateKey.isPrivateKey = function (obj, ver) { - return (utils.isCompatible(obj, PrivateKey, ver)); -}; - -PrivateKey.generate = function (type, options) { - if (options === undefined) - options = {}; - assert.object(options, 'options'); - - switch (type) { - case 'ecdsa': - if (options.curve === undefined) - options.curve = 'nistp256'; - assert.string(options.curve, 'options.curve'); - return (generateECDSA(options.curve)); - case 'ed25519': - return (generateED25519()); - default: - throw (new Error('Key generation not supported with key ' + - 'type "' + type + '"')); - } -}; - -/* - * API versions for PrivateKey: - * [1,0] -- initial ver - * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats - * [1,2] -- added defaultHashAlgorithm - * [1,3] -- added derive, ed, createDH - * [1,4] -- first tagged version - * [1,5] -- changed ed25519 part names and format - */ -PrivateKey.prototype._sshpkApiVersion = [1, 5]; - -PrivateKey._oldVersionDetect = function (obj) { - assert.func(obj.toPublic); - assert.func(obj.createSign); - if (obj.derive) - return ([1, 3]); - if (obj.defaultHashAlgorithm) - return ([1, 2]); - if (obj.formats['auto']) - return ([1, 1]); - return ([1, 0]); -}; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.wrapLifecycle = exports.run = exports.install = exports.Install = undefined; - -var _extends2; - -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(20)); -} - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(2)); -} - -let install = exports.install = (() => { - var _ref29 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, lockfile) { - yield wrapLifecycle(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const install = new Install(flags, config, reporter, lockfile); - yield install.init(); - })); - }); - - return function install(_x7, _x8, _x9, _x10) { - return _ref29.apply(this, arguments); - }; -})(); - -let run = exports.run = (() => { - var _ref31 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - let lockfile; - let error = 'installCommandRenamed'; - if (flags.lockfile === false) { - lockfile = new (_lockfile || _load_lockfile()).default(); - } else { - lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder, reporter); - } - - if (args.length) { - const exampleArgs = args.slice(); - - if (flags.saveDev) { - exampleArgs.push('--dev'); - } - if (flags.savePeer) { - exampleArgs.push('--peer'); - } - if (flags.saveOptional) { - exampleArgs.push('--optional'); - } - if (flags.saveExact) { - exampleArgs.push('--exact'); - } - if (flags.saveTilde) { - exampleArgs.push('--tilde'); - } - let command = 'add'; - if (flags.global) { - error = 'globalFlagRemoved'; - command = 'global add'; - } - throw new (_errors || _load_errors()).MessageError(reporter.lang(error, `yarn ${command} ${exampleArgs.join(' ')}`)); - } - - yield install(config, reporter, flags, lockfile); - }); - - return function run(_x11, _x12, _x13, _x14) { - return _ref31.apply(this, arguments); - }; -})(); - -let wrapLifecycle = exports.wrapLifecycle = (() => { - var _ref32 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags, factory) { - yield config.executeLifecycleScript('preinstall'); - - yield factory(); - - // npm behaviour, seems kinda funky but yay compatibility - yield config.executeLifecycleScript('install'); - yield config.executeLifecycleScript('postinstall'); - - if (!config.production) { - if (!config.disablePrepublish) { - yield config.executeLifecycleScript('prepublish'); - } - yield config.executeLifecycleScript('prepare'); - } - }); - - return function wrapLifecycle(_x15, _x16, _x17) { - return _ref32.apply(this, arguments); - }; -})(); - -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; - -var _objectPath; - -function _load_objectPath() { - return _objectPath = _interopRequireDefault(__webpack_require__(304)); -} - -var _hooks; - -function _load_hooks() { - return _hooks = __webpack_require__(368); -} - -var _index; - -function _load_index() { - return _index = _interopRequireDefault(__webpack_require__(218)); -} - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(6); -} - -var _integrityChecker; - -function _load_integrityChecker() { - return _integrityChecker = _interopRequireDefault(__webpack_require__(206)); -} - -var _lockfile; - -function _load_lockfile() { - return _lockfile = _interopRequireDefault(__webpack_require__(19)); -} - -var _lockfile2; - -function _load_lockfile2() { - return _lockfile2 = __webpack_require__(19); -} - -var _packageFetcher; - -function _load_packageFetcher() { - return _packageFetcher = _interopRequireWildcard(__webpack_require__(208)); -} - -var _packageInstallScripts; - -function _load_packageInstallScripts() { - return _packageInstallScripts = _interopRequireDefault(__webpack_require__(525)); -} - -var _packageCompatibility; - -function _load_packageCompatibility() { - return _packageCompatibility = _interopRequireWildcard(__webpack_require__(207)); -} - -var _packageResolver; - -function _load_packageResolver() { - return _packageResolver = _interopRequireDefault(__webpack_require__(360)); -} - -var _packageLinker; - -function _load_packageLinker() { - return _packageLinker = _interopRequireDefault(__webpack_require__(209)); -} - -var _index2; - -function _load_index2() { - return _index2 = __webpack_require__(58); -} - -var _index3; - -function _load_index3() { - return _index3 = __webpack_require__(78); -} - -var _autoclean; - -function _load_autoclean() { - return _autoclean = __webpack_require__(348); -} - -var _constants; - -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} - -var _normalizePattern; - -function _load_normalizePattern() { - return _normalizePattern = __webpack_require__(37); -} - -var _fs; - -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(5)); -} - -var _map; - -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(30)); -} - -var _yarnVersion; - -function _load_yarnVersion() { - return _yarnVersion = __webpack_require__(105); -} - -var _generatePnpMap; - -function _load_generatePnpMap() { - return _generatePnpMap = __webpack_require__(547); -} - -var _workspaceLayout; - -function _load_workspaceLayout() { - return _workspaceLayout = _interopRequireDefault(__webpack_require__(90)); -} - -var _resolutionMap; - -function _load_resolutionMap() { - return _resolutionMap = _interopRequireDefault(__webpack_require__(212)); -} - -var _guessName; - -function _load_guessName() { - return _guessName = _interopRequireDefault(__webpack_require__(169)); -} - -var _audit; - -function _load_audit() { - return _audit = _interopRequireDefault(__webpack_require__(347)); -} - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const deepEqual = __webpack_require__(599); - -const emoji = __webpack_require__(302); -const invariant = __webpack_require__(9); -const path = __webpack_require__(0); -const semver = __webpack_require__(22); -const uuid = __webpack_require__(120); -const ssri = __webpack_require__(65); - -const ONE_DAY = 1000 * 60 * 60 * 24; - -/** - * Try and detect the installation method for Yarn and provide a command to update it with. - */ - -function getUpdateCommand(installationMethod) { - if (installationMethod === 'tar') { - return `curl --compressed -o- -L ${(_constants || _load_constants()).YARN_INSTALLER_SH} | bash`; - } - - if (installationMethod === 'homebrew') { - return 'brew upgrade yarn'; - } - - if (installationMethod === 'deb') { - return 'sudo apt-get update && sudo apt-get install yarn'; - } - - if (installationMethod === 'rpm') { - return 'sudo yum install yarn'; - } - - if (installationMethod === 'npm') { - return 'npm install --global yarn'; - } - - if (installationMethod === 'chocolatey') { - return 'choco upgrade yarn'; - } - - if (installationMethod === 'apk') { - return 'apk update && apk add -u yarn'; - } - - if (installationMethod === 'portage') { - return 'sudo emerge --sync && sudo emerge -au sys-apps/yarn'; - } - - return null; -} - -function getUpdateInstaller(installationMethod) { - // Windows - if (installationMethod === 'msi') { - return (_constants || _load_constants()).YARN_INSTALLER_MSI; - } - - return null; -} - -function normalizeFlags(config, rawFlags) { - const flags = { - // install - har: !!rawFlags.har, - ignorePlatform: !!rawFlags.ignorePlatform, - ignoreEngines: !!rawFlags.ignoreEngines, - ignoreScripts: !!rawFlags.ignoreScripts, - ignoreOptional: !!rawFlags.ignoreOptional, - force: !!rawFlags.force, - flat: !!rawFlags.flat, - lockfile: rawFlags.lockfile !== false, - pureLockfile: !!rawFlags.pureLockfile, - updateChecksums: !!rawFlags.updateChecksums, - skipIntegrityCheck: !!rawFlags.skipIntegrityCheck, - frozenLockfile: !!rawFlags.frozenLockfile, - linkDuplicates: !!rawFlags.linkDuplicates, - checkFiles: !!rawFlags.checkFiles, - audit: !!rawFlags.audit, - - // add - peer: !!rawFlags.peer, - dev: !!rawFlags.dev, - optional: !!rawFlags.optional, - exact: !!rawFlags.exact, - tilde: !!rawFlags.tilde, - ignoreWorkspaceRootCheck: !!rawFlags.ignoreWorkspaceRootCheck, - - // outdated, update-interactive - includeWorkspaceDeps: !!rawFlags.includeWorkspaceDeps, - - // add, remove, update - workspaceRootIsCwd: rawFlags.workspaceRootIsCwd !== false - }; - - if (config.getOption('ignore-scripts')) { - flags.ignoreScripts = true; - } - - if (config.getOption('ignore-platform')) { - flags.ignorePlatform = true; - } - - if (config.getOption('ignore-engines')) { - flags.ignoreEngines = true; - } - - if (config.getOption('ignore-optional')) { - flags.ignoreOptional = true; - } - - if (config.getOption('force')) { - flags.force = true; - } - - return flags; -} - -class Install { - constructor(flags, config, reporter, lockfile) { - this.rootManifestRegistries = []; - this.rootPatternsToOrigin = (0, (_map || _load_map()).default)(); - this.lockfile = lockfile; - this.reporter = reporter; - this.config = config; - this.flags = normalizeFlags(config, flags); - this.resolutions = (0, (_map || _load_map()).default)(); // Legacy resolutions field used for flat install mode - this.resolutionMap = new (_resolutionMap || _load_resolutionMap()).default(config); // Selective resolutions for nested dependencies - this.resolver = new (_packageResolver || _load_packageResolver()).default(config, lockfile, this.resolutionMap); - this.integrityChecker = new (_integrityChecker || _load_integrityChecker()).default(config); - this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver); - this.scripts = new (_packageInstallScripts || _load_packageInstallScripts()).default(config, this.resolver, this.flags.force); - } - - /** - * Create a list of dependency requests from the current directories manifests. - */ - - fetchRequestFromCwd(excludePatterns = [], ignoreUnusedPatterns = false) { - var _this = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const patterns = []; - const deps = []; - let resolutionDeps = []; - const manifest = {}; - - const ignorePatterns = []; - const usedPatterns = []; - let workspaceLayout; - - // some commands should always run in the context of the entire workspace - const cwd = _this.flags.includeWorkspaceDeps || _this.flags.workspaceRootIsCwd ? _this.config.lockfileFolder : _this.config.cwd; - - // non-workspaces are always root, otherwise check for workspace root - const cwdIsRoot = !_this.config.workspaceRootFolder || _this.config.lockfileFolder === cwd; - - // exclude package names that are in install args - const excludeNames = []; - for (var _iterator = excludePatterns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - const pattern = _ref; - - if ((0, (_index3 || _load_index3()).getExoticResolver)(pattern)) { - excludeNames.push((0, (_guessName || _load_guessName()).default)(pattern)); - } else { - // extract the name - const parts = (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern); - excludeNames.push(parts.name); - } - } - - const stripExcluded = function stripExcluded(manifest) { - for (var _iterator2 = excludeNames, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - const exclude = _ref2; - - if (manifest.dependencies && manifest.dependencies[exclude]) { - delete manifest.dependencies[exclude]; - } - if (manifest.devDependencies && manifest.devDependencies[exclude]) { - delete manifest.devDependencies[exclude]; - } - if (manifest.optionalDependencies && manifest.optionalDependencies[exclude]) { - delete manifest.optionalDependencies[exclude]; - } - } - }; - - for (var _iterator3 = Object.keys((_index2 || _load_index2()).registries), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - const registry = _ref3; - - const filename = (_index2 || _load_index2()).registries[registry].filename; - - const loc = path.join(cwd, filename); - if (!(yield (_fs || _load_fs()).exists(loc))) { - continue; - } - - _this.rootManifestRegistries.push(registry); - - const projectManifestJson = yield _this.config.readJson(loc); - yield (0, (_index || _load_index()).default)(projectManifestJson, cwd, _this.config, cwdIsRoot); - - Object.assign(_this.resolutions, projectManifestJson.resolutions); - Object.assign(manifest, projectManifestJson); - - _this.resolutionMap.init(_this.resolutions); - for (var _iterator4 = Object.keys(_this.resolutionMap.resolutionsByPackage), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - const packageName = _ref4; - - const optional = (_objectPath || _load_objectPath()).default.has(manifest.optionalDependencies, packageName) && _this.flags.ignoreOptional; - for (var _iterator8 = _this.resolutionMap.resolutionsByPackage[packageName], _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) { - var _ref9; - - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref9 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref9 = _i8.value; - } - - const _ref8 = _ref9; - const pattern = _ref8.pattern; - - resolutionDeps = [...resolutionDeps, { registry, pattern, optional, hint: 'resolution' }]; - } - } - - const pushDeps = function pushDeps(depType, manifest, { hint, optional }, isUsed) { - if (ignoreUnusedPatterns && !isUsed) { - return; - } - // We only take unused dependencies into consideration to get deterministic hoisting. - // Since flat mode doesn't care about hoisting and everything is top level and specified then we can safely - // leave these out. - if (_this.flags.flat && !isUsed) { - return; - } - const depMap = manifest[depType]; - for (const name in depMap) { - if (excludeNames.indexOf(name) >= 0) { - continue; - } - - let pattern = name; - if (!_this.lockfile.getLocked(pattern)) { - // when we use --save we save the dependency to the lockfile with just the name rather than the - // version combo - pattern += '@' + depMap[name]; - } - - // normalization made sure packages are mentioned only once - if (isUsed) { - usedPatterns.push(pattern); - } else { - ignorePatterns.push(pattern); - } - - _this.rootPatternsToOrigin[pattern] = depType; - patterns.push(pattern); - deps.push({ pattern, registry, hint, optional, workspaceName: manifest.name, workspaceLoc: manifest._loc }); - } - }; - - if (cwdIsRoot) { - pushDeps('dependencies', projectManifestJson, { hint: null, optional: false }, true); - pushDeps('devDependencies', projectManifestJson, { hint: 'dev', optional: false }, !_this.config.production); - pushDeps('optionalDependencies', projectManifestJson, { hint: 'optional', optional: true }, true); - } - - if (_this.config.workspaceRootFolder) { - const workspaceLoc = cwdIsRoot ? loc : path.join(_this.config.lockfileFolder, filename); - const workspacesRoot = path.dirname(workspaceLoc); - - let workspaceManifestJson = projectManifestJson; - if (!cwdIsRoot) { - // the manifest we read before was a child workspace, so get the root - workspaceManifestJson = yield _this.config.readJson(workspaceLoc); - yield (0, (_index || _load_index()).default)(workspaceManifestJson, workspacesRoot, _this.config, true); - } - - const workspaces = yield _this.config.resolveWorkspaces(workspacesRoot, workspaceManifestJson); - workspaceLayout = new (_workspaceLayout || _load_workspaceLayout()).default(workspaces, _this.config); - - // add virtual manifest that depends on all workspaces, this way package hoisters and resolvers will work fine - const workspaceDependencies = (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.dependencies); - for (var _iterator5 = Object.keys(workspaces), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - const workspaceName = _ref5; - - const workspaceManifest = workspaces[workspaceName].manifest; - workspaceDependencies[workspaceName] = workspaceManifest.version; - - // include dependencies from all workspaces - if (_this.flags.includeWorkspaceDeps) { - pushDeps('dependencies', workspaceManifest, { hint: null, optional: false }, true); - pushDeps('devDependencies', workspaceManifest, { hint: 'dev', optional: false }, !_this.config.production); - pushDeps('optionalDependencies', workspaceManifest, { hint: 'optional', optional: true }, true); - } - } - const virtualDependencyManifest = { - _uid: '', - name: `workspace-aggregator-${uuid.v4()}`, - version: '1.0.0', - _registry: 'npm', - _loc: workspacesRoot, - dependencies: workspaceDependencies, - devDependencies: (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.devDependencies), - optionalDependencies: (0, (_extends2 || _load_extends()).default)({}, workspaceManifestJson.optionalDependencies), - private: workspaceManifestJson.private, - workspaces: workspaceManifestJson.workspaces - }; - workspaceLayout.virtualManifestName = virtualDependencyManifest.name; - const virtualDep = {}; - virtualDep[virtualDependencyManifest.name] = virtualDependencyManifest.version; - workspaces[virtualDependencyManifest.name] = { loc: workspacesRoot, manifest: virtualDependencyManifest }; - - // ensure dependencies that should be excluded are stripped from the correct manifest - stripExcluded(cwdIsRoot ? virtualDependencyManifest : workspaces[projectManifestJson.name].manifest); - - pushDeps('workspaces', { workspaces: virtualDep }, { hint: 'workspaces', optional: false }, true); - - const implicitWorkspaceDependencies = (0, (_extends2 || _load_extends()).default)({}, workspaceDependencies); - - for (var _iterator6 = (_constants || _load_constants()).OWNED_DEPENDENCY_TYPES, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) { - var _ref6; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } - - const type = _ref6; - - for (var _iterator7 = Object.keys(projectManifestJson[type] || {}), _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) { - var _ref7; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } - - const dependencyName = _ref7; - - delete implicitWorkspaceDependencies[dependencyName]; - } - } - - pushDeps('dependencies', { dependencies: implicitWorkspaceDependencies }, { hint: 'workspaces', optional: false }, true); - } - - break; - } - - // inherit root flat flag - if (manifest.flat) { - _this.flags.flat = true; - } - - return { - requests: [...resolutionDeps, ...deps], - patterns, - manifest, - usedPatterns, - ignorePatterns, - workspaceLayout - }; - })(); - } - - /** - * TODO description - */ - - prepareRequests(requests) { - return requests; - } - - preparePatterns(patterns) { - return patterns; - } - preparePatternsForLinking(patterns, cwdManifest, cwdIsRoot) { - return patterns; - } - - prepareManifests() { - var _this2 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const manifests = yield _this2.config.getRootManifests(); - return manifests; - })(); - } - - bailout(patterns, workspaceLayout) { - var _this3 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // We don't want to skip the audit - it could yield important errors - if (_this3.flags.audit) { - return false; - } - // PNP is so fast that the integrity check isn't pertinent - if (_this3.config.plugnplayEnabled) { - return false; - } - if (_this3.flags.skipIntegrityCheck || _this3.flags.force) { - return false; - } - const lockfileCache = _this3.lockfile.cache; - if (!lockfileCache) { - return false; - } - const lockfileClean = _this3.lockfile.parseResultType === 'success'; - const match = yield _this3.integrityChecker.check(patterns, lockfileCache, _this3.flags, workspaceLayout); - if (_this3.flags.frozenLockfile && (!lockfileClean || match.missingPatterns.length > 0)) { - throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('frozenLockfileError')); - } - - const haveLockfile = yield (_fs || _load_fs()).exists(path.join(_this3.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME)); - - const lockfileIntegrityPresent = !_this3.lockfile.hasEntriesExistWithoutIntegrity(); - const integrityBailout = lockfileIntegrityPresent || !_this3.config.autoAddIntegrity; - - if (match.integrityMatches && haveLockfile && lockfileClean && integrityBailout) { - _this3.reporter.success(_this3.reporter.lang('upToDate')); - return true; - } - - if (match.integrityFileMissing && haveLockfile) { - // Integrity file missing, force script installations - _this3.scripts.setForce(true); - return false; - } - - if (match.hardRefreshRequired) { - // e.g. node version doesn't match, force script installations - _this3.scripts.setForce(true); - return false; - } - - if (!patterns.length && !match.integrityFileMissing) { - _this3.reporter.success(_this3.reporter.lang('nothingToInstall')); - yield _this3.createEmptyManifestFolders(); - yield _this3.saveLockfileAndIntegrity(patterns, workspaceLayout); - return true; - } - - return false; - })(); - } - - /** - * Produce empty folders for all used root manifests. - */ - - createEmptyManifestFolders() { - var _this4 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (_this4.config.modulesFolder) { - // already created - return; - } - - for (var _iterator9 = _this4.rootManifestRegistries, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) { - var _ref10; - - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref10 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref10 = _i9.value; - } - - const registryName = _ref10; - const folder = _this4.config.registries[registryName].folder; - - yield (_fs || _load_fs()).mkdirp(path.join(_this4.config.lockfileFolder, folder)); - } - })(); - } - - /** - * TODO description - */ - - markIgnored(patterns) { - for (var _iterator10 = patterns, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) { - var _ref11; - - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref11 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref11 = _i10.value; - } - - const pattern = _ref11; - - const manifest = this.resolver.getStrictResolvedPattern(pattern); - const ref = manifest._reference; - invariant(ref, 'expected package reference'); - - // just mark the package as ignored. if the package is used by a required package, the hoister - // will take care of that. - ref.ignore = true; - } - } - - /** - * helper method that gets only recent manifests - * used by global.ls command - */ - getFlattenedDeps() { - var _this5 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - var _ref12 = yield _this5.fetchRequestFromCwd(); - - const depRequests = _ref12.requests, - rawPatterns = _ref12.patterns; - - - yield _this5.resolver.init(depRequests, {}); - - const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this5.resolver.getManifests(), _this5.config); - _this5.resolver.updateManifests(manifests); - - return _this5.flatten(rawPatterns); - })(); - } - - /** - * TODO description - */ - - init() { - var _this6 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this6.checkUpdate(); - - // warn if we have a shrinkwrap - if (yield (_fs || _load_fs()).exists(path.join(_this6.config.lockfileFolder, (_constants || _load_constants()).NPM_SHRINKWRAP_FILENAME))) { - _this6.reporter.warn(_this6.reporter.lang('shrinkwrapWarning')); - } - - // warn if we have an npm lockfile - if (yield (_fs || _load_fs()).exists(path.join(_this6.config.lockfileFolder, (_constants || _load_constants()).NPM_LOCK_FILENAME))) { - _this6.reporter.warn(_this6.reporter.lang('npmLockfileWarning')); - } - - if (_this6.config.plugnplayEnabled) { - _this6.reporter.info(_this6.reporter.lang('plugnplaySuggestV2L1')); - _this6.reporter.info(_this6.reporter.lang('plugnplaySuggestV2L2')); - } - - let flattenedTopLevelPatterns = []; - const steps = []; - - var _ref13 = yield _this6.fetchRequestFromCwd(); - - const depRequests = _ref13.requests, - rawPatterns = _ref13.patterns, - ignorePatterns = _ref13.ignorePatterns, - workspaceLayout = _ref13.workspaceLayout, - manifest = _ref13.manifest; - - let topLevelPatterns = []; - - const artifacts = yield _this6.integrityChecker.getArtifacts(); - if (artifacts) { - _this6.linker.setArtifacts(artifacts); - _this6.scripts.setArtifacts(artifacts); - } - - if ((_packageCompatibility || _load_packageCompatibility()).shouldCheck(manifest, _this6.flags)) { - steps.push((() => { - var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - _this6.reporter.step(curr, total, _this6.reporter.lang('checkingManifest'), emoji.get('mag')); - yield _this6.checkCompatibility(); - }); - - return function (_x, _x2) { - return _ref14.apply(this, arguments); - }; - })()); - } - - const audit = new (_audit || _load_audit()).default(_this6.config, _this6.reporter, { groups: (_constants || _load_constants()).OWNED_DEPENDENCY_TYPES }); - let auditFoundProblems = false; - - steps.push(function (curr, total) { - return (0, (_hooks || _load_hooks()).callThroughHook)('resolveStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this6.reporter.step(curr, total, _this6.reporter.lang('resolvingPackages'), emoji.get('mag')); - yield _this6.resolver.init(_this6.prepareRequests(depRequests), { - isFlat: _this6.flags.flat, - isFrozen: _this6.flags.frozenLockfile, - workspaceLayout - }); - topLevelPatterns = _this6.preparePatterns(rawPatterns); - flattenedTopLevelPatterns = yield _this6.flatten(topLevelPatterns); - return { bailout: !_this6.flags.audit && (yield _this6.bailout(topLevelPatterns, workspaceLayout)) }; - })); - }); - - if (_this6.flags.audit) { - steps.push(function (curr, total) { - return (0, (_hooks || _load_hooks()).callThroughHook)('auditStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this6.reporter.step(curr, total, _this6.reporter.lang('auditRunning'), emoji.get('mag')); - if (_this6.flags.offline) { - _this6.reporter.warn(_this6.reporter.lang('auditOffline')); - return { bailout: false }; - } - const preparedManifests = yield _this6.prepareManifests(); - // $FlowFixMe - Flow considers `m` in the map operation to be "mixed", so does not recognize `m.object` - const mergedManifest = Object.assign({}, ...Object.values(preparedManifests).map(function (m) { - return m.object; - })); - const auditVulnerabilityCounts = yield audit.performAudit(mergedManifest, _this6.lockfile, _this6.resolver, _this6.linker, topLevelPatterns); - auditFoundProblems = auditVulnerabilityCounts.info || auditVulnerabilityCounts.low || auditVulnerabilityCounts.moderate || auditVulnerabilityCounts.high || auditVulnerabilityCounts.critical; - return { bailout: yield _this6.bailout(topLevelPatterns, workspaceLayout) }; - })); - }); - } - - steps.push(function (curr, total) { - return (0, (_hooks || _load_hooks()).callThroughHook)('fetchStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this6.markIgnored(ignorePatterns); - _this6.reporter.step(curr, total, _this6.reporter.lang('fetchingPackages'), emoji.get('truck')); - const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this6.resolver.getManifests(), _this6.config); - _this6.resolver.updateManifests(manifests); - yield (_packageCompatibility || _load_packageCompatibility()).check(_this6.resolver.getManifests(), _this6.config, _this6.flags.ignoreEngines); - })); - }); - - steps.push(function (curr, total) { - return (0, (_hooks || _load_hooks()).callThroughHook)('linkStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // remove integrity hash to make this operation atomic - yield _this6.integrityChecker.removeIntegrityFile(); - _this6.reporter.step(curr, total, _this6.reporter.lang('linkingDependencies'), emoji.get('link')); - flattenedTopLevelPatterns = _this6.preparePatternsForLinking(flattenedTopLevelPatterns, manifest, _this6.config.lockfileFolder === _this6.config.cwd); - yield _this6.linker.init(flattenedTopLevelPatterns, workspaceLayout, { - linkDuplicates: _this6.flags.linkDuplicates, - ignoreOptional: _this6.flags.ignoreOptional - }); - })); - }); - - if (_this6.config.plugnplayEnabled) { - steps.push(function (curr, total) { - return (0, (_hooks || _load_hooks()).callThroughHook)('pnpStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const pnpPath = `${_this6.config.lockfileFolder}/${(_constants || _load_constants()).PNP_FILENAME}`; - - const code = yield (0, (_generatePnpMap || _load_generatePnpMap()).generatePnpMap)(_this6.config, flattenedTopLevelPatterns, { - resolver: _this6.resolver, - reporter: _this6.reporter, - targetPath: pnpPath, - workspaceLayout - }); - - try { - const file = yield (_fs || _load_fs()).readFile(pnpPath); - if (file === code) { - return; - } - } catch (error) {} - - yield (_fs || _load_fs()).writeFile(pnpPath, code); - yield (_fs || _load_fs()).chmod(pnpPath, 0o755); - })); - }); - } - - steps.push(function (curr, total) { - return (0, (_hooks || _load_hooks()).callThroughHook)('buildStep', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this6.reporter.step(curr, total, _this6.flags.force ? _this6.reporter.lang('rebuildingPackages') : _this6.reporter.lang('buildingFreshPackages'), emoji.get('hammer')); - - if (_this6.config.ignoreScripts) { - _this6.reporter.warn(_this6.reporter.lang('ignoredScripts')); - } else { - yield _this6.scripts.init(flattenedTopLevelPatterns); - } - })); - }); - - if (_this6.flags.har) { - steps.push((() => { - var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - const formattedDate = new Date().toISOString().replace(/:/g, '-'); - const filename = `yarn-install_${formattedDate}.har`; - _this6.reporter.step(curr, total, _this6.reporter.lang('savingHar', filename), emoji.get('black_circle_for_record')); - yield _this6.config.requestManager.saveHar(filename); - }); - - return function (_x3, _x4) { - return _ref21.apply(this, arguments); - }; - })()); - } - - if (yield _this6.shouldClean()) { - steps.push((() => { - var _ref22 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - _this6.reporter.step(curr, total, _this6.reporter.lang('cleaningModules'), emoji.get('recycle')); - yield (0, (_autoclean || _load_autoclean()).clean)(_this6.config, _this6.reporter); - }); - - return function (_x5, _x6) { - return _ref22.apply(this, arguments); - }; - })()); - } - - let currentStep = 0; - for (var _iterator11 = steps, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : _iterator11[Symbol.iterator]();;) { - var _ref23; - - if (_isArray11) { - if (_i11 >= _iterator11.length) break; - _ref23 = _iterator11[_i11++]; - } else { - _i11 = _iterator11.next(); - if (_i11.done) break; - _ref23 = _i11.value; - } - - const step = _ref23; - - const stepResult = yield step(++currentStep, steps.length); - if (stepResult && stepResult.bailout) { - if (_this6.flags.audit) { - audit.summary(); - } - if (auditFoundProblems) { - _this6.reporter.warn(_this6.reporter.lang('auditRunAuditForDetails')); - } - _this6.maybeOutputUpdate(); - return flattenedTopLevelPatterns; - } - } - - // fin! - if (_this6.flags.audit) { - audit.summary(); - } - if (auditFoundProblems) { - _this6.reporter.warn(_this6.reporter.lang('auditRunAuditForDetails')); - } - yield _this6.saveLockfileAndIntegrity(topLevelPatterns, workspaceLayout); - yield _this6.persistChanges(); - _this6.maybeOutputUpdate(); - _this6.config.requestManager.clearCache(); - return flattenedTopLevelPatterns; - })(); - } - - checkCompatibility() { - var _this7 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - var _ref24 = yield _this7.fetchRequestFromCwd(); - - const manifest = _ref24.manifest; - - yield (_packageCompatibility || _load_packageCompatibility()).checkOne(manifest, _this7.config, _this7.flags.ignoreEngines); - })(); - } - - persistChanges() { - var _this8 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // get all the different registry manifests in this folder - const manifests = yield _this8.config.getRootManifests(); - - if (yield _this8.applyChanges(manifests)) { - yield _this8.config.saveRootManifests(manifests); - } - })(); - } - - applyChanges(manifests) { - let hasChanged = false; - - if (this.config.plugnplayPersist) { - const object = manifests.npm.object; - - - if (typeof object.installConfig !== 'object') { - object.installConfig = {}; - } - - if (this.config.plugnplayEnabled && object.installConfig.pnp !== true) { - object.installConfig.pnp = true; - hasChanged = true; - } else if (!this.config.plugnplayEnabled && typeof object.installConfig.pnp !== 'undefined') { - delete object.installConfig.pnp; - hasChanged = true; - } - - if (Object.keys(object.installConfig).length === 0) { - delete object.installConfig; - } - } - - return Promise.resolve(hasChanged); - } - - /** - * Check if we should run the cleaning step. - */ - - shouldClean() { - return (_fs || _load_fs()).exists(path.join(this.config.lockfileFolder, (_constants || _load_constants()).CLEAN_FILENAME)); - } - - /** - * TODO - */ - - flatten(patterns) { - var _this9 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (!_this9.flags.flat) { - return patterns; - } - - const flattenedPatterns = []; - - for (var _iterator12 = _this9.resolver.getAllDependencyNamesByLevelOrder(patterns), _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : _iterator12[Symbol.iterator]();;) { - var _ref25; - - if (_isArray12) { - if (_i12 >= _iterator12.length) break; - _ref25 = _iterator12[_i12++]; - } else { - _i12 = _iterator12.next(); - if (_i12.done) break; - _ref25 = _i12.value; - } - - const name = _ref25; - - const infos = _this9.resolver.getAllInfoForPackageName(name).filter(function (manifest) { - const ref = manifest._reference; - invariant(ref, 'expected package reference'); - return !ref.ignore; - }); - - if (infos.length === 0) { - continue; - } - - if (infos.length === 1) { - // single version of this package - // take out a single pattern as multiple patterns may have resolved to this package - flattenedPatterns.push(_this9.resolver.patternsByPackage[name][0]); - continue; - } - - const options = infos.map(function (info) { - const ref = info._reference; - invariant(ref, 'expected reference'); - return { - // TODO `and is required by {PARENT}`, - name: _this9.reporter.lang('manualVersionResolutionOption', ref.patterns.join(', '), info.version), - - value: info.version - }; - }); - const versions = infos.map(function (info) { - return info.version; - }); - let version; - - const resolutionVersion = _this9.resolutions[name]; - if (resolutionVersion && versions.indexOf(resolutionVersion) >= 0) { - // use json `resolution` version - version = resolutionVersion; - } else { - version = yield _this9.reporter.select(_this9.reporter.lang('manualVersionResolution', name), _this9.reporter.lang('answer'), options); - _this9.resolutions[name] = version; - } - - flattenedPatterns.push(_this9.resolver.collapseAllVersionsOfPackage(name, version)); - } - - // save resolutions to their appropriate root manifest - if (Object.keys(_this9.resolutions).length) { - const manifests = yield _this9.config.getRootManifests(); - - for (const name in _this9.resolutions) { - const version = _this9.resolutions[name]; - - const patterns = _this9.resolver.patternsByPackage[name]; - if (!patterns) { - continue; - } - - let manifest; - for (var _iterator13 = patterns, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : _iterator13[Symbol.iterator]();;) { - var _ref26; - - if (_isArray13) { - if (_i13 >= _iterator13.length) break; - _ref26 = _iterator13[_i13++]; - } else { - _i13 = _iterator13.next(); - if (_i13.done) break; - _ref26 = _i13.value; - } - - const pattern = _ref26; - - manifest = _this9.resolver.getResolvedPattern(pattern); - if (manifest) { - break; - } - } - invariant(manifest, 'expected manifest'); - - const ref = manifest._reference; - invariant(ref, 'expected reference'); - - const object = manifests[ref.registry].object; - object.resolutions = object.resolutions || {}; - object.resolutions[name] = version; - } - - yield _this9.config.saveRootManifests(manifests); - } - - return flattenedPatterns; - })(); - } - - /** - * Remove offline tarballs that are no longer required - */ - - pruneOfflineMirror(lockfile) { - var _this10 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const mirror = _this10.config.getOfflineMirrorPath(); - if (!mirror) { - return; - } - - const requiredTarballs = new Set(); - for (const dependency in lockfile) { - const resolved = lockfile[dependency].resolved; - if (resolved) { - const basename = path.basename(resolved.split('#')[0]); - if (dependency[0] === '@' && basename[0] !== '@') { - requiredTarballs.add(`${dependency.split('/')[0]}-${basename}`); - } - requiredTarballs.add(basename); - } - } - - const mirrorFiles = yield (_fs || _load_fs()).walk(mirror); - for (var _iterator14 = mirrorFiles, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : _iterator14[Symbol.iterator]();;) { - var _ref27; - - if (_isArray14) { - if (_i14 >= _iterator14.length) break; - _ref27 = _iterator14[_i14++]; - } else { - _i14 = _iterator14.next(); - if (_i14.done) break; - _ref27 = _i14.value; - } - - const file = _ref27; - - const isTarball = path.extname(file.basename) === '.tgz'; - // if using experimental-pack-script-packages-in-mirror flag, don't unlink prebuilt packages - const hasPrebuiltPackage = file.relative.startsWith('prebuilt/'); - if (isTarball && !hasPrebuiltPackage && !requiredTarballs.has(file.basename)) { - yield (_fs || _load_fs()).unlink(file.absolute); - } - } - })(); - } - - /** - * Save updated integrity and lockfiles. - */ - - saveLockfileAndIntegrity(patterns, workspaceLayout) { - var _this11 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const resolvedPatterns = {}; - Object.keys(_this11.resolver.patterns).forEach(function (pattern) { - if (!workspaceLayout || !workspaceLayout.getManifestByPattern(pattern)) { - resolvedPatterns[pattern] = _this11.resolver.patterns[pattern]; - } - }); - - // TODO this code is duplicated in a few places, need a common way to filter out workspace patterns from lockfile - patterns = patterns.filter(function (p) { - return !workspaceLayout || !workspaceLayout.getManifestByPattern(p); - }); - - const lockfileBasedOnResolver = _this11.lockfile.getLockfile(resolvedPatterns); - - if (_this11.config.pruneOfflineMirror) { - yield _this11.pruneOfflineMirror(lockfileBasedOnResolver); - } - - // write integrity hash - if (!_this11.config.plugnplayEnabled) { - yield _this11.integrityChecker.save(patterns, lockfileBasedOnResolver, _this11.flags, workspaceLayout, _this11.scripts.getArtifacts()); - } - - // --no-lockfile or --pure-lockfile or --frozen-lockfile - if (_this11.flags.lockfile === false || _this11.flags.pureLockfile || _this11.flags.frozenLockfile) { - return; - } - - const lockFileHasAllPatterns = patterns.every(function (p) { - return _this11.lockfile.getLocked(p); - }); - const lockfilePatternsMatch = Object.keys(_this11.lockfile.cache || {}).every(function (p) { - return lockfileBasedOnResolver[p]; - }); - const resolverPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { - const manifest = _this11.lockfile.getLocked(pattern); - return manifest && manifest.resolved === lockfileBasedOnResolver[pattern].resolved && deepEqual(manifest.prebuiltVariants, lockfileBasedOnResolver[pattern].prebuiltVariants); - }); - const integrityPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { - const existingIntegrityInfo = lockfileBasedOnResolver[pattern].integrity; - if (!existingIntegrityInfo) { - // if this entry does not have an integrity, no need to re-write the lockfile because of it - return true; - } - const manifest = _this11.lockfile.getLocked(pattern); - if (manifest && manifest.integrity) { - const manifestIntegrity = ssri.stringify(manifest.integrity); - return manifestIntegrity === existingIntegrityInfo; - } - return false; - }); - - // remove command is followed by install with force, lockfile will be rewritten in any case then - if (!_this11.flags.force && _this11.lockfile.parseResultType === 'success' && lockFileHasAllPatterns && lockfilePatternsMatch && resolverPatternsAreSameAsInLockfile && integrityPatternsAreSameAsInLockfile && patterns.length) { - return; - } - - // build lockfile location - const loc = path.join(_this11.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME); - - // write lockfile - const lockSource = (0, (_lockfile2 || _load_lockfile2()).stringify)(lockfileBasedOnResolver, false, _this11.config.enableLockfileVersions); - yield (_fs || _load_fs()).writeFilePreservingEol(loc, lockSource); - - _this11._logSuccessSaveLockfile(); - })(); - } - - _logSuccessSaveLockfile() { - this.reporter.success(this.reporter.lang('savedLockfile')); - } - - /** - * Load the dependency graph of the current install. Only does package resolving and wont write to the cwd. - */ - hydrate(ignoreUnusedPatterns) { - var _this12 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const request = yield _this12.fetchRequestFromCwd([], ignoreUnusedPatterns); - const depRequests = request.requests, - rawPatterns = request.patterns, - ignorePatterns = request.ignorePatterns, - workspaceLayout = request.workspaceLayout; - - - yield _this12.resolver.init(depRequests, { - isFlat: _this12.flags.flat, - isFrozen: _this12.flags.frozenLockfile, - workspaceLayout - }); - yield _this12.flatten(rawPatterns); - _this12.markIgnored(ignorePatterns); - - // fetch packages, should hit cache most of the time - const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this12.resolver.getManifests(), _this12.config); - _this12.resolver.updateManifests(manifests); - yield (_packageCompatibility || _load_packageCompatibility()).check(_this12.resolver.getManifests(), _this12.config, _this12.flags.ignoreEngines); - - // expand minimal manifests - for (var _iterator15 = _this12.resolver.getManifests(), _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : _iterator15[Symbol.iterator]();;) { - var _ref28; - - if (_isArray15) { - if (_i15 >= _iterator15.length) break; - _ref28 = _iterator15[_i15++]; - } else { - _i15 = _iterator15.next(); - if (_i15.done) break; - _ref28 = _i15.value; - } - - const manifest = _ref28; - - const ref = manifest._reference; - invariant(ref, 'expected reference'); - const type = ref.remote.type; - // link specifier won't ever hit cache - - let loc = ''; - if (type === 'link') { - continue; - } else if (type === 'workspace') { - if (!ref.remote.reference) { - continue; - } - loc = ref.remote.reference; - } else { - loc = _this12.config.generateModuleCachePath(ref); - } - const newPkg = yield _this12.config.readManifest(loc); - yield _this12.resolver.updateManifest(ref, newPkg); - } - - return request; - })(); - } - - /** - * Check for updates every day and output a nag message if there's a newer version. - */ - - checkUpdate() { - if (this.config.nonInteractive) { - // don't show upgrade dialog on CI or non-TTY terminals - return; - } - - // don't check if disabled - if (this.config.getOption('disable-self-update-check')) { - return; - } - - // only check for updates once a day - const lastUpdateCheck = Number(this.config.getOption('lastUpdateCheck')) || 0; - if (lastUpdateCheck && Date.now() - lastUpdateCheck < ONE_DAY) { - return; - } - - // don't bug for updates on tagged releases - if ((_yarnVersion || _load_yarnVersion()).version.indexOf('-') >= 0) { - return; - } - - this._checkUpdate().catch(() => { - // swallow errors - }); - } - - _checkUpdate() { - var _this13 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let latestVersion = yield _this13.config.requestManager.request({ - url: (_constants || _load_constants()).SELF_UPDATE_VERSION_URL - }); - invariant(typeof latestVersion === 'string', 'expected string'); - latestVersion = latestVersion.trim(); - if (!semver.valid(latestVersion)) { - return; - } - - // ensure we only check for updates periodically - _this13.config.registries.yarn.saveHomeConfig({ - lastUpdateCheck: Date.now() - }); - - if (semver.gt(latestVersion, (_yarnVersion || _load_yarnVersion()).version)) { - const installationMethod = yield (0, (_yarnVersion || _load_yarnVersion()).getInstallationMethod)(); - _this13.maybeOutputUpdate = function () { - _this13.reporter.warn(_this13.reporter.lang('yarnOutdated', latestVersion, (_yarnVersion || _load_yarnVersion()).version)); - - const command = getUpdateCommand(installationMethod); - if (command) { - _this13.reporter.info(_this13.reporter.lang('yarnOutdatedCommand')); - _this13.reporter.command(command); - } else { - const installer = getUpdateInstaller(installationMethod); - if (installer) { - _this13.reporter.info(_this13.reporter.lang('yarnOutdatedInstaller', installer)); - } - } - }; - } - })(); - } - - /** - * Method to override with a possible upgrade message. - */ - - maybeOutputUpdate() {} -} - -exports.Install = Install; -function hasWrapper(commander, args) { - return true; -} - -function setFlags(commander) { - commander.description('Yarn install is used to install all dependencies for a project.'); - commander.usage('install [flags]'); - commander.option('-A, --audit', 'Run vulnerability audit on installed packages'); - commander.option('-g, --global', 'DEPRECATED'); - commander.option('-S, --save', 'DEPRECATED - save package to your `dependencies`'); - commander.option('-D, --save-dev', 'DEPRECATED - save package to your `devDependencies`'); - commander.option('-P, --save-peer', 'DEPRECATED - save package to your `peerDependencies`'); - commander.option('-O, --save-optional', 'DEPRECATED - save package to your `optionalDependencies`'); - commander.option('-E, --save-exact', 'DEPRECATED'); - commander.option('-T, --save-tilde', 'DEPRECATED'); -} - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -var isObject = __webpack_require__(53); -module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; -}; - - -/***/ }), -/* 36 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SubjectSubscriber; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subject; }); -/* unused harmony export AnonymousSubject */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tslib__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Observable__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Subscriber__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Subscription__ = __webpack_require__(25); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__ = __webpack_require__(190); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__SubjectSubscription__ = __webpack_require__(422); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__internal_symbol_rxSubscriber__ = __webpack_require__(321); -/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ - - - - - - - -var SubjectSubscriber = /*@__PURE__*/ (function (_super) { - __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](SubjectSubscriber, _super); - function SubjectSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - return _this; - } - return SubjectSubscriber; -}(__WEBPACK_IMPORTED_MODULE_2__Subscriber__["a" /* Subscriber */])); - -var Subject = /*@__PURE__*/ (function (_super) { - __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.observers = []; - _this.closed = false; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject.prototype[__WEBPACK_IMPORTED_MODULE_6__internal_symbol_rxSubscriber__["a" /* rxSubscriber */]] = function () { - return new SubjectSubscriber(this); - }; - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype.next = function (value) { - if (this.closed) { - throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); - } - if (!this.isStopped) { - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].next(value); - } - } - }; - Subject.prototype.error = function (err) { - if (this.closed) { - throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); - } - this.hasError = true; - this.thrownError = err; - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].error(err); - } - this.observers.length = 0; - }; - Subject.prototype.complete = function () { - if (this.closed) { - throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); - } - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].complete(); - } - this.observers.length = 0; - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = true; - this.closed = true; - this.observers = null; - }; - Subject.prototype._trySubscribe = function (subscriber) { - if (this.closed) { - throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); - } - else { - return _super.prototype._trySubscribe.call(this, subscriber); - } - }; - Subject.prototype._subscribe = function (subscriber) { - if (this.closed) { - throw new __WEBPACK_IMPORTED_MODULE_4__util_ObjectUnsubscribedError__["a" /* ObjectUnsubscribedError */](); - } - else if (this.hasError) { - subscriber.error(this.thrownError); - return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; - } - else if (this.isStopped) { - subscriber.complete(); - return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; - } - else { - this.observers.push(subscriber); - return new __WEBPACK_IMPORTED_MODULE_5__SubjectSubscription__["a" /* SubjectSubscription */](this, subscriber); - } - }; - Subject.prototype.asObservable = function () { - var observable = new __WEBPACK_IMPORTED_MODULE_1__Observable__["a" /* Observable */](); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject; -}(__WEBPACK_IMPORTED_MODULE_1__Observable__["a" /* Observable */])); - -var AnonymousSubject = /*@__PURE__*/ (function (_super) { - __WEBPACK_IMPORTED_MODULE_0_tslib__["a" /* __extends */](AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject.prototype.next = function (value) { - var destination = this.destination; - if (destination && destination.next) { - destination.next(value); - } - }; - AnonymousSubject.prototype.error = function (err) { - var destination = this.destination; - if (destination && destination.error) { - this.destination.error(err); - } - }; - AnonymousSubject.prototype.complete = function () { - var destination = this.destination; - if (destination && destination.complete) { - this.destination.complete(); - } - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var source = this.source; - if (source) { - return this.source.subscribe(subscriber); - } - else { - return __WEBPACK_IMPORTED_MODULE_3__Subscription__["a" /* Subscription */].EMPTY; - } - }; - return AnonymousSubject; -}(Subject)); - -//# sourceMappingURL=Subject.js.map - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.normalizePattern = normalizePattern; - -/** - * Explode and normalize a pattern into its name and range. - */ - -function normalizePattern(pattern) { - let hasVersion = false; - let range = 'latest'; - let name = pattern; - - // if we're a scope then remove the @ and add it back later - let isScoped = false; - if (name[0] === '@') { - isScoped = true; - name = name.slice(1); - } - - // take first part as the name - const parts = name.split('@'); - if (parts.length > 1) { - name = parts.shift(); - range = parts.join('@'); - - if (range) { - hasVersion = true; - } else { - range = '*'; - } - } - - // add back @ scope suffix - if (isScoped) { - name = `@${name}`; - } - - return { name, range, hasVersion }; -} - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** - * @license - * Lodash - * Copyright JS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '4.17.10'; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function'; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; - - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); - - /** Used to match leading and trailing whitespace. */ - var reTrim = /^\s+|\s+$/g, - reTrimStart = /^\s+/, - reTrimEnd = /\s+$/; - - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; - - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; - - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); - - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; - - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; - - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; - - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /*--------------------------------------------------------------------------*/ - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); - - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } - - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } - - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } - - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; - } - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; - - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; - - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; - - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); - - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); - - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } - - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; - - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } - - /** - * Gets the value at `key`, unless `key` is "__proto__". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - return key == '__proto__' - ? undefined - : object[key]; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } - } - return index; - } - - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } - - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } - - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } - - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to generate unique IDs. */ - var idCounter = 0; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; - - /** Used to lookup unminified function names. */ - var realNames = {}; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } - - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined; - } - - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB) as well as ES2015 template strings. Change the - * following template settings to use alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ - lodash.templateSettings = { - - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, - - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, - - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, - - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', - - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { - - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; - - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; - - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } - - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = copyArray(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = copyArray(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = copyArray(this.__views__); - return result; - } - - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } - - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); - - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; - - outer: - while (length-- && resIndex < takeCount) { - index += dir; - - var iterIndex = -1, - value = array[index]; - - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); - - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } - - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } - - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } - - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; - - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } - - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG; - - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - - return result; - } - - if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - - return result; - } - - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); - - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } - - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length], - predicate = source[key], - value = object[key]; - - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } - - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); - - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } - - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index], - current = iteratee(value); - - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } - - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; - - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; - } - - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } - - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } - - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } - - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } - - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } - - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; - - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; - - var index = -1, - seen = caches[0]; - - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } - - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } - - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); - - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ - function baseLt(value, other) { - return value < other; - } - - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - if (isObject(srcValue)) { - stack || (stack = new Stack); - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; - } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; - } - - /** - * The base implementation of `_.orderBy` without param guards. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseOrderBy(collection, iteratees, orders) { - var index = -1; - iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); - - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; - - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); - } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; - - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } - - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; - - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } - - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. - * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } - - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. - * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); - - return result; - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * The base implementation of `_.sample`. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } - - /** - * The base implementation of `_.sampleSize` without param guards. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** - * The base implementation of `_.shuffle`. - * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } - - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } - - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } - - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - value = iteratee(value); - - var low = 0, - high = array == null ? 0 : array.length, - valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); - - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } - - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.unset`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } - - /** - * The base implementation of `_.update`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } - - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} - - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } - - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } - - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); - - while (++index < length) { - var array = arrays[index], - othIndex = -1; - - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } - - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; - - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } - - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } - - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. - * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - var castRest = baseRest; - - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } - - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = isSymbol(value); - - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = isSymbol(other); - - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } - - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; - - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } - - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } - - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; - - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result; - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } - - /** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; - - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; - } - - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; - } - - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } - - /** - * Creates a function that wraps `func` to enable currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); - - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); - - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; - } - - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } - - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; - - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; - - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; - - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; - - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } - - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; - - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; - - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); - } - return wrapper; - } - - /** - * Creates a function like `_.invertBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; - } - - /** - * Creates a function that performs a mathematical operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; - } - if (other !== undefined) { - if (result === undefined) { - return other; - } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result = operator(value, other); - } - return result; - }; - } - - /** - * Creates a function like `_.over`. - * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); - } - - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); - - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); - } - - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); - } - return wrapper; - } - - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } - - /** - * Creates a function that performs a relational operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; - } - - /** - * Creates a function that wraps `func` to continue currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; - - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; - - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } - - /** - * Creates a function like `_.round`. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); - - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; - } - - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; - - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } - - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); - - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; - - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); - - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); - } - - /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; - } - - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); - } - return objValue; - } - - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; - } - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag: - return object.name == other.name && object.message == other.message; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag: - var convert = mapToArray; - - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - - /** - * Gets the name of `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } - - /** - * Gets the argument placeholder value for `func`. - * - * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. - */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; - } - - /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. - * - * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. - */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; - - while (++index < length) { - var data = transforms[index], - size = data.size; - - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } - - /** - * Extracts wrapper details from the `source` body comment. - * - * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. - */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return new Ctor; - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return new Ctor; - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. - * - * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. - */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); - } - - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has a lazy counterpart. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. - */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; - - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `func` is capable of being masked. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ - var isMaskable = coreJsData ? isFunction : stubFalse; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. - * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); - } - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Gets the parent value at `path` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. - */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } - - /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. - * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; - } - - /** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var setData = shortOut(baseSetData); - - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. - */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. - * - * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. - */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. - * - * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. - */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; - - array[rand] = array[index]; - array[index] = value; - } - array.length = size; - return array; - } - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Updates wrapper `details` based on `bitmask` flags. - * - * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. - */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); - } - - /** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; - } - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] - * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); - - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] - * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; - } - - /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; - } - - /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] - * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] - */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; - } - return baseFill(array, value, start, end); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); - } - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 - * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 - */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } - - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - - /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - - /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] - * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } - - /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example - * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; - - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; - } - return result; - } - - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } - - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value, index); - } - - /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } - - /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] - * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); - - /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example - * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); - } - - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } - - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 - */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); - } - - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' - * - * _.nth(array, -2); - * // => 'c'; - */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; - } - - /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); - - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] - */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; - } - - /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] - * - * console.log(pulled); - * // => ['b', 'd'] - */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); - - /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] - * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; - - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result; - } - - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); - } - return baseSlice(array, start, end); - } - - /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([30, 50], 40); - * // => 1 - */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); - } - - /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 - */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); - } - - /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 - */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); - } - - /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 - * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 - */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); - } - - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } - - /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; - } - - /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.tail([1, 2, 3]); - * // => [2, 3] - */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - - /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.take([1, 2, 3], 0); - * // => [] - */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] - */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; - } - - /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] - * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] - */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; - } - - /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - - /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); - - /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; - } - - /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); - } - - /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] - * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; - } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); - } - - /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example - * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] - */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); - - /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example - * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] - */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - - /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] - * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); - - /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ - var zip = baseRest(unzip); - - /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); - } - - /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } - */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); - } - - /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] - */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; - - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; - } - - /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example - * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor) { - interceptor(value); - return value; - } - - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor) { - return interceptor(value); - } - - /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] - */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; - - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); - } - return array; - }); - }); - - /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } - * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - - /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 - * - * console.log(array); - * // => [1, 2, 3] - */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - - /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } - * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } - */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; - - return { 'done': done, 'value': value }; - } - - /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true - * - * Array.from(wrapped); - * // => [1, 2] - */ - function wrapperToIterator() { - return this; - } - - /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ - function wrapperPlant(value) { - var result, - parent = this; - - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; - } - previous.__wrapped__ = value; - return result; - } - - /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - - /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } - * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); - } - }); - - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); - - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ - var findLast = createFind(findLastIndex); - - /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] - */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); - } - - /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example - * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. - */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } - }); - - /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); - } - - /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result; - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); - - /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; - * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - - /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] - * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] - * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); - } - - /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce - * @example - * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); - } - - /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } - - /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } - - /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. - * @example - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] - * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] - */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); - } - - /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example - * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] - */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - var now = ctxNow || function() { - return root.Date.now(); - }; - - /*------------------------------------------------------------------------*/ - - /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. - */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); - } - - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - - /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' - * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); - - /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; - } - - /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; - return result; - } - - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; - - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } - - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - - /** - * Creates a function that invokes `func` with arguments reversed. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example - * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); - * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] - */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ - function once(func) { - return before(2, func); - } - - /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] - * - * func(10, 5); - * // => [100, 10] - */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); - - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); - - /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); - - /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); - - /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. - * @example - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); - - /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. - * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); - } - - /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); - - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); - } - - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); - } - - /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ - function unary(func) { - return ary(func, 1); - } - - /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' - */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; - } - - /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 - */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 - */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. - * - * @static - * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true - * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false - */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false - * - * _.gt(1, 3); - * // => false - */ - var gt = createRelationalOperation(baseGt); - - /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true - * - * _.gte(1, 3); - * // => false - */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true - * - * _.isArrayBuffer(new Array(2)); - * // => false - */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - * - * _.isDate('Mon April 23 2012'); - * // => false - */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - - /** - * Checks if `value` is likely a DOM element. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - * - * _.isElement(''); - * // => false - */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } - - /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } - } - return true; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } - * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; - * - * _.isEqualWith(array, other, customizer); - * // => true - */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; - } - - /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false - */ - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); - } - - /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); - } - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false - */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - - /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true - * - * _.isMatch(object, { 'b': 1 }); - * // => false - */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } - - /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } - * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; - * - * _.isMatchWith(object, source, customizer); - * // => true - */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false - */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true - * - * _.isNil(NaN); - * // => false - */ - function isNil(value) { - return value == null; - } - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - - /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. - * @example - * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false - * - * _.isSafeInteger(Infinity); - * // => false - * - * _.isSafeInteger('3'); - * // => false - */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true - * - * _.isSet(new WeakSet); - * // => false - */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); - } - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - /** - * Checks if `value` is classified as a `WeakMap` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. - * @example - * - * _.isWeakMap(new WeakMap); - * // => true - * - * _.isWeakMap(new Map); - * // => false - */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } - - /** - * Checks if `value` is classified as a `WeakSet` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. - * @example - * - * _.isWeakSet(new WeakSet); - * // => true - * - * _.isWeakSet(new Set); - * // => false - */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - - /** - * Checks if `value` is less than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt - * @example - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false - * - * _.lt(3, 1); - * // => false - */ - var lt = createRelationalOperation(baseLt); - - /** - * Checks if `value` is less than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte - * @example - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false - */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); - - /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] - * - * _.toArray(null); - * // => [] - */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); - } - - /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; - } - - /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; - } - - /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 - * - * _.toLength(Infinity); - * // => 4294967295 - * - * _.toLength('3.2'); - * // => 3 - */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } - - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 - */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - } - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } - } - }); - - /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } - */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); - - /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); - - /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); - - /** - * Creates an array of values corresponding to `paths` of `object`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Array} Returns the picked values. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] - */ - var at = flatRest(baseAt); - - /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); - } - - /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var defaults = baseRest(function(object, sources) { - object = Object(object); - - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } - } - - return object; - }); - - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults - * @example - * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } - */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } - - /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' - */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } - - /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). - */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. - */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. - */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); - } - - /** - * Creates an array of function property names from own enumerable properties - * of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functions(new Foo); - * // => ['a', 'b'] - */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); - } - - /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] - */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } - */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - result[value] = key; - }, constant(identity)); - - /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } - * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } - */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; - } - }, getIteratee); - - /** - * Invokes the method at `path` of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - * @example - * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; - * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] - */ - var invoke = baseRest(baseInvoke); - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; - * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } - */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); - - /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. - * - * **Note:** This method is considerably slower than `_.pick`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to omit. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } - */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); - } - return result; - }); - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } - - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' - * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' - */ - function result(object, path, defaultValue) { - path = castPath(path, object); - - var index = -1, - length = path.length; - - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; - } - return object; - } - - /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 - */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); - } - - /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } - */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); - } - - /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) - */ - var toPairs = createToPairs(keys); - - /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) - */ - var toPairsIn = createToPairs(keysIn); - - /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. - * @example - * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } - */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } - - /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } - - /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 - * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 - */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } - - /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } - */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } - - /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); - } - - /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) - */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - * @example - * - * _.clamp(-10, -5, 5); - * // => -5 - * - * _.clamp(10, -5, 5); - * // => 5 - */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber(number), lower, upper); - } - - /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. - * - * @static - * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight - * @example - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false - * - * _.inRange(-3, -2, -6); - * // => true - */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); - } - - /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. - * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); - } - - /*------------------------------------------------------------------------*/ - - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); - - /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } - - /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } - - /** - * Checks if `string` ends with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. - * @example - * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true - */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } - - /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } - - /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' - */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; - } - - /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' - */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); - - /** - * Converts `string`, as space separated words, to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. - * @example - * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' - * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' - */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); - - /** - * Converts the first character of `string` to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.lowerFirst('Fred'); - * // => 'fred' - * - * _.lowerFirst('FRED'); - * // => 'fRED' - */ - var lowerFirst = createCaseFirst('toLowerCase'); - - /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' - * - * _.pad('abc', 3); - * // => 'abc' - */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; - } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); - } - - /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padEnd('abc', 3); - * // => 'abc' - */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; - } - - /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padStart('abc', 3); - * // => 'abc' - */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; - } - - /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. - * @example - * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] - */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } - - /** - * Repeats the given string `n` times. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. - * @example - * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' - */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); - } - - /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. - * @example - * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' - */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); - } - - /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. - * @example - * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' - */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); - - /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. - * @example - * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] - */ - function split(string, separator, limit) { - if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { - separator = limit = undefined; - } - limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && ( - typeof separator == 'string' || - (separator != null && !isRegExp(separator)) - )) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); - } - - /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). - * - * @static - * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. - * @example - * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' - */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); - - /** - * Checks if `string` starts with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, - * else `false`. - * @example - * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true - */ - function startsWith(string, target, position) { - string = toString(string); - position = position == null - ? 0 - : baseClamp(toInteger(position), 0, string.length); - - target = baseToString(target); - return string.slice(position, position + target.length) == target; - } - - /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. - * @example - * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': '