From 05152587e3e17fb8a727a38837f21a5f9bbec974 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20=C5=A0im=C3=A1nek?= Date: Tue, 6 Oct 2026 19:02:52 +0200 Subject: [PATCH] Add Gemfile export with `rb-gemfile` --- .github/workflows/ci.yml | 35 + Cargo.lock | 117 ++ crates/rb-cli/Cargo.toml | 1 + crates/rb-cli/src/commands/export_gemfile.rs | 179 ++ crates/rb-cli/src/commands/mod.rs | 1 + crates/rb-cli/src/dispatch.rs | 9 +- crates/rb-cli/src/help_formatter.rs | 8 +- crates/rb-cli/src/lib.rs | 34 + crates/rb-cli/src/runtime_helpers.rs | 44 +- crates/rb-cli/tests/export_gemfile_tests.rs | 546 ++++++ ...d_rejects_conflicts_without_writing-1.toml | 4 + .../legacy_generated.toml | 5 + ...ions_and_preserves_project_settings-1.toml | 4 + crates/rb-gemfile/Cargo.toml | 17 + crates/rb-gemfile/README.md | 31 + crates/rb-gemfile/assets/compatibility.rb | 21 + crates/rb-gemfile/assets/evaluate.rb | 15 + crates/rb-gemfile/assets/gemfile.rb | 188 +++ crates/rb-gemfile/assets/gemspec.rb | 90 + crates/rb-gemfile/assets/sources.rb | 54 + crates/rb-gemfile/examples/evaluate.rs | 10 + crates/rb-gemfile/src/evaluator.rs | 117 ++ crates/rb-gemfile/src/format.rs | 183 +++ crates/rb-gemfile/src/kdl.rs | 155 ++ crates/rb-gemfile/src/kdl/parse.rs | 245 +++ crates/rb-gemfile/src/lib.rs | 15 + crates/rb-gemfile/src/manifest.rs | 282 ++++ crates/rb-gemfile/src/project.rs | 172 ++ crates/rb-gemfile/src/snapshot.rs | 280 ++++ crates/rb-gemfile/src/sources.rs | 265 +++ crates/rb-gemfile/tests/corpus.rs | 259 +++ crates/rb-gemfile/tests/evaluation.rs | 705 ++++++++ .../tests/fixtures/corpus/chatwoot.json | 29 + .../tests/fixtures/corpus/diaspora.json | 27 + .../tests/fixtures/corpus/errbit.json | 20 + .../tests/fixtures/corpus/forem.json | 23 + .../tests/fixtures/corpus/foreman.json | 31 + .../tests/fixtures/corpus/lobsters.json | 20 + .../tests/fixtures/corpus/manageiq.json | 28 + .../tests/fixtures/corpus/mastodon.json | 24 + .../tests/fixtures/corpus/postal.json | 24 + .../tests/fixtures/corpus/zammad.json | 25 + ...ts_are_combined_without_losing_bounds-1.rb | 8 + ...s_and_conditions_for_each_declaration-1.rb | 18 + ..._and_require_settings_without_bundler-1.rb | 12 + ...nd_preserves_custom_selector_metadata-1.rb | 10 + ...ndency_sources_override_scope_sources-1.rb | 5 + ...evelopment_declaration_in_both_orders-1.rb | 5 + ...name_and_retains_package_requirements-1.rb | 9 + ...project_gemspec_and_ruby_version_file-1.rb | 9 + ..._sources_do_not_inherit_git_selectors-1.rb | 12 + ...ns_with_different_activation_settings-1.rb | 11 + ...orms_and_evaluated_install_conditions-1.rb | 11 + ...s_sources_and_resolves_included_paths-1.rb | 12 + ...platform_variant_of_a_package_gemspec-1.rb | 5 + ...platform_variant_of_a_package_gemspec-2.rb | 6 + ...s_and_escaping_survive_both_formats-1.toml | 4 + .../fixtures/format/default_registry_pin.toml | 9 + .../tests/fixtures/format/evaluate-1.rb | 16 + .../fixtures/format/explicit_sources.toml | 17 + .../tests/fixtures/format/group_source.kdl | 7 + ...ifferent_sources_remain_unambiguous-1.toml | 5 + ..._and_preserves_metadata_and_options-1.toml | 4 + .../fixtures/format/multi_source/Gemfile | 15 + .../fixtures/format/multi_source/project.kdl | 18 + .../fixtures/format/multi_source/project.toml | 23 + .../fixtures/format/package_named_item.toml | 10 + ...dencies_and_checks_source_conflicts-1.toml | 8 + .../format/repeated_declarations.toml | 7 + .../tests/fixtures/format/source_group.kdl | 5 + ...clarations_and_omits_redundant_fields-1.rb | 21 + ...ettings_and_additional_dependencies-1.toml | 10 + .../tests/fixtures/real-world/README.md | 7 + .../fixtures/real-world/chatwoot/Gemfile | 283 ++++ .../fixtures/real-world/chatwoot/LICENSE | 25 + .../fixtures/real-world/chatwoot/source.json | 14 + .../fixtures/real-world/diaspora/Gemfile | 277 ++++ .../fixtures/real-world/diaspora/LICENSE | 662 ++++++++ .../fixtures/real-world/diaspora/source.json | 14 + .../fixtures/real-world/errbit/.ruby-version | 1 + .../tests/fixtures/real-world/errbit/Gemfile | 114 ++ .../tests/fixtures/real-world/errbit/LICENSE | 20 + .../fixtures/real-world/errbit/UserGemfile | 1 + .../fixtures/real-world/errbit/source.json | 16 + .../fixtures/real-world/forem/.ruby-version | 1 + .../tests/fixtures/real-world/forem/Gemfile | 189 +++ .../fixtures/real-world/forem/LICENSE.md | 661 ++++++++ .../fixtures/real-world/forem/source.json | 16 + .../tests/fixtures/real-world/foreman/Gemfile | 55 + .../tests/fixtures/real-world/foreman/LICENSE | 1460 +++++++++++++++++ .../real-world/foreman/bundler.d/assets.rb | 8 + .../real-world/foreman/bundler.d/console.rb | 4 + .../foreman/bundler.d/development.rb | 28 + .../foreman/bundler.d/dynflow_sidekiq.rb | 4 + .../real-world/foreman/bundler.d/ec2.rb | 3 + .../real-world/foreman/bundler.d/facter.rb | 3 + .../real-world/foreman/bundler.d/journald.rb | 4 + .../real-world/foreman/bundler.d/jsonp.rb | 3 + .../real-world/foreman/bundler.d/libvirt.rb | 4 + .../real-world/foreman/bundler.d/nulldb.rb | 1 + .../real-world/foreman/bundler.d/openid.rb | 3 + .../real-world/foreman/bundler.d/openstack.rb | 3 + .../foreman/bundler.d/postgresql.rb | 4 + .../real-world/foreman/bundler.d/redis.rb | 3 + .../real-world/foreman/bundler.d/service.rb | 1 + .../real-world/foreman/bundler.d/telemetry.rb | 4 + .../real-world/foreman/bundler.d/test.rb | 23 + .../real-world/foreman/bundler.d/vmware.rb | 3 + .../fixtures/real-world/foreman/source.json | 32 + .../real-world/lobsters/.ruby-version | 1 + .../fixtures/real-world/lobsters/Gemfile | 84 + .../fixtures/real-world/lobsters/LICENSE | 27 + .../fixtures/real-world/lobsters/source.json | 15 + .../fixtures/real-world/manageiq/Gemfile | 328 ++++ .../fixtures/real-world/manageiq/LICENSE.txt | 202 +++ .../fixtures/real-world/manageiq/source.json | 55 + .../fixtures/real-world/mastodon/Gemfile | 235 +++ .../fixtures/real-world/mastodon/LICENSE | 661 ++++++++ .../fixtures/real-world/mastodon/source.json | 15 + .../tests/fixtures/real-world/postal/Gemfile | 67 + .../fixtures/real-world/postal/source.json | 14 + .../tests/fixtures/real-world/zammad/Gemfile | 293 ++++ .../tests/fixtures/real-world/zammad/LICENSE | 661 ++++++++ .../fixtures/real-world/zammad/source.json | 17 + .../ruby/compatibility_helpers/Gemfile | 12 + .../ruby/compatibility_helpers/sample.gemspec | 5 + .../fixtures/ruby/gemspec_options/Gemfile | 1 + .../ruby/gemspec_options/sample.gemspec | 4 + .../tests/fixtures/ruby/nested_sources.rb | 7 + .../fixtures/ruby/require_settings/Gemfile | 3 + .../fixtures/ruby/source_options/Gemfile | 5 + ..._inputs_updates_exported_dependencies-1.rb | 4 + crates/rb-gemfile/tests/format.rs | 260 +++ crates/rb-gemfile/tests/project.rs | 140 ++ .../rb-gemfile/tests/ruby/evaluator_test.rb | 189 +++ crates/rb-gemfile/tests/snapshot.rs | 424 +++++ spec/commands/export_gemfile_spec.sh | 51 + spec/fixtures/export-gemfile/Gemfile | 8 + .../ExportGemfile.Integration.Tests.ps1 | 52 + 139 files changed, 12444 insertions(+), 4 deletions(-) create mode 100644 crates/rb-cli/src/commands/export_gemfile.rs create mode 100644 crates/rb-cli/tests/export_gemfile_tests.rs create mode 100644 crates/rb-cli/tests/fixtures/export_gemfile_tests/global_project_input_preserves_settings_and_rejects_conflicts_without_writing-1.toml create mode 100644 crates/rb-cli/tests/fixtures/export_gemfile_tests/legacy_generated.toml create mode 100644 crates/rb-cli/tests/fixtures/export_gemfile_tests/reexport_replaces_generated_declarations_and_preserves_project_settings-1.toml create mode 100644 crates/rb-gemfile/Cargo.toml create mode 100644 crates/rb-gemfile/README.md create mode 100644 crates/rb-gemfile/assets/compatibility.rb create mode 100644 crates/rb-gemfile/assets/evaluate.rb create mode 100644 crates/rb-gemfile/assets/gemfile.rb create mode 100644 crates/rb-gemfile/assets/gemspec.rb create mode 100644 crates/rb-gemfile/assets/sources.rb create mode 100644 crates/rb-gemfile/examples/evaluate.rs create mode 100644 crates/rb-gemfile/src/evaluator.rs create mode 100644 crates/rb-gemfile/src/format.rs create mode 100644 crates/rb-gemfile/src/kdl.rs create mode 100644 crates/rb-gemfile/src/kdl/parse.rs create mode 100644 crates/rb-gemfile/src/lib.rs create mode 100644 crates/rb-gemfile/src/manifest.rs create mode 100644 crates/rb-gemfile/src/project.rs create mode 100644 crates/rb-gemfile/src/snapshot.rs create mode 100644 crates/rb-gemfile/src/sources.rs create mode 100644 crates/rb-gemfile/tests/corpus.rs create mode 100644 crates/rb-gemfile/tests/evaluation.rs create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/chatwoot.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/diaspora.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/errbit.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/forem.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/foreman.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/lobsters.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/manageiq.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/mastodon.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/postal.json create mode 100644 crates/rb-gemfile/tests/fixtures/corpus/zammad.json create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/duplicate_gemspec_requirements_are_combined_without_losing_bounds-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/evaluates_environment_scopes_and_conditions_for_each_declaration-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/evaluates_requirements_groups_and_require_settings_without_bundler-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/expands_git_shortcuts_and_preserves_custom_selector_metadata-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/explicit_dependency_sources_override_scope_sources-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/gemfile_activation_wins_over_gemspec_development_declaration_in_both_orders-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/gemspec_name_uses_package_name_and_retains_package_requirements-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/loads_project_gemspec_and_ruby_version_file-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/nested_sources_do_not_inherit_git_selectors-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/preserves_duplicate_declarations_with_different_activation_settings-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/preserves_platforms_and_evaluated_install_conditions-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/scopes_sources_and_resolves_included_paths-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-2.rb create mode 100644 crates/rb-gemfile/tests/fixtures/format/complex_variants_and_escaping_survive_both_formats-1.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/default_registry_pin.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/evaluate-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/format/explicit_sources.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/group_source.kdl create mode 100644 crates/rb-gemfile/tests/fixtures/format/inline_sources_and_variants_with_different_sources_remain_unambiguous-1.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/kdl_uses_source_blocks_and_preserves_metadata_and_options-1.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/multi_source/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/format/multi_source/project.kdl create mode 100644 crates/rb-gemfile/tests/fixtures/format/multi_source/project.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/package_named_item.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/reads_mixed_and_expanded_dependencies_and_checks_source_conflicts-1.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/repeated_declarations.toml create mode 100644 crates/rb-gemfile/tests/fixtures/format/source_group.kdl create mode 100644 crates/rb-gemfile/tests/fixtures/project/exports_only_active_declarations_and_omits_redundant_fields-1.rb create mode 100644 crates/rb-gemfile/tests/fixtures/project/merges_root_settings_and_additional_dependencies-1.toml create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/README.md create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/chatwoot/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/chatwoot/LICENSE create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/chatwoot/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/diaspora/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/diaspora/LICENSE create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/diaspora/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/errbit/.ruby-version create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/errbit/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/errbit/LICENSE create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/errbit/UserGemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/errbit/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/forem/.ruby-version create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/forem/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/forem/LICENSE.md create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/forem/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/LICENSE create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/assets.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/console.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/development.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/dynflow_sidekiq.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/ec2.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/facter.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/journald.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/jsonp.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/libvirt.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/nulldb.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openid.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openstack.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/postgresql.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/redis.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/service.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/telemetry.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/test.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/vmware.rb create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/foreman/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/lobsters/.ruby-version create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/lobsters/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/lobsters/LICENSE create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/lobsters/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/manageiq/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/manageiq/LICENSE.txt create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/manageiq/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/mastodon/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/mastodon/LICENSE create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/mastodon/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/postal/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/postal/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/zammad/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/zammad/LICENSE create mode 100644 crates/rb-gemfile/tests/fixtures/real-world/zammad/source.json create mode 100644 crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/sample.gemspec create mode 100644 crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/sample.gemspec create mode 100644 crates/rb-gemfile/tests/fixtures/ruby/nested_sources.rb create mode 100644 crates/rb-gemfile/tests/fixtures/ruby/require_settings/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/ruby/source_options/Gemfile create mode 100644 crates/rb-gemfile/tests/fixtures/snapshot/changing_condition_inputs_updates_exported_dependencies-1.rb create mode 100644 crates/rb-gemfile/tests/format.rs create mode 100644 crates/rb-gemfile/tests/project.rs create mode 100644 crates/rb-gemfile/tests/ruby/evaluator_test.rb create mode 100644 crates/rb-gemfile/tests/snapshot.rs create mode 100644 spec/commands/export_gemfile_spec.sh create mode 100644 spec/fixtures/export-gemfile/Gemfile create mode 100644 tests/commands/ExportGemfile.Integration.Tests.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ad4977..239b1fe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,7 @@ on: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 + RUBY_TEST_VERSION: '3.4' jobs: lint: @@ -90,6 +91,28 @@ jobs: - name: Run yamllint run: make lint-yaml + test-gemfile-ruby: + name: Gemfile Ruby Tests (${{ matrix.ruby }}, ${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + ruby: ['3.3', '3.4', '4.0'] + steps: + - uses: actions/checkout@v4 + + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler: none + + - name: Install Minitest + run: gem install minitest --version '~> 5.25' --no-document + + - name: Test the Ruby evaluator + run: ruby crates/rb-gemfile/tests/ruby/evaluator_test.rb + test-rust: name: Rust Tests runs-on: ${{ matrix.os }} @@ -116,6 +139,12 @@ jobs: - name: Build run: cargo build --verbose + - name: Install Ruby for Gemfile evaluation tests + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ env.RUBY_TEST_VERSION }} + bundler: none + - name: Run unit tests run: cargo test --verbose @@ -342,6 +371,12 @@ jobs: - name: Install cargo-llvm-cov run: cargo install --force cargo-llvm-cov + - name: Install Ruby for Gemfile evaluation tests + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ env.RUBY_TEST_VERSION }} + bundler: none + - name: Generate coverage report run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info diff --git a/Cargo.lock b/Cargo.lock index a7a26ae..1614bfe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,6 +112,15 @@ version = "2.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34efbcccd345379ca2868b2b2c9d3782e9cc58ba87bc7d79d5b53d9c9ae6f25d" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "cfg-if" version = "1.0.3" @@ -183,6 +192,41 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "either" version = "1.15.0" @@ -234,6 +278,16 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.3.3" @@ -295,6 +349,12 @@ version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "jiff" version = "0.2.15" @@ -556,6 +616,7 @@ dependencies = [ "kdl", "log", "rb-core", + "rb-gemfile", "rb-progress", "rb-tests", "semver", @@ -583,6 +644,21 @@ dependencies = [ "which", ] +[[package]] +name = "rb-gemfile" +version = "0.3.1" +dependencies = [ + "dunce", + "kdl", + "serde", + "serde_json", + "sha2", + "tempfile", + "toml", + "toml_edit", + "which", +] + [[package]] name = "rb-progress" version = "0.3.1" @@ -664,6 +740,12 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "semver" version = "1.0.26" @@ -690,6 +772,18 @@ dependencies = [ "syn", ] +[[package]] +name = "serde_json" +version = "1.0.143" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d401abef1d108fbd9cbaebc3e46611f4b1021f714a0597a71f41ee463f5f4a5a" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + [[package]] name = "serde_spanned" version = "0.6.9" @@ -699,6 +793,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "strsim" version = "0.11.1" @@ -811,6 +916,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.18" @@ -841,6 +952,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasi" version = "0.14.2+wasi-0.2.4" diff --git a/crates/rb-cli/Cargo.toml b/crates/rb-cli/Cargo.toml index 075234d..ad9ea65 100644 --- a/crates/rb-cli/Cargo.toml +++ b/crates/rb-cli/Cargo.toml @@ -22,6 +22,7 @@ path = "src/bin/rb.rs" clap = { version = "4.0", features = ["derive", "color", "help", "usage", "env"] } clap_complete = "4.0" rb-core = { path = "../rb-core" } +rb-gemfile = { path = "../rb-gemfile" } rb-progress = { path = "../rb-progress" } home = "0.5" colored = "2.0" diff --git a/crates/rb-cli/src/commands/export_gemfile.rs b/crates/rb-cli/src/commands/export_gemfile.rs new file mode 100644 index 0000000..f7ac3c1 --- /dev/null +++ b/crates/rb-cli/src/commands/export_gemfile.rs @@ -0,0 +1,179 @@ +use rb_core::butler::{ButlerError, ButlerRuntime}; +use rb_gemfile::{Evaluator, ExportFormat, write_project}; +use std::{ + ffi::OsStr, + fs, io, + io::Write, + path::{Path, PathBuf}, +}; + +pub fn find_gemfile( + start: &Path, + explicit: Option<&Path>, + environment: Option<&OsStr>, +) -> io::Result { + if let Some(path) = + explicit.or_else(|| environment.filter(|value| !value.is_empty()).map(Path::new)) + { + let path = start.join(path); + if !path.is_file() { + return Err(io::Error::new( + io::ErrorKind::NotFound, + format!("Gemfile not found: {}", path.display()), + )); + } + return fs::canonicalize(path); + } + for directory in start.ancestors() { + for name in ["gems.rb", "Gemfile"] { + let path = directory.join(name); + if path.is_file() { + return fs::canonicalize(path); + } + } + } + Err(io::Error::new( + io::ErrorKind::NotFound, + "No gems.rb or Gemfile found in the working directory or its parents", + )) +} + +pub fn export_gemfile_command( + runtime: &ButlerRuntime, + gemfile: &Path, + project_file: Option<&Path>, + output: Option<&Path>, + format: ExportFormat, +) -> Result<(), ButlerError> { + let ruby = runtime.selected_ruby()?.ruby_executable_path(); + export(runtime, &ruby, gemfile, project_file, output, format) + .map_err(|error| ButlerError::General(error.to_string())) +} + +fn export( + runtime: &ButlerRuntime, + ruby: &Path, + gemfile: &Path, + project_file: Option<&Path>, + output: Option<&Path>, + format: ExportFormat, +) -> io::Result<()> { + let directory = gemfile.parent().unwrap(); + let default_project = directory.join("rbproject.toml"); + let project_path = project_file.unwrap_or(&default_project); + if output.is_some_and(|output| fs::canonicalize(output).is_ok_and(|path| path == gemfile)) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "The output must not overwrite the Gemfile", + )); + } + let project = match fs::read_to_string(project_path) { + Ok(project) if project.starts_with("# Generated by Ruby Butler. Do not edit.\n") => { + let mut settings: toml::Table = toml::from_str(&project).map_err(io::Error::other)?; + for key in ["dependencies", "sources", "groups", "bundle", "gemspecs"] { + settings.remove(key); + } + toml::to_string(&settings).map_err(io::Error::other)? + } + Ok(project) => project, + Err(error) if error.kind() == io::ErrorKind::NotFound && project_file.is_none() => { + let name = directory + .file_name() + .unwrap_or(OsStr::new("project")) + .to_string_lossy(); + let project = toml::Table::from_iter([( + "project".into(), + toml::Value::Table(toml::Table::from_iter([( + "name".into(), + toml::Value::String(name.into_owned()), + )])), + )]); + toml::to_string(&project).map_err(io::Error::other)? + } + Err(error) => return Err(error), + }; + let mut evaluator = Evaluator::new(ruby); + for (key, value) in runtime.env_vars(std::env::var("PATH").ok()) { + evaluator = evaluator.env(key, value); + } + let evaluation = evaluator.env("BUNDLE_GEMFILE", gemfile).evaluate(gemfile)?; + eprint!("{}{}", evaluation.stdout, evaluation.stderr); + let mut project = evaluation.manifest.merge_project_format(&project, format)?; + let prefix = match format { + ExportFormat::Toml => "#", + ExportFormat::Kdl => "//", + }; + let mut sources = format!("{prefix} Source Gemfile: {gemfile:?}\n"); + if project_path.is_file() { + sources.push_str(&format!("{prefix} Project settings: {project_path:?}\n")); + } + let guidance = format!("{prefix} Edit the source Gemfile and project settings instead.\n"); + project = project.replacen(&guidance, &sources, 1); + if let Some(output) = output { + write_project(output, &project)?; + eprintln!("Exported {} to {}", gemfile.display(), output.display()); + } else { + io::stdout().lock().write_all(project.as_bytes())?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn discovers_nearest_gemfile_and_prefers_gems_rb() { + let root = tempfile::tempdir().unwrap(); + let child = root.path().join("nested"); + fs::create_dir(&child).unwrap(); + fs::write(root.path().join("gems.rb"), "").unwrap(); + fs::write(child.join("Gemfile"), "").unwrap(); + assert_eq!( + find_gemfile(&child, None, None).unwrap(), + fs::canonicalize(child.join("Gemfile")).unwrap() + ); + fs::write(child.join("gems.rb"), "").unwrap(); + assert_eq!( + find_gemfile(&child, None, None).unwrap(), + fs::canonicalize(child.join("gems.rb")).unwrap() + ); + fs::remove_file(child.join("gems.rb")).unwrap(); + fs::remove_file(child.join("Gemfile")).unwrap(); + assert_eq!( + find_gemfile(&child, None, Some(OsStr::new(""))).unwrap(), + fs::canonicalize(root.path().join("gems.rb")).unwrap() + ); + } + + #[test] + fn explicit_file_overrides_environment_and_missing_overrides_do_not_fall_back() { + let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("Gemfile"), "").unwrap(); + fs::write(root.path().join("custom.rb"), "").unwrap(); + assert_eq!( + find_gemfile(root.path(), None, Some(OsStr::new("custom.rb"))).unwrap(), + fs::canonicalize(root.path().join("custom.rb")).unwrap() + ); + assert_eq!( + find_gemfile( + root.path(), + Some(Path::new("Gemfile")), + Some(OsStr::new("missing")) + ) + .unwrap(), + fs::canonicalize(root.path().join("Gemfile")).unwrap() + ); + for (explicit, environment) in [ + (Some(Path::new("missing")), None), + (None, Some(OsStr::new("missing"))), + ] { + assert_eq!( + find_gemfile(root.path(), explicit, environment) + .unwrap_err() + .kind(), + io::ErrorKind::NotFound + ); + } + } +} diff --git a/crates/rb-cli/src/commands/mod.rs b/crates/rb-cli/src/commands/mod.rs index 0bd260e..c4548b1 100644 --- a/crates/rb-cli/src/commands/mod.rs +++ b/crates/rb-cli/src/commands/mod.rs @@ -1,4 +1,5 @@ pub mod exec; +pub mod export_gemfile; pub mod help; pub mod info; pub mod new; diff --git a/crates/rb-cli/src/dispatch.rs b/crates/rb-cli/src/dispatch.rs index 51b54c7..c076868 100644 --- a/crates/rb-cli/src/dispatch.rs +++ b/crates/rb-cli/src/dispatch.rs @@ -8,8 +8,8 @@ use crate::runtime_helpers::CommandContext; use rb_core::butler::ButlerError; use crate::runtime_helpers::{ - bash_complete_command, new_command_wrapper, shell_integration_command_wrapper, - with_butler_runtime, + bash_complete_command, export_gemfile_command_wrapper, new_command_wrapper, + shell_integration_command_wrapper, with_butler_runtime, }; /// Dispatch command to appropriate handler @@ -21,6 +21,11 @@ pub fn dispatch_command( Commands::Version => version_command(), Commands::Help { command: help_cmd } => help_command(help_cmd), Commands::New => new_command_wrapper(), + Commands::ExportGemfile { + gemfile, + output, + format, + } => export_gemfile_command_wrapper(context, gemfile, output, format), Commands::ShellIntegration { shell } => shell_integration_command_wrapper(shell), Commands::BashComplete { line, point } => bash_complete_command(context, &line, &point), diff --git a/crates/rb-cli/src/help_formatter.rs b/crates/rb-cli/src/help_formatter.rs index 8fe7455..211a90d 100644 --- a/crates/rb-cli/src/help_formatter.rs +++ b/crates/rb-cli/src/help_formatter.rs @@ -19,7 +19,13 @@ pub fn print_custom_help(cmd: &clap::Command) { let workflow_commands = ["run", "exec", "sync"]; let diagnostic_commands = ["info"]; - let utility_commands = ["new", "version", "help", "shell-integration"]; + let utility_commands = [ + "new", + "export-gemfile", + "version", + "help", + "shell-integration", + ]; println!("{}", "Commands:".green().bold()); for subcmd in cmd.get_subcommands() { diff --git a/crates/rb-cli/src/lib.rs b/crates/rb-cli/src/lib.rs index 73008d8..31329f4 100644 --- a/crates/rb-cli/src/lib.rs +++ b/crates/rb-cli/src/lib.rs @@ -181,6 +181,25 @@ pub enum Commands { )] New, + /// 📄 Export Gemfile declarations into a project manifest without Bundler + #[command( + about = "📄 Export Gemfile declarations without Bundler", + next_help_heading = "Utility Commands" + )] + ExportGemfile { + /// Gemfile path (otherwise BUNDLE_GEMFILE, then gems.rb or Gemfile searched upward) + #[arg(value_hint = clap::ValueHint::FilePath)] + gemfile: Option, + + /// Write atomically to this file instead of stdout + #[arg(short, long, value_hint = clap::ValueHint::FilePath)] + output: Option, + + /// Output format + #[arg(long, value_enum, default_value = "toml")] + format: ProjectFormat, + }, + /// 📋 Display Ruby Butler version information #[command(about = "📋 Display Ruby Butler version information")] Version, @@ -214,6 +233,21 @@ pub enum Commands { }, } +#[derive(Clone, Copy, Debug, ValueEnum)] +pub enum ProjectFormat { + Toml, + Kdl, +} + +impl From for rb_gemfile::ExportFormat { + fn from(format: ProjectFormat) -> Self { + match format { + ProjectFormat::Toml => Self::Toml, + ProjectFormat::Kdl => Self::Kdl, + } + } +} + #[derive(Subcommand)] pub enum InfoCommands { /// 🔍 Detected Rubies and selected runtime diff --git a/crates/rb-cli/src/runtime_helpers.rs b/crates/rb-cli/src/runtime_helpers.rs index a9cc8e0..032181d 100644 --- a/crates/rb-cli/src/runtime_helpers.rs +++ b/crates/rb-cli/src/runtime_helpers.rs @@ -13,6 +13,24 @@ pub struct CommandContext { /// Create ButlerRuntime lazily and execute command with it /// Also updates the context with resolved values (e.g., which Ruby was actually selected) pub fn with_butler_runtime(context: &mut CommandContext, f: F) -> Result<(), ButlerError> +where + F: FnOnce(&ButlerRuntime) -> Result<(), ButlerError>, +{ + with_runtime(context, *context.config.no_bundler.get(), f) +} + +pub fn with_ruby_runtime(context: &mut CommandContext, f: F) -> Result<(), ButlerError> +where + F: FnOnce(&ButlerRuntime) -> Result<(), ButlerError>, +{ + with_runtime(context, true, f) +} + +fn with_runtime( + context: &mut CommandContext, + skip_bundler: bool, + f: F, +) -> Result<(), ButlerError> where F: FnOnce(&ButlerRuntime) -> Result<(), ButlerError>, { @@ -24,7 +42,7 @@ where rubies_dir, requested_version, Some(context.config.gem_home.get().clone()), - *context.config.no_bundler.get(), + skip_bundler, )?; if context.config.has_unresolved() @@ -37,6 +55,30 @@ where f(&butler_runtime) } +pub fn export_gemfile_command_wrapper( + context: &mut CommandContext, + gemfile: Option, + output: Option, + format: crate::ProjectFormat, +) -> Result<(), ButlerError> { + let gemfile = crate::commands::export_gemfile::find_gemfile( + &std::env::current_dir().map_err(|error| ButlerError::General(error.to_string()))?, + gemfile.as_deref(), + std::env::var_os("BUNDLE_GEMFILE").as_deref(), + ) + .map_err(|error| ButlerError::General(error.to_string()))?; + let project_file = context.project_file.clone(); + with_ruby_runtime(context, |runtime| { + crate::commands::export_gemfile::export_gemfile_command( + runtime, + &gemfile, + project_file.as_deref(), + output.as_deref(), + format.into(), + ) + }) +} + /// New command wrapper - no runtime needed pub fn new_command_wrapper() -> Result<(), ButlerError> { let current_dir = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")); diff --git a/crates/rb-cli/tests/export_gemfile_tests.rs b/crates/rb-cli/tests/export_gemfile_tests.rs new file mode 100644 index 0000000..039c585 --- /dev/null +++ b/crates/rb-cli/tests/export_gemfile_tests.rs @@ -0,0 +1,546 @@ +#![cfg(unix)] + +use std::{ + fs, + os::unix::fs::PermissionsExt, + path::Path, + process::{Command, Output}, +}; + +struct Fixture { + root: tempfile::TempDir, +} + +impl Fixture { + fn new() -> Self { + let root = tempfile::tempdir().unwrap(); + let bin = root.path().join("rubies/ruby-9.9.9/bin"); + fs::create_dir_all(&bin).unwrap(); + let ruby = + which::which(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())) + .unwrap(); + let quoted = ruby.to_str().unwrap().replace('\'', "'\\''"); + fs::write( + bin.join("ruby"), + format!("#!/bin/sh\nexec '{quoted}' \"$@\"\n"), + ) + .unwrap(); + fs::set_permissions(bin.join("ruby"), fs::Permissions::from_mode(0o755)).unwrap(); + fs::write(root.path().join("config.toml"), "").unwrap(); + fs::create_dir(root.path().join("tea-room")).unwrap(); + Self { root } + } + + fn project(&self) -> std::path::PathBuf { + self.root.path().join("tea-room") + } + + fn command(&self) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_rb")); + command + .current_dir(self.root.path()) + .args(["-c", "config.toml", "-r", "9.9.9"]) + .env("RB_RUBIES_DIR", self.root.path().join("rubies")) + .env_remove("BUNDLE_GEMFILE") + .env_remove("RB_PROJECT") + .env_remove("RB_WORK_DIR") + .env_remove("RB_NO_BUNDLER") + .env_remove("RB_LOG_LEVEL") + .env_remove("RB_VERBOSE") + .env_remove("RB_VERY_VERBOSE"); + command + } + + fn run(&self, args: &[&str]) -> Output { + self.command().args(args).output().unwrap() + } +} + +fn success(output: &Output) { + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +fn stdout(output: &Output) -> toml::Value { + normalize_export(toml::from_str(std::str::from_utf8(&output.stdout).unwrap()).unwrap()) +} + +fn read(path: impl AsRef) -> toml::Value { + normalize_export(toml::from_str(&fs::read_to_string(path).unwrap()).unwrap()) +} + +fn normalize_export(mut value: toml::Value) -> toml::Value { + let mut model = value.as_table().unwrap().clone(); + model.retain(|key, _| { + matches!( + key, + "bundle" | "dependencies" | "sources" | "groups" | "gemspecs" + ) + }); + let manifest: rb_gemfile::Manifest = toml::Value::Table(model).try_into().unwrap(); + let mut dependencies = toml::Table::new(); + for (name, dependency) in &manifest.dependencies { + let default = rb_gemfile::Dependency { + version: dependency.version.clone(), + ..Default::default() + }; + let entry = if dependency == &default && dependency.version.len() == 1 { + toml::Value::String(dependency.version[0].clone()) + } else { + toml::Value::try_from(dependency).unwrap() + }; + dependencies.insert(name.clone(), entry); + } + for (_, dependency) in &mut dependencies { + if let Some(table) = dependency.as_table_mut() { + table.remove("enabled"); + } + } + value + .as_table_mut() + .unwrap() + .insert("dependencies".into(), toml::Value::Table(dependencies)); + let bundle = value + .as_table_mut() + .unwrap() + .entry("bundle") + .or_insert_with(|| toml::Value::Table(toml::Table::new())); + if let Some(source) = manifest.bundle.source { + bundle + .as_table_mut() + .unwrap() + .insert("source".into(), toml::Value::String(source)); + } + value +} + +#[test] +fn exports_with_work_dir_and_initializes_missing_project_settings() { + let fixture = Fixture::new(); + fs::write( + fixture.project().join("Gemfile"), + "raise 'Bundler was loaded' if Gem.loaded_specs.key?('bundler'); source 'https://rubygems.org'; gem 'rake', require: false", + ) + .unwrap(); + let output = fixture.run(&["export-gemfile", "-C", "tea-room", "-R", "../rubies"]); + success(&output); + let project = stdout(&output); + assert_eq!(project["project"]["name"].as_str(), Some("tea-room")); + assert_eq!( + project["dependencies"]["rake"]["require"].as_bool(), + Some(false) + ); + assert!( + !std::str::from_utf8(&output.stdout) + .unwrap() + .contains("enabled") + ); + let raw: toml::Value = toml::from_str(std::str::from_utf8(&output.stdout).unwrap()).unwrap(); + assert!(raw.get("sources").is_some()); + assert!( + String::from_utf8_lossy(&output.stdout) + .starts_with("# Generated by Ruby Butler. Do not edit.\n") + ); + assert!(!fixture.project().join("rbproject.toml").exists()); + assert!(!fixture.project().join("Gemfile.lock").exists()); +} + +#[test] +fn selects_gems_rb_and_searches_parents() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "raise 'wrong file'").unwrap(); + fs::write(fixture.project().join("gems.rb"), "gem 'rake'").unwrap(); + fs::create_dir(fixture.project().join("nested")).unwrap(); + let output = fixture.run(&[ + "-C", + "tea-room/nested", + "-R", + "../../rubies", + "export-gemfile", + ]); + success(&output); + assert!(stdout(&output)["dependencies"].get("rake").is_some()); + assert!(!fixture.project().join("rbproject.toml").exists()); + assert!(!fixture.project().join("nested/rbproject.toml").exists()); +} + +#[test] +fn argument_overrides_environment_and_empty_environment_uses_discovery() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "gem 'rake'").unwrap(); + fs::write(fixture.project().join("custom.rb"), "raise 'wrong file'").unwrap(); + let output = fixture + .command() + .env("BUNDLE_GEMFILE", "tea-room/custom.rb") + .args(["export-gemfile", "tea-room/Gemfile"]) + .output() + .unwrap(); + success(&output); + let output = fixture + .command() + .env("BUNDLE_GEMFILE", "") + .args(["-C", "tea-room", "-R", "../rubies", "export-gemfile"]) + .output() + .unwrap(); + success(&output); +} + +#[test] +fn environment_paths_are_relative_to_work_dir_and_evaluation_receives_selected_file() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("custom.rb"), "raise 'wrong BUNDLE_GEMFILE' unless File.expand_path(ENV.fetch('BUNDLE_GEMFILE')) == __FILE__; gem 'rack'").unwrap(); + let output = fixture + .command() + .env("BUNDLE_GEMFILE", "custom.rb") + .args([ + "-C", + "tea-room", + "-R", + "../rubies", + "export-gemfile", + "--output", + "export/result.toml", + ]) + .output() + .unwrap(); + success(&output); + assert!( + read(fixture.project().join("export/result.toml"))["dependencies"] + .get("rack") + .is_some() + ); +} + +#[test] +fn global_project_input_preserves_settings_and_rejects_conflicts_without_writing() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "gem 'rake', '>= 13'").unwrap(); + let destination = fixture.root.path().join("custom.toml"); + fs::write( + &destination, + include_str!("fixtures/export_gemfile_tests/global_project_input_preserves_settings_and_rejects_conflicts_without_writing-1.toml"), + ) + .unwrap(); + let before = fs::read_to_string(&destination).unwrap(); + let output = fixture.run(&["-P", "custom.toml", "export-gemfile", "tea-room/Gemfile"]); + success(&output); + let parsed = stdout(&output); + assert_eq!(fs::read_to_string(&destination).unwrap(), before); + assert_eq!(parsed["project"]["name"].as_str(), Some("kept")); + assert_eq!(parsed["scripts"]["test"].as_str(), Some("rspec")); + let original = "[dependencies]\nrake='< 12'\n"; + fs::write(&destination, original).unwrap(); + let output = fixture.run(&["export-gemfile", "tea-room/Gemfile", "-P", "custom.toml"]); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Conflicting dependency rake.version") + ); + assert_eq!(fs::read_to_string(&destination).unwrap(), original); +} + +#[test] +fn failures_do_not_overwrite_destination_or_input() { + let fixture = Fixture::new(); + let gemfile = fixture.project().join("Gemfile"); + fs::write(&gemfile, "gem 'rake'").unwrap(); + let output = fixture.run(&[ + "export-gemfile", + "tea-room/Gemfile", + "-o", + "tea-room/Gemfile", + ]); + assert!(!output.status.success()); + assert_eq!(fs::read_to_string(&gemfile).unwrap(), "gem 'rake'"); + let project = fixture.project().join("rbproject.toml"); + fs::write(&project, "[project]\nname='kept'").unwrap(); + fs::write(&gemfile, "raise 'deliberate failure'").unwrap(); + let output = fixture.run(&["export-gemfile", "tea-room/Gemfile"]); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("deliberate failure")); + assert_eq!( + fs::read_to_string(project).unwrap(), + "[project]\nname='kept'" + ); + let output = fixture + .command() + .env("BUNDLE_GEMFILE", "missing") + .arg("export-gemfile") + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("Gemfile not found")); +} + +#[test] +fn utility_is_listed_in_help() { + let fixture = Fixture::new(); + let output = fixture.run(&["help"]); + success(&output); + assert!(String::from_utf8_lossy(&output.stdout).contains("export-gemfile")); + let output = fixture.run(&["help", "export-gemfile"]); + success(&output); + let help = String::from_utf8_lossy(&output.stdout); + assert!(help.contains("BUNDLE_GEMFILE")); + assert!(help.contains("--output")); + assert!(help.contains("[GEMFILE]")); +} + +#[test] +fn reexport_replaces_generated_declarations_and_preserves_project_settings() { + let fixture = Fixture::new(); + let gemfile = fixture.project().join("Gemfile"); + fs::write( + &gemfile, + "source 'https://rubygems.org'; gem 'rake', '>= 13'; gem 'removed'", + ) + .unwrap(); + let project = fixture.project().join("rbproject.toml"); + fs::write( + &project, + include_str!("fixtures/export_gemfile_tests/reexport_replaces_generated_declarations_and_preserves_project_settings-1.toml"), + ) + .unwrap(); + success(&fixture.run(&[ + "export-gemfile", + "tea-room/Gemfile", + "-o", + "tea-room/rbproject.toml", + ])); + fs::write(&gemfile, "source 'https://other.test'; gem 'rake', '>= 14'; install_if -> { ENV['WITH_DEBUG'] == '1' } do\n gem 'debug'\nend").unwrap(); + for enabled in ["1", "0"] { + let output = fixture + .command() + .env("WITH_DEBUG", enabled) + .args([ + "export-gemfile", + "tea-room/Gemfile", + "-o", + "tea-room/rbproject.toml", + ]) + .output() + .unwrap(); + success(&output); + assert!(output.stdout.is_empty()); + let parsed = read(&project); + assert_eq!(parsed["project"]["name"].as_str(), Some("kept")); + assert_eq!(parsed["scripts"]["test"].as_str(), Some("rspec")); + assert_eq!( + parsed["bundle"]["source"].as_str(), + Some("https://other.test") + ); + assert_eq!(parsed["dependencies"]["rake"].as_str(), Some(">= 14")); + assert!(parsed["dependencies"].get("removed").is_none()); + assert_eq!( + parsed["dependencies"].get("debug").is_some(), + enabled == "1" + ); + } +} + +#[test] +fn global_project_input_and_output_are_independent() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "gem 'rake'").unwrap(); + let input = fixture.project().join("from-env.toml"); + let original = "[project]\nname='from environment'\n"; + fs::write(&input, original).unwrap(); + let output = fixture + .command() + .env("RB_WORK_DIR", "tea-room") + .env("RB_PROJECT", "from-env.toml") + .args(["export-gemfile", "--output", "chosen.toml"]) + .output() + .unwrap(); + success(&output); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("Exported")); + assert_eq!( + read(fixture.project().join("chosen.toml"))["project"]["name"].as_str(), + Some("from environment") + ); + assert_eq!(fs::read_to_string(&input).unwrap(), original); + assert!(!fixture.project().join("rbproject.toml").exists()); + let output = fixture + .command() + .env("RB_WORK_DIR", "tea-room") + .env("RB_PROJECT", "from-env.toml") + .arg("export-gemfile") + .output() + .unwrap(); + success(&output); + assert_eq!( + stdout(&output)["project"]["name"].as_str(), + Some("from environment") + ); + assert_eq!(fs::read_to_string(input).unwrap(), original); +} + +#[test] +fn global_project_flag_overrides_environment_before_and_after_command() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "gem 'rake'").unwrap(); + fs::write( + fixture.project().join("settings.toml"), + "[project]\nname='CLI settings'\n", + ) + .unwrap(); + for args in [ + vec!["-C", "tea-room", "-P", "settings.toml", "export-gemfile"], + vec!["export-gemfile", "-C", "tea-room", "-P", "settings.toml"], + ] { + let output = fixture + .command() + .env("RB_PROJECT", "missing-env.toml") + .args(args) + .output() + .unwrap(); + success(&output); + assert_eq!( + stdout(&output)["project"]["name"].as_str(), + Some("CLI settings") + ); + assert!(!fixture.project().join("rbproject.toml").exists()); + } +} + +#[test] +fn diagnostics_do_not_contaminate_stdout_and_missing_project_override_is_an_error() { + let fixture = Fixture::new(); + fs::write( + fixture.project().join("Gemfile"), + "puts 'Gemfile message'; warn 'Gemfile warning'; gem 'rake'", + ) + .unwrap(); + let output = fixture.run(&["-v", "export-gemfile", "tea-room/Gemfile"]); + success(&output); + assert!(stdout(&output)["dependencies"].get("rake").is_some()); + let diagnostics = String::from_utf8_lossy(&output.stderr); + assert!(diagnostics.contains("Gemfile message")); + assert!(diagnostics.contains("Gemfile warning")); + assert!(!String::from_utf8_lossy(&output.stdout).contains("Gemfile message")); + let destination = fixture.root.path().join("result.toml"); + fs::write(&destination, "existing output").unwrap(); + let output = fixture.run(&[ + "export-gemfile", + "tea-room/Gemfile", + "-P", + "missing.toml", + "-o", + "result.toml", + ]); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + assert_eq!(fs::read_to_string(destination).unwrap(), "existing output"); +} + +#[test] +fn optional_kdl_output_uses_the_same_global_project_settings() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "gem 'rails', '~> 8.0'; source 'https://gems.example.com' do\n gem 'internal', '~> 2.0', require: false\nend").unwrap(); + fs::write( + fixture.project().join("settings.toml"), + "[project]\nname='shared settings'\n", + ) + .unwrap(); + for output_file in [None, Some("result.kdl")] { + let mut command = fixture.command(); + command + .env("RB_WORK_DIR", "tea-room") + .env("RB_PROJECT", "settings.toml") + .args(["export-gemfile", "--format", "kdl"]); + if let Some(path) = output_file { + command.args(["--output", path]); + } + let output = command.output().unwrap(); + success(&output); + let text = if let Some(path) = output_file { + assert!(output.stdout.is_empty()); + fs::read_to_string(fixture.project().join(path)).unwrap() + } else { + String::from_utf8(output.stdout).unwrap() + }; + let document: kdl::KdlDocument = text.parse().unwrap(); + assert_eq!( + document + .get("project") + .unwrap() + .children() + .unwrap() + .get("name") + .unwrap() + .get(0) + .unwrap() + .as_string(), + Some("shared settings") + ); + let source = document + .nodes() + .iter() + .find(|node| node.name().value() == "source") + .unwrap(); + assert_eq!( + source.get(0).unwrap().as_string(), + Some("https://gems.example.com") + ); + let gem = source + .children() + .unwrap() + .nodes() + .iter() + .find(|node| node.get(0).and_then(kdl::KdlValue::as_string) == Some("internal")) + .unwrap(); + assert_eq!(gem.get("require").unwrap().as_bool(), Some(false)); + } + assert!(!fixture.project().join("rbproject.toml").exists()); + let output = fixture.run(&["export-gemfile", "--format", "yaml"]); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); +} + +#[test] +fn toml_source_blocks_from_global_settings_merge_into_export() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "gem 'rails', '~> 8.0'").unwrap(); + fs::write( + fixture.project().join("settings.toml"), + "[[sources]]\nurl='https://gems.example.com'\n[sources.dependencies]\ninternal='~> 2.0'\n", + ) + .unwrap(); + let output = fixture.run(&[ + "export-gemfile", + "tea-room/Gemfile", + "-P", + "tea-room/settings.toml", + ]); + success(&output); + let parsed = stdout(&output); + assert_eq!(parsed["dependencies"]["rails"].as_str(), Some("~> 8.0")); + assert_eq!( + parsed["dependencies"]["internal"]["version"].as_str(), + Some("~> 2.0") + ); +} + +#[test] +fn legacy_generated_header_refreshes_dependencies_and_identifies_sources() { + let fixture = Fixture::new(); + fs::write(fixture.project().join("Gemfile"), "gem 'rake'").unwrap(); + fs::write( + fixture.project().join("rbproject.toml"), + include_str!("fixtures/export_gemfile_tests/legacy_generated.toml"), + ) + .unwrap(); + let output = fixture.run(&["-C", "tea-room", "export-gemfile"]); + success(&output); + let parsed = stdout(&output); + assert_eq!(parsed["project"]["name"].as_str(), Some("kept")); + assert!(parsed["dependencies"].get("removed").is_none()); + assert!(parsed["dependencies"].get("rake").is_some()); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains("# Source Gemfile:")); + assert!(text.contains("# Project settings:")); + assert!(text.contains("Regenerate with rb export-gemfile")); +} diff --git a/crates/rb-cli/tests/fixtures/export_gemfile_tests/global_project_input_preserves_settings_and_rejects_conflicts_without_writing-1.toml b/crates/rb-cli/tests/fixtures/export_gemfile_tests/global_project_input_preserves_settings_and_rejects_conflicts_without_writing-1.toml new file mode 100644 index 0000000..be6c193 --- /dev/null +++ b/crates/rb-cli/tests/fixtures/export_gemfile_tests/global_project_input_preserves_settings_and_rejects_conflicts_without_writing-1.toml @@ -0,0 +1,4 @@ +[project] +name='kept' +[scripts] +test='rspec' diff --git a/crates/rb-cli/tests/fixtures/export_gemfile_tests/legacy_generated.toml b/crates/rb-cli/tests/fixtures/export_gemfile_tests/legacy_generated.toml new file mode 100644 index 0000000..f92e102 --- /dev/null +++ b/crates/rb-cli/tests/fixtures/export_gemfile_tests/legacy_generated.toml @@ -0,0 +1,5 @@ +# Generated by Ruby Butler. Do not edit. +[project] +name='kept' +[dependencies] +removed='>= 0' diff --git a/crates/rb-cli/tests/fixtures/export_gemfile_tests/reexport_replaces_generated_declarations_and_preserves_project_settings-1.toml b/crates/rb-cli/tests/fixtures/export_gemfile_tests/reexport_replaces_generated_declarations_and_preserves_project_settings-1.toml new file mode 100644 index 0000000..be6c193 --- /dev/null +++ b/crates/rb-cli/tests/fixtures/export_gemfile_tests/reexport_replaces_generated_declarations_and_preserves_project_settings-1.toml @@ -0,0 +1,4 @@ +[project] +name='kept' +[scripts] +test='rspec' diff --git a/crates/rb-gemfile/Cargo.toml b/crates/rb-gemfile/Cargo.toml new file mode 100644 index 0000000..1ed909c --- /dev/null +++ b/crates/rb-gemfile/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "rb-gemfile" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Evaluate Ruby Gemfiles into dependency manifests without Bundler" + +[dependencies] +dunce = "1.0.5" +kdl = "6.0.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +sha2 = "0.10.9" +tempfile = "3.21.0" +toml = "0.8" +toml_edit = { version = "0.22", features = ["serde"] } +which = "6.0" diff --git a/crates/rb-gemfile/README.md b/crates/rb-gemfile/README.md new file mode 100644 index 0000000..5646c70 --- /dev/null +++ b/crates/rb-gemfile/README.md @@ -0,0 +1,31 @@ +# rb-gemfile + +Evaluate trusted Gemfiles into dependency manifests without loading Bundler. An embedded Ruby evaluator collects declarations; Rust provides typed data, TOML/KDL export and optional caching. Ruby and RubyGems are still required. This crate does not resolve versions, install gems or generate lockfiles. + +```rust,no_run +use rb_gemfile::{Evaluator, write_project}; + +let evaluation = Evaluator::new("ruby").evaluate("Gemfile")?; +let project = evaluation.manifest.merge_project("[project]\nname = 'example'\n")?; +write_project(".rb/rbproject.toml", &project)?; +# Ok::<(), Box>(()) +``` + +| API | Purpose | +| --- | --- | +| `Evaluator::evaluate` | Run a Gemfile and return its manifest, input paths and captured output. | +| `Manifest::to_toml` / `to_kdl` | Export active declarations with explicit source and group blocks. | +| `Manifest::merge_project` / `merge_project_format` | Merge with TOML project settings, rejecting explicit conflicts. | +| `Manifest::from_kdl` | Read KDL declarations; TOML uses Serde deserialization. | +| `SnapshotCache::evaluate` | Reuse deterministic evaluations when fingerprinted inputs are unchanged. | +| `write_project` | Write a generated file atomically. | + +Supports groups, platforms, conditions, require settings, registry/Git/path sources, included Gemfiles and local gemspecs. Repeated declarations remain separate in `Dependency::variants`; exports omit inactive declarations. Bundler compatibility helpers are limited: plugins are recorded, not installed or executed, and source `cooldown` is accepted but not enforced. + +Gemfiles execute arbitrary Ruby: evaluate only trusted inputs. For caching, declare external files/directories with `input` and unread generated files with `output`. The project directory is fingerprinted automatically. Use uncached evaluation for time, network, subprocess results or side effects. + +The CLI exposes this through `rb export-gemfile`, with `--format kdl` for KDL output. Exported dependencies are not yet consumed by `rb-core`. + +Tested against 1,477 snapshots from the public [Gemfile corpus](https://github.com/RubyElders/gemfile-corpus), using Ruby 3.4.1 and Bundler 2.6.2 as a comparison: 1,318 evaluated and exported to TOML successfully; 159 failed, of which 157 also failed Bundler. Most failures involved missing companion files. Two Git-option combinations accepted by Bundler remain unsupported. This checks evaluation/export, not installation or complete manifest equivalence. + +Run `cargo test -p rb-gemfile`. Direct Ruby tests use `ruby crates/rb-gemfile/tests/ruby/evaluator_test.rb` with Minitest 5. `RB_GEMFILE_RUBY` selects Ruby for Rust tests and the `evaluate` example. diff --git a/crates/rb-gemfile/assets/compatibility.rb b/crates/rb-gemfile/assets/compatibility.rb new file mode 100644 index 0000000..72e5279 --- /dev/null +++ b/crates/rb-gemfile/assets/compatibility.rb @@ -0,0 +1,21 @@ +module Bundler + VERSION = "2.5.0" + + def self.read_file(path) + RubyButler.evaluator.read_file(path) + end + + def self.load_gemspec(path, validate = false) + RubyButler.evaluator.load_gemspec(path, validate) + end + + module Plugin + def self.index + self + end + + def self.load_paths(_name) + [] + end + end +end diff --git a/crates/rb-gemfile/assets/evaluate.rb b/crates/rb-gemfile/assets/evaluate.rb new file mode 100644 index 0000000..2fbd271 --- /dev/null +++ b/crates/rb-gemfile/assets/evaluate.rb @@ -0,0 +1,15 @@ +require_relative "gemfile" +require_relative "sources" +require_relative "gemspec" +require_relative "compatibility" + +begin + evaluator = RubyButler::Gemfile.new + RubyButler.define_singleton_method(:evaluator) { evaluator } + evaluator.eval_gemfile(ARGV.fetch(0)) + File.write(ARGV.fetch(1), JSON.generate(manifest: evaluator.manifest, inputs: evaluator.inputs)) +rescue StandardError, ScriptError => error + warn "#{error.class}: #{error.message}" + warn error.backtrace.first(8).join("\n") + exit 1 +end diff --git a/crates/rb-gemfile/assets/gemfile.rb b/crates/rb-gemfile/assets/gemfile.rb new file mode 100644 index 0000000..9b3e8d2 --- /dev/null +++ b/crates/rb-gemfile/assets/gemfile.rb @@ -0,0 +1,188 @@ +require "json" +require "rubygems" +require "pathname" + +module RubyButler + class Gemfile + attr_reader :inputs + + def initialize + @bundle = { source: nil, ruby: [], optional_groups: [] } + @declarations = {} + @dependencies = [] + @gemspecs = [] + @gemspec_development = {} + @inputs = [] + @stack = [] + @context = { groups: [], platforms: [], conditions: [] } + @git_sources = { + "github" => ->(name) { "https://github.com/#{name.include?('/') ? name : "#{name}/#{name}"}.git" }, + "gitlab" => ->(name) { "https://gitlab.com/#{name.include?('/') ? name : "#{name}/#{name}"}.git" }, + "gist" => ->(name) { "https://gist.github.com/#{name}.git" }, + "bitbucket" => ->(name) { + user, repo = name.split('/') + "https://#{user}@bitbucket.org/#{user}/#{repo || user}.git" + } + } + end + + def dependencies + @dependencies + end + + def plugin(name, *requirements, **options) + raise ArgumentError, "Plugin options are unsupported" unless options.empty? + requirements = Gem::Requirement.new(requirements.flatten.compact).as_list + @bundle[:plugins] ||= [] + @bundle[:plugins] << { name: name, version: requirements } + end + + def manifest + names = @dependencies.map(&:name) + { bundle: @bundle, dependencies: @declarations.select { |name, _| names.include?(name) }, gemspecs: @gemspecs } + end + + def eval_gemfile(path, contents = nil) + path = File.expand_path(path, @stack.empty? ? Dir.pwd : File.dirname(@stack.last)) + raise ArgumentError, "Recursive eval_gemfile: #{path}" if @stack.include?(path) + @inputs << path unless @inputs.include?(path) + @stack.push(path) + begin + instance_eval(contents || read_file(path), path, 1) + ensure + @stack.pop + end + end + + def read_file(path) + path = File.expand_path(path) + @inputs << path unless @inputs.include?(path) + File.read(path) + end + + def lockfile(path) + @bundle[:lockfile] = File.expand_path(path, File.dirname(@stack.last)) + end + + def env(value, &block) + scoped({ environment: value }, &block) + end + + def gem(name, *requirements, **options) + options = requirements.pop.merge(options) if requirements.last.is_a?(Hash) + options = options.transform_keys(&:to_sym) + @git_sources.each do |key, expansion| + if options.key?(key.to_sym) + raise ArgumentError, "Conflicting Git sources for #{name}" if options[:git] + expansion = expansion.call(options.delete(key.to_sym)) + expansion = { git: expansion } if expansion.is_a?(String) + expansion = expansion.transform_keys(&:to_sym) + raise ArgumentError, "Conflicting Git shortcut options for #{name}" unless (expansion.keys & options.keys).empty? + options.merge!(expansion) + end + end + valid = %i[group groups platform platforms require source git path branch tag ref rev glob submodules force_ruby_platform install_if] + unknown = options.keys - valid + raise ArgumentError, "Unsupported gem options: #{unknown.join(', ')}" unless unknown.empty? + raise ArgumentError, "Gem names must be strings" unless name.is_a?(String) + raise ArgumentError, "Empty gem name" if name.empty? + raise ArgumentError, "Gem names cannot contain whitespace" if name.match?(/\s/) + @declarations.delete(name) unless @dependencies.any? { |dependency| dependency.name == name } + options[:require] = false if options.key?(:require) && options[:require].nil? + requirements = requirements.flatten.compact.map(&:to_s) + requirements = [">= 0"] if requirements.empty? + Gem::Requirement.new(requirements) + if @gemspec_development.delete(name) && (existing = @declarations.delete(name)) + requirements = (existing[:version] + requirements).uniq + end + groups = @context[:groups] + Array(options[:group]) + Array(options[:groups]) + platforms = @context[:platforms] + Array(options[:platform]) + Array(options[:platforms]) + platforms.each do |platform| + unless platform.to_s.match?(/\A(?:ruby|mri|rbx|truffleruby|jruby|windows|mswin|mswin64|mingw|x64_mingw)(?:_\d+)?\z/) + raise ArgumentError, "Unknown platform: #{platform}" + end + end + dependency = @context.reject { |key, _| %i[groups platforms conditions environment].include?(key) } + dependency.compact! + if %i[source git path].any? { |key| options.key?(key) } + dependency.reject! { |key, _| %i[source git path branch tag rev glob submodules].include?(key) } + end + dependency.merge!(options.reject { |key, _| %i[group groups platform platforms install_if].include?(key) }) + raise ArgumentError, "Specify ref or rev, not both for #{name}" if dependency[:ref] && dependency[:rev] + dependency[:rev] = dependency.delete(:ref) if dependency.key?(:ref) + if dependency[:path] + dependency[:path] = File.expand_path(dependency[:path], File.dirname(@stack.last)) + end + raise ArgumentError, "Conflicting sources for #{name}" if %i[source git path].count { |key| dependency[key] } > 1 + raise ArgumentError, "Conflicting Git selectors for #{name}" if %i[branch tag rev].count { |key| dependency[key] } > 1 + if !dependency[:git] && %i[branch tag rev submodules].any? { |key| dependency.key?(key) } + raise ArgumentError, "Git options require a Git source for #{name}" + end + dependency.merge!(version: requirements, groups: groups.empty? ? ["default"] : groups.map(&:to_s).uniq, + platforms: platforms.map(&:to_s).uniq, + enabled: (@context[:conditions] + Array(options[:install_if])).all? { |value| condition(value) } && environment_enabled?) + if (current = @declarations[name]) + unless Gem::Requirement.new(current[:version]) == Gem::Requirement.new(dependency[:version]) + raise ArgumentError, "Conflicting declarations for #{name}" + end + source_keys = %i[source git path branch tag rev glob submodules] + unless source_keys.all? { |key| current[key] == dependency[key] } + raise ArgumentError, "Conflicting sources for #{name}" + end + primary = current.reject { |key, _| key == :variants } + unless primary == dependency || Array(current[:variants]).include?(dependency) + (current[:variants] ||= []) << dependency + end + else + @declarations[name] = dependency + end + refresh_dependency(name) + end + + def group(*names, optional: false, &block) + @bundle[:optional_groups] |= names.map(&:to_s) if optional + scoped({ groups: @context[:groups] + names }, &block) + end + + def platforms(*names, &block) + scoped({ platforms: @context[:platforms] + names }, &block) + end + alias platform platforms + + def install_if(*conditions, &block) + scoped({ conditions: @context[:conditions] + conditions }, &block) + end + + private + + def refresh_dependency(name) + @dependencies.reject! { |dependency| dependency.name == name } + @dependencies << Gem::Dependency.new(name, @declarations.fetch(name).fetch(:version)) + end + + def environment_enabled? + value = @context[:environment] + return true unless value + return !!ENV[value.to_s] unless value.is_a?(Hash) + value.all? do |name, expected| + actual = ENV[name.to_s] + actual && (expected.is_a?(Regexp) ? expected.match?(actual) : actual == expected) + end + end + + def condition(value) + !!(value.respond_to?(:call) ? value.call : value) + end + + def scoped(values) + raise ArgumentError, "This declaration requires a block" unless block_given? + previous = @context + @context = previous.merge(values) + begin + yield + ensure + @context = previous + end + end + end +end diff --git a/crates/rb-gemfile/assets/gemspec.rb b/crates/rb-gemfile/assets/gemspec.rb new file mode 100644 index 0000000..80c6ea0 --- /dev/null +++ b/crates/rb-gemfile/assets/gemspec.rb @@ -0,0 +1,90 @@ +module RubyButler + class Gemfile + def ruby(*versions, **options) + options = versions.pop.merge(options) if versions.last.is_a?(Hash) + options = options.transform_keys(&:to_sym) + unknown = options.keys - %i[engine engine_version file patchlevel] + raise ArgumentError, "Unsupported ruby options: #{unknown.join(', ')}" unless unknown.empty? + engine, engine_version, file, patchlevel = options.values_at(:engine, :engine_version, :file, :patchlevel) + if file + raise ArgumentError, "ruby accepts versions or file, not both" unless versions.empty? + location = File.expand_path(file, File.dirname(@stack.last)) + @inputs << location unless @inputs.include?(location) + text = read_file(location) + match = /^ruby[\s-]*(?:=\s*)?(?:"([^"]+)"|'([^']+)'|([^\s#"']+))/.match(text) + versions = [match ? match.captures.compact.first : text.strip] + end + raise ArgumentError, "ruby requires a version" if versions.empty? + versions = versions.flatten + Gem::Requirement.new(versions) + raise ArgumentError, "engine and engine_version must be specified together" if engine.nil? != engine_version.nil? + if engine == "ruby" && engine_version && versions != Array(engine_version) + raise ArgumentError, "Ruby requirements must match engine_version for MRI" + end + @bundle.merge!(ruby: versions.map(&:to_s), engine: engine, engine_version: engine_version, patchlevel: patchlevel&.to_s) + end + + def gemspec(options = {}, **keywords) + options = options.merge(keywords).transform_keys(&:to_sym) + unknown = options.keys - %i[path name glob development_group require] + raise ArgumentError, "Unsupported gemspec options: #{unknown.join(', ')}" unless unknown.empty? + path = options.fetch(:path, ".") + name = options[:name] + glob = options[:glob] + development_group = options.fetch(:development_group, :development) + directory = File.expand_path(path, File.dirname(@stack.last)) + specs = Dir.glob(File.join(directory, "{*,.*}.gemspec")).uniq.map { |file| load_gemspec(file) } + specs.select! { |spec| spec.name == name } if name + groups = specs.group_by { |spec| [spec.name, spec.version] } + raise ArgumentError, "Expected one gemspec in #{directory}, found #{groups.length}" unless groups.length == 1 + choices = groups.values.first + spec = choices.find { |candidate| candidate.platform.to_s == Gem::Platform.local.to_s } || + choices.find { |candidate| candidate.platform.to_s == "ruby" } || choices.first + @gemspecs << { + name: spec.name, version: spec.version.to_s, platform: spec.platform.to_s, path: directory, + required_ruby_version: spec.required_ruby_version.as_list, + required_rubygems_version: spec.required_rubygems_version.as_list, + runtime_dependencies: package_dependencies(spec.runtime_dependencies), + development_dependencies: package_dependencies(spec.development_dependencies) + } + source = { path: directory } + source[:glob] = glob if glob + gem(spec.name, "= #{spec.version}", **source) + spec.development_dependencies.each do |dependency| + if (existing = @declarations[dependency.name]) + requirements = (existing[:version] + dependency.requirement.as_list).uniq + existing[:version] = requirements + Array(existing[:variants]).each { |variant| variant[:version] = requirements } + refresh_dependency(dependency.name) + else + gem(dependency.name, *dependency.requirement.as_list, group: development_group) + @gemspec_development[dependency.name] = true + end + end + end + + def load_gemspec(path, validate = false) + path = File.expand_path(path) + contents = read_file(path) + spec = Dir.chdir(File.dirname(path)) do + if contents.start_with?("---") + Gem::Specification.from_yaml(contents) + else + eval(contents, TOPLEVEL_BINDING.dup, path, 1) + end + end + raise ArgumentError, "Unable to evaluate #{path}" unless spec.is_a?(Gem::Specification) + spec.loaded_from = path + spec.validate if validate + spec + end + + private + + def package_dependencies(dependencies) + dependencies.group_by(&:name).transform_values do |declarations| + declarations.flat_map { |dependency| dependency.requirement.as_list }.uniq + end + end + end +end diff --git a/crates/rb-gemfile/assets/sources.rb b/crates/rb-gemfile/assets/sources.rb new file mode 100644 index 0000000..f47974b --- /dev/null +++ b/crates/rb-gemfile/assets/sources.rb @@ -0,0 +1,54 @@ +module RubyButler + class Gemfile + def source(url, options = {}, **keywords, &block) + options = options.merge(keywords).transform_keys(&:to_sym) + unknown = options.keys - [:cooldown] + raise ArgumentError, "Unsupported source options: #{unknown.join(', ')}" unless unknown.empty? + cooldown = options[:cooldown] + unless cooldown.nil? || (cooldown.is_a?(Integer) && cooldown >= 0) + raise ArgumentError, "Expected cooldown to be a non-negative integer" + end + if block + scoped(source_context.merge(source: url.to_s), &block) + else + if @bundle[:source] && @bundle[:source] != url.to_s + raise ArgumentError, "Multiple global sources are unsupported; use source blocks" + end + @bundle[:source] = url.to_s + end + end + + def git(url, **options, &block) + unknown = options.keys - %i[branch tag ref rev glob submodules] + raise ArgumentError, "Unsupported Git options: #{unknown.join(', ')}" unless unknown.empty? + scoped(source_context.merge(options).merge(git: url.to_s), &block) + end + + def path(directory, **options, &block) + unknown = options.keys - [:glob] + raise ArgumentError, "Unsupported path options: #{unknown.join(', ')}" unless unknown.empty? + directory = File.expand_path(directory, File.dirname(@stack.last)) + scoped(source_context.merge(options).merge(path: directory), &block) + end + + def git_source(name, &block) + raise ArgumentError, "git_source requires a block" unless block + @git_sources[name.to_s] = block + end + + def github(repository, **options, &block) + expanded = @git_sources.fetch("github").call(repository) + expanded = { git: expanded } if expanded.is_a?(String) + expanded = expanded.transform_keys(&:to_sym) + raise ArgumentError, "Conflicting Git shortcut options" unless (expanded.keys & options.keys).empty? + url = expanded.delete(:git) + git(url, **expanded.merge(options), &block) + end + + private + + def source_context + %i[source git path branch tag ref rev glob submodules].to_h { |key| [key, nil] } + end + end +end diff --git a/crates/rb-gemfile/examples/evaluate.rs b/crates/rb-gemfile/examples/evaluate.rs new file mode 100644 index 0000000..c184ab9 --- /dev/null +++ b/crates/rb-gemfile/examples/evaluate.rs @@ -0,0 +1,10 @@ +use rb_gemfile::Evaluator; + +fn main() -> Result<(), Box> { + let gemfile = std::env::args().nth(1).unwrap_or_else(|| "Gemfile".into()); + let ruby = std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into()); + let result = Evaluator::new(ruby).evaluate(gemfile)?; + eprint!("{}{}", result.stdout, result.stderr); + print!("{}", result.manifest.to_toml()?); + Ok(()) +} diff --git a/crates/rb-gemfile/src/evaluator.rs b/crates/rb-gemfile/src/evaluator.rs new file mode 100644 index 0000000..e514992 --- /dev/null +++ b/crates/rb-gemfile/src/evaluator.rs @@ -0,0 +1,117 @@ +use crate::Manifest; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + ffi::{OsStr, OsString}, + io, + path::{Path, PathBuf}, + process::Command, +}; + +/// Executes a trusted Gemfile using the selected Ruby and its RubyGems API. +pub struct Evaluator { + pub(crate) ruby: PathBuf, + pub(crate) environment: BTreeMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Evaluation { + pub manifest: Manifest, + pub inputs: Vec, + #[serde(default)] + pub stdout: String, + #[serde(default)] + pub stderr: String, +} + +impl Evaluator { + pub fn new(ruby: impl Into) -> Self { + Self { + ruby: ruby.into(), + environment: BTreeMap::new(), + } + } + + pub fn env(mut self, name: impl AsRef, value: impl AsRef) -> Self { + self.environment + .insert(name.as_ref().to_owned(), value.as_ref().to_owned()); + self + } + + pub fn evaluate(&self, gemfile: impl AsRef) -> io::Result { + let gemfile = gemfile_path(gemfile.as_ref())?; + let directory = tempfile::tempdir()?; + let result = directory.path().join("manifest.json"); + for (name, source) in SOURCES { + std::fs::write(directory.path().join(name), source)?; + } + let ruby = self.ruby_executable()?; + let output = Command::new(ruby) + .envs(&self.environment) + .env_remove("RUBYOPT") + .arg(directory.path().join("evaluate.rb")) + .arg(&gemfile) + .arg(&result) + .current_dir(gemfile.parent().unwrap()) + .output()?; + if !output.status.success() { + return Err(io::Error::other(format!( + "Gemfile evaluation failed ({}): {}", + output.status, + String::from_utf8_lossy(&output.stderr) + ))); + } + let mut evaluation: Evaluation = + serde_json::from_slice(&std::fs::read(result).map_err(|error| { + io::Error::other(format!("Ruby did not produce a Gemfile manifest: {error}")) + })?) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + evaluation.stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + evaluation.stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + evaluation.inputs = evaluation + .inputs + .iter() + .map(dunce::canonicalize) + .collect::>()?; + for dependency in evaluation.manifest.dependencies.values() { + dependency.validate().map_err(io::Error::other)?; + } + Ok(evaluation) + } + + pub(crate) fn ruby_executable(&self) -> io::Result { + let ruby = which::which_in( + &self.ruby, + self.environment + .get(OsStr::new("PATH")) + .cloned() + .or_else(|| std::env::var_os("PATH")), + std::env::current_dir()?, + ) + .map_err(|error| io::Error::new(io::ErrorKind::NotFound, error))?; + dunce::canonicalize(ruby) + } +} + +pub(crate) fn gemfile_path(path: &Path) -> io::Result { + let path = dunce::canonicalize(path)?; + if !std::fs::metadata(&path)?.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Gemfile must be a file", + )); + } + Ok(path) +} + +pub(crate) const SOURCES: &[(&str, &str)] = &[ + ("evaluate.rb", include_str!("../assets/evaluate.rb")), + ("gemfile.rb", include_str!("../assets/gemfile.rb")), + ("sources.rb", include_str!("../assets/sources.rb")), + ("gemspec.rb", include_str!("../assets/gemspec.rb")), + ( + "compatibility.rb", + include_str!("../assets/compatibility.rb"), + ), +]; diff --git a/crates/rb-gemfile/src/format.rs b/crates/rb-gemfile/src/format.rs new file mode 100644 index 0000000..472358e --- /dev/null +++ b/crates/rb-gemfile/src/format.rs @@ -0,0 +1,183 @@ +use crate::Dependency; +use serde::{Deserialize, Deserializer}; +use std::collections::BTreeMap; +use toml::{Table, Value}; + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum ExportFormat { + #[default] + Toml, + Kdl, +} + +pub(crate) fn is_source(key: &str) -> bool { + key.contains("://") +} + +pub(crate) fn expand_dependencies(dependencies: Table) -> Result { + let mut expanded = Table::new(); + for (key, value) in dependencies { + let entries = if is_source(&key) { + value + .as_table() + .ok_or_else(|| "Source dependencies must be a table".to_string())? + .clone() + } else { + Table::from_iter([(key.clone(), value)]) + }; + for (name, mut value) in entries { + if let Value::Array(declarations) = value { + let mut declarations = declarations.into_iter(); + value = declarations + .next() + .ok_or("Empty dependency declaration list")?; + if let Value::String(version) = value { + value = Value::Table(Table::from_iter([( + "version".into(), + Value::String(version), + )])); + } + let variants = declarations + .map(|value| match value { + Value::String(version) => Value::Table(Table::from_iter([( + "version".into(), + Value::String(version), + )])), + value => value, + }) + .collect::>(); + if !variants.is_empty() { + value + .as_table_mut() + .ok_or("Dependency must be a string or table")? + .insert("variants".into(), Value::Array(variants)); + } + } + if let Value::String(version) = value { + value = Value::Table(Table::from_iter([( + "version".into(), + Value::String(version), + )])); + } + if is_source(&key) { + inherit_source(&mut value, &key)?; + } + if expanded.insert(name.clone(), value).is_some() { + return Err(format!("Duplicate dependency {name} across source blocks")); + } + } + } + Ok(expanded) +} + +pub(crate) fn inherit_source(value: &mut Value, source: &str) -> Result<(), String> { + let table = value + .as_table_mut() + .ok_or_else(|| "Dependency must be a string or table".to_string())?; + if table.contains_key("git") + || table.contains_key("path") + || table + .get("source") + .is_some_and(|value| value.as_str() != Some(source)) + { + return Err("Dependency conflicts with its source block".into()); + } + table.insert("source".into(), Value::String(source.into())); + if let Some(Value::Array(variants)) = table.get_mut("variants") { + for variant in variants { + inherit_source(variant, source)?; + } + } + Ok(()) +} + +pub(crate) fn deserialize_dependencies<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let dependencies = Table::deserialize(deserializer)?; + let expanded = expand_dependencies(dependencies).map_err(serde::de::Error::custom)?; + expanded + .into_iter() + .map(|(name, value)| { + let dependency: Dependency = value.try_into().map_err(serde::de::Error::custom)?; + dependency.validate().map_err(serde::de::Error::custom)?; + Ok((name, dependency)) + }) + .collect() +} + +pub(crate) fn compact(mut value: Value) -> Value { + let table = value.as_table_mut().unwrap(); + if table + .get("groups") + .and_then(Value::as_array) + .is_some_and(|groups| groups == &[Value::String("default".into())]) + { + table.remove("groups"); + } + if let Some(Value::Array(variants)) = table.get_mut("variants") { + for variant in variants { + *variant = compact(variant.clone()); + if let Value::String(version) = variant { + *variant = Value::Table(Table::from_iter([( + "version".into(), + Value::String(version.clone()), + )])); + } + } + } + if table.len() == 1 && table.contains_key("version") && table["version"].is_str() { + return table.remove("version").unwrap(); + } + if table.get("version").and_then(Value::as_str) == Some(">= 0") { + table.remove("version"); + } + value +} + +pub(crate) fn toml(value: Value) -> Result { + let value = crate::sources::explicit_sources(value); + let mut document = toml_edit::ser::to_document(&value).map_err(serde::ser::Error::custom)?; + compact_tables(document.as_table_mut()); + Ok(format!("{}{document}", crate::GENERATED_HEADER)) +} + +fn compact_tables(table: &mut toml_edit::Table) { + for (name, item) in table.iter_mut() { + if matches!(name.get(), "sources" | "groups") + && let Some(array) = item.as_array() + { + let mut tables = toml_edit::ArrayOfTables::new(); + for value in array.iter() { + if let Some(value) = value.as_inline_table() { + tables.push(value.clone().into_table()); + } + } + *item = toml_edit::Item::ArrayOfTables(tables); + } + if name == "dependencies" { + if let Some(table) = item.as_table_mut() { + for (_, dependency) in table.iter_mut() { + dependency.make_value(); + } + } + } else if let Some(table) = item.as_table_mut() { + compact_tables(table); + } else if let Some(array) = item.as_array_of_tables_mut() { + for table in array.iter_mut() { + expand_inline_tables(table); + compact_tables(table); + } + } + } +} + +fn expand_inline_tables(table: &mut toml_edit::Table) { + for (name, item) in table.iter_mut() { + if name == "dependencies" + && let Some(value) = item.as_inline_table() + { + *item = toml_edit::Item::Table(value.clone().into_table()); + } + } +} diff --git a/crates/rb-gemfile/src/kdl.rs b/crates/rb-gemfile/src/kdl.rs new file mode 100644 index 0000000..4712e8a --- /dev/null +++ b/crates/rb-gemfile/src/kdl.rs @@ -0,0 +1,155 @@ +mod parse; +pub(crate) use parse::parse; + +use kdl::{KdlDocument, KdlNode, KdlValue}; +use std::io; +use toml::{Table, Value}; + +pub(crate) fn render(value: Value) -> io::Result { + let mut root = crate::sources::explicit_sources(value) + .as_table() + .unwrap() + .clone(); + let sources = root.remove("sources"); + let dependencies = root.remove("dependencies"); + let groups = root.remove("groups"); + let mut output = document(&root)?; + append_dependencies(&mut output, dependencies.as_ref())?; + append_groups(&mut output, groups.as_ref())?; + if let Some(Value::Array(sources)) = sources { + for source in sources { + let source = source.as_table().unwrap(); + let mut node = KdlNode::new("source"); + node.push(scalar(&source["url"])?); + if let Some(default) = source.get("default") { + node.push(("default", scalar(default)?)); + } + let mut children = KdlDocument::new(); + append_dependencies(&mut children, source.get("dependencies"))?; + append_groups(&mut children, source.get("groups"))?; + node.set_children(children); + output.nodes_mut().push(node); + } + } + output.autoformat(); + Ok(format!( + "{}{output}", + crate::GENERATED_HEADER.replace("# ", "// ") + )) +} + +fn append_dependencies(document: &mut KdlDocument, dependencies: Option<&Value>) -> io::Result<()> { + if let Some(Value::Table(dependencies)) = dependencies { + for (name, value) in dependencies { + if let Value::Array(declarations) = value { + for value in declarations { + document.nodes_mut().push(dependency(name, value)?); + } + } else { + document.nodes_mut().push(dependency(name, value)?); + } + } + } + Ok(()) +} + +fn append_groups(document: &mut KdlDocument, groups: Option<&Value>) -> io::Result<()> { + if let Some(Value::Array(groups)) = groups { + for group in groups { + let mut node = KdlNode::new("group"); + for name in group["names"].as_array().unwrap() { + node.push(scalar(name)?); + } + let mut children = KdlDocument::new(); + append_dependencies(&mut children, group.get("dependencies"))?; + node.set_children(children); + document.nodes_mut().push(node); + } + } + Ok(()) +} + +fn dependency(name: &str, value: &Value) -> io::Result { + let mut node = KdlNode::new("gem"); + node.push(name); + if let Value::String(version) = value { + node.push(version.clone()); + return Ok(node); + } + let table = value.as_table().unwrap(); + if let Some(version) = table.get("version") { + match version { + Value::Array(versions) => { + for version in versions { + node.push(scalar(version)?); + } + } + _ => node.push(scalar(version)?), + } + } + let mut children = KdlDocument::new(); + for (key, value) in table { + if key == "version" { + continue; + } + if value.is_table() || value.is_array() { + children.nodes_mut().push(generic_node(key, value)?); + } else { + node.push((key.as_str(), scalar(value)?)); + } + } + if !children.nodes().is_empty() { + node.set_children(children); + } + Ok(node) +} + +fn document(table: &Table) -> io::Result { + let mut document = KdlDocument::new(); + for (name, value) in table { + document.nodes_mut().push(generic_node(name, value)?); + } + Ok(document) +} + +fn generic_node(name: &str, value: &Value) -> io::Result { + let mut node = KdlNode::new(name); + match value { + Value::Table(table) => node.set_children(document(table)?), + Value::Array(values) => { + node.set_ty("array"); + if values + .iter() + .any(|value| value.is_table() || value.is_array()) + { + let mut children = KdlDocument::new(); + for value in values { + children.nodes_mut().push(generic_node("item", value)?); + } + node.set_children(children); + } else { + for value in values { + node.push(scalar(value)?); + } + } + } + _ => node.push(scalar(value)?), + } + Ok(node) +} + +fn scalar(value: &Value) -> io::Result { + Ok(match value { + Value::String(value) => value.clone().into(), + Value::Integer(value) => i128::from(*value).into(), + Value::Float(value) => (*value).into(), + Value::Boolean(value) => (*value).into(), + Value::Datetime(value) => value.to_string().into(), + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Expected a scalar value", + )); + } + }) +} diff --git a/crates/rb-gemfile/src/kdl/parse.rs b/crates/rb-gemfile/src/kdl/parse.rs new file mode 100644 index 0000000..40ab74f --- /dev/null +++ b/crates/rb-gemfile/src/kdl/parse.rs @@ -0,0 +1,245 @@ +use kdl::{KdlDocument, KdlNode, KdlValue}; +use std::io; +use toml::{Table, Value}; + +pub(crate) fn parse(input: &str) -> io::Result { + let document: KdlDocument = input.parse().map_err(invalid)?; + let mut root = Table::new(); + let mut dependencies = Table::new(); + parse_nodes(&document, None, &[], &mut root, &mut dependencies)?; + root.insert("dependencies".into(), Value::Table(dependencies)); + Ok(Value::Table(root)) +} + +fn parse_nodes( + document: &KdlDocument, + source: Option<(&str, bool)>, + groups: &[String], + root: &mut Table, + dependencies: &mut Table, +) -> io::Result<()> { + for node in document.nodes() { + match node.name().value() { + "source" => { + let url = node + .get(0) + .and_then(KdlValue::as_string) + .filter(|url| !url.is_empty()) + .ok_or_else(|| invalid("source requires URL"))?; + let default = match node.get("default") { + None => false, + Some(value) => value + .as_bool() + .ok_or_else(|| invalid("source default must be boolean"))?, + }; + if node + .entries() + .iter() + .any(|entry| entry.name().is_some_and(|name| name.value() != "default")) + || node + .entries() + .iter() + .filter(|entry| entry.name().is_none()) + .count() + != 1 + { + return Err(invalid("Unknown source entry")); + } + if default { + let bundle = root + .entry("bundle".to_string()) + .or_insert_with(|| Value::Table(Table::new())) + .as_table_mut() + .ok_or_else(|| invalid("bundle must be a table"))?; + if bundle + .get("source") + .is_some_and(|value| value.as_str() != Some(url)) + { + return Err(invalid("Conflicting default sources")); + } + bundle.insert("source".into(), Value::String(url.into())); + } + if let Some(children) = node.children() { + parse_nodes(children, Some((url, default)), groups, root, dependencies)?; + } + } + "group" => { + let mut inherited = groups.to_vec(); + for entry in node.entries() { + if entry.name().is_some() { + return Err(invalid("group expects names")); + } + let name = entry + .value() + .as_string() + .filter(|name| !name.is_empty()) + .ok_or_else(|| invalid("group names must be nonempty strings"))?; + if !inherited.iter().any(|value| value == name) { + inherited.push(name.into()); + } + } + if node.entries().is_empty() { + return Err(invalid("group requires names")); + } + if let Some(children) = node.children() { + parse_nodes(children, source, &inherited, root, dependencies)?; + } + } + "gem" => { + let name = node + .get(0) + .and_then(KdlValue::as_string) + .ok_or_else(|| invalid("gem requires a name"))?; + let mut table = Table::new(); + let mut versions = Vec::new(); + for entry in node + .entries() + .iter() + .filter(|entry| entry.name().is_none()) + .skip(1) + { + versions.push(kdl_scalar(entry.value())?); + } + if !versions.is_empty() { + table.insert("version".into(), Value::Array(versions)); + } + for entry in node.entries().iter().filter(|entry| entry.name().is_some()) { + let key = entry.name().unwrap().value(); + if table + .insert(key.into(), kdl_scalar(entry.value())?) + .is_some() + { + return Err(invalid("Duplicate gem option")); + } + } + if let Some(children) = node.children() { + for child in children.nodes() { + if table + .insert(child.name().value().into(), generic_value(child)?) + .is_some() + { + return Err(invalid("Duplicate gem option")); + } + } + } + if let Some((url, default)) = source { + if table.contains_key("git") + || table.contains_key("path") + || table + .get("source") + .is_some_and(|value| value.as_str() != Some(url)) + { + return Err(invalid("Dependency conflicts with its source block")); + } + if !default { + table.insert("source".into(), Value::String(url.into())); + } + } + if !groups.is_empty() { + let value = Value::Array(groups.iter().cloned().map(Value::String).collect()); + if table.get("groups").is_some_and(|groups| groups != &value) { + return Err(invalid("Dependency conflicts with its group block")); + } + table.insert("groups".into(), value); + } + if let Some(current) = dependencies.get_mut(name) { + current + .as_table_mut() + .ok_or_else(|| invalid("dependency must be a table"))? + .entry("variants".to_string()) + .or_insert_with(|| Value::Array(Vec::new())) + .as_array_mut() + .ok_or_else(|| invalid("variants must be an array"))? + .push(Value::Table(table)); + } else { + dependencies.insert(name.into(), Value::Table(table)); + } + } + _ => { + if source.is_some() || !groups.is_empty() { + return Err(invalid("Unknown dependency block")); + } + if root + .insert(node.name().value().into(), generic_value(node)?) + .is_some() + { + return Err(invalid("Duplicate metadata node")); + } + } + } + } + Ok(()) +} + +fn generic_value(node: &KdlNode) -> io::Result { + if let Some(children) = node.children() { + if !node.entries().is_empty() { + return Err(invalid("Metadata cannot mix entries and children")); + } + if node.ty().is_some_and(|ty| ty.value() == "array") + && children + .nodes() + .iter() + .all(|node| node.name().value() == "item") + && !children.nodes().is_empty() + { + return children + .nodes() + .iter() + .map(generic_value) + .collect::>>() + .map(Value::Array); + } + let mut table = Table::new(); + for child in children.nodes() { + if table + .insert(child.name().value().into(), generic_value(child)?) + .is_some() + { + return Err(invalid("Duplicate metadata key")); + } + } + return Ok(Value::Table(table)); + } + if node.entries().iter().any(|entry| entry.name().is_some()) { + return Err(invalid("Metadata expects positional values")); + } + let values = node + .entries() + .iter() + .map(|entry| kdl_scalar(entry.value())) + .collect::>>()?; + if values.len() == 1 + && node.ty().is_none() + && !matches!( + node.name().value(), + "groups" + | "platforms" + | "optional_groups" + | "required_ruby_version" + | "required_rubygems_version" + ) + { + Ok(values.into_iter().next().unwrap()) + } else { + Ok(Value::Array(values)) + } +} + +fn kdl_scalar(value: &KdlValue) -> io::Result { + if let Some(value) = value.as_string() { + Ok(Value::String(value.into())) + } else if let Some(value) = value.as_bool() { + Ok(Value::Boolean(value)) + } else if let Some(value) = value.as_integer() { + Ok(Value::Integer(i64::try_from(value).map_err(invalid)?)) + } else if let Some(value) = value.as_float() { + Ok(Value::Float(value)) + } else { + Err(invalid("Unsupported KDL scalar")) + } +} + +fn invalid(error: impl std::fmt::Display) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, error.to_string()) +} diff --git a/crates/rb-gemfile/src/lib.rs b/crates/rb-gemfile/src/lib.rs new file mode 100644 index 0000000..5c2b8b9 --- /dev/null +++ b/crates/rb-gemfile/src/lib.rs @@ -0,0 +1,15 @@ +#![doc = include_str!("../README.md")] + +mod evaluator; +mod format; +mod kdl; +mod manifest; +mod project; +mod snapshot; +mod sources; + +pub use evaluator::{Evaluation, Evaluator}; +pub use format::ExportFormat; +pub use manifest::{Bundle, Dependency, Manifest, Package, Plugin, Require}; +pub use project::GENERATED_HEADER; +pub use snapshot::{CachedEvaluation, SnapshotCache, write_project}; diff --git a/crates/rb-gemfile/src/manifest.rs b/crates/rb-gemfile/src/manifest.rs new file mode 100644 index 0000000..b8ac50a --- /dev/null +++ b/crates/rb-gemfile/src/manifest.rs @@ -0,0 +1,282 @@ +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use toml::Value; + +/// Normalized declarations, not resolved versions or an installation lockfile. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Manifest { + pub bundle: Bundle, + pub dependencies: BTreeMap, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub gemspecs: Vec, +} + +fn remove_null_fields(value: &mut serde_json::Value) { + match value { + serde_json::Value::Object(table) => { + table.retain(|key, value| { + !value.is_null() + || !matches!( + key.as_str(), + "source" + | "engine" + | "engine_version" + | "patchlevel" + | "lockfile" + | "require" + | "git" + | "path" + | "branch" + | "tag" + | "rev" + | "glob" + | "submodules" + | "force_ruby_platform" + ) + }); + for value in table.values_mut() { + remove_null_fields(value); + } + } + serde_json::Value::Array(values) => { + for value in values { + remove_null_fields(value); + } + } + _ => {} + } +} + +impl<'de> Deserialize<'de> for Manifest { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Wire { + #[serde(default)] + bundle: Bundle, + #[serde(deserialize_with = "crate::format::deserialize_dependencies")] + dependencies: BTreeMap, + #[serde(default)] + gemspecs: Vec, + } + let mut value = serde_json::Value::deserialize(deserializer)?; + remove_null_fields(&mut value); + let root = Value::try_from(value) + .map_err(serde::de::Error::custom)? + .as_table() + .cloned() + .ok_or_else(|| serde::de::Error::custom("manifest must be a table"))?; + let root = crate::sources::normalize_document(root).map_err(serde::de::Error::custom)?; + let wire: Wire = Value::Table(root) + .try_into() + .map_err(serde::de::Error::custom)?; + Ok(Self { + bundle: wire.bundle, + dependencies: wire.dependencies, + gemspecs: wire.gemspecs, + }) + } +} + +impl Manifest { + /// Reads dependency declarations and package metadata from KDL. + pub fn from_kdl(input: &str) -> std::io::Result { + crate::kdl::parse(input)? + .try_into() + .map_err(std::io::Error::other) + } + + pub fn to_kdl(&self) -> std::io::Result { + let value = crate::project::render_normalized(self).map_err(std::io::Error::other)?; + crate::kdl::render(value) + } + + pub fn to_toml(&self) -> Result { + crate::project::render(self) + } +} + +/// Local package metadata needed without evaluating its gemspec again. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Package { + pub name: String, + pub version: String, + pub platform: String, + pub path: String, + pub required_ruby_version: Vec, + pub required_rubygems_version: Vec, + pub runtime_dependencies: BTreeMap>, + pub development_dependencies: BTreeMap>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default, deny_unknown_fields)] +pub struct Bundle { + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + #[serde(with = "requirements")] + pub ruby: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub engine: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub engine_version: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub patchlevel: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub lockfile: Option, + pub optional_groups: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub plugins: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Dependency { + #[serde(with = "requirements")] + pub version: Vec, + pub groups: Vec, + pub platforms: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub require: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub git: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tag: Option, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "ref")] + pub rev: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub glob: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub submodules: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub force_ruby_platform: Option, + pub enabled: bool, + /// Additional declarations of this gem with distinct activation settings. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub variants: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum Require { + Enabled(bool), + Name(String), + Names(Vec), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Plugin { + pub name: String, + #[serde(with = "requirements")] + pub version: Vec, +} + +impl Default for Dependency { + fn default() -> Self { + Self { + version: vec![">= 0".into()], + groups: vec!["default".into()], + platforms: Vec::new(), + require: None, + source: None, + git: None, + path: None, + branch: None, + tag: None, + rev: None, + glob: None, + submodules: None, + force_ruby_platform: None, + enabled: true, + variants: Vec::new(), + } + } +} + +mod requirements { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + pub fn serialize(value: &[String], serializer: S) -> Result { + if let [requirement] = value { + requirement.serialize(serializer) + } else { + value.serialize(serializer) + } + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Requirements { + One(String), + Many(Vec), + } + Ok(match Requirements::deserialize(deserializer)? { + Requirements::One(value) => vec![value], + Requirements::Many(values) => values, + }) + } +} + +impl Dependency { + pub fn validate(&self) -> Result<(), String> { + if self.version.is_empty() || self.version.iter().any(|value| value.trim().is_empty()) { + return Err("Version requirements must not be empty".into()); + } + if self + .groups + .iter() + .chain(&self.platforms) + .any(|value| value.is_empty()) + { + return Err("Groups and platforms must not contain empty names".into()); + } + if [&self.git, &self.path, &self.source] + .iter() + .filter(|value| value.is_some()) + .count() + > 1 + { + return Err("Git, path and registry sources are mutually exclusive".into()); + } + let selectors = [&self.branch, &self.tag, &self.rev]; + if selectors.iter().filter(|value| value.is_some()).count() > 1 { + return Err("Specify only one of branch, tag or rev".into()); + } + if self.git.is_none() + && (selectors.iter().any(|value| value.is_some()) || self.submodules.is_some()) + { + return Err("Git options require a Git source".into()); + } + for value in [ + &self.git, + &self.path, + &self.source, + &self.branch, + &self.tag, + &self.rev, + ] + .into_iter() + .flatten() + { + if value.is_empty() || value.chars().any(char::is_control) { + return Err("Source locations and selectors must not be empty or contain control characters".into()); + } + } + for variant in &self.variants { + variant.validate()?; + } + Ok(()) + } +} diff --git a/crates/rb-gemfile/src/project.rs b/crates/rb-gemfile/src/project.rs new file mode 100644 index 0000000..f5edaa0 --- /dev/null +++ b/crates/rb-gemfile/src/project.rs @@ -0,0 +1,172 @@ +use crate::{Bundle, Dependency, Manifest}; +use std::io; +use toml::{Table, Value}; + +pub const GENERATED_HEADER: &str = "# Generated by Ruby Butler. Do not edit.\n# Edit the source Gemfile and project settings instead.\n# Regenerate with rb export-gemfile when source files change.\n"; + +pub(crate) fn render_normalized(value: &impl serde::Serialize) -> Result { + let mut value = Value::try_from(value)?; + if let Some(bundle) = value.get_mut("bundle").and_then(Value::as_table_mut) { + for key in ["ruby", "optional_groups"] { + if bundle + .get(key) + .and_then(Value::as_array) + .is_some_and(Vec::is_empty) + { + bundle.remove(key); + } + } + } + if let Some(dependencies) = value.get_mut("dependencies").and_then(Value::as_table_mut) { + dependencies.retain(|_, dependency| { + let declarations = active_declarations(dependency.clone()); + let mut declarations = declarations.into_iter(); + let Some(mut primary) = declarations.next() else { + return false; + }; + let variants: Vec<_> = declarations.collect(); + if !variants.is_empty() { + primary + .as_table_mut() + .unwrap() + .insert("variants".into(), Value::Array(variants)); + } + *dependency = primary; + true + }); + } + Ok(value) +} + +pub(crate) fn render(value: &impl serde::Serialize) -> Result { + crate::format::toml(render_normalized(value)?) +} + +fn active_declarations(mut value: Value) -> Vec { + let table = value.as_table_mut().unwrap(); + let variants = table + .remove("variants") + .and_then(|value| value.as_array().cloned()) + .unwrap_or_default(); + let enabled = table + .remove("enabled") + .and_then(|value| value.as_bool()) + .unwrap_or(true); + if table + .get("platforms") + .and_then(Value::as_array) + .is_some_and(Vec::is_empty) + { + table.remove("platforms"); + } + let mut declarations = Vec::new(); + if enabled { + declarations.push(value); + } + for variant in variants { + declarations.extend(active_declarations(variant)); + } + declarations +} + +impl Manifest { + /// Merges declarations with root project settings, rejecting explicit conflicts. + pub fn merge_project(&self, project: &str) -> io::Result { + self.merge_project_format(project, crate::ExportFormat::Toml) + } + + pub fn merge_project_format( + &self, + project: &str, + format: crate::ExportFormat, + ) -> io::Result { + let project = self.merged_project(project)?; + match format { + crate::ExportFormat::Toml => render(&project).map_err(invalid), + crate::ExportFormat::Kdl => { + crate::kdl::render(render_normalized(&project).map_err(invalid)?) + } + } + } + + fn merged_project(&self, project: &str) -> io::Result { + let project: Table = toml::from_str(project).map_err(invalid)?; + let mut project = crate::sources::normalize_document(project).map_err(invalid)?; + let mut dependencies = match project.remove("dependencies") { + None => Table::new(), + Some(Value::Table(value)) => value, + Some(_) => return Err(invalid("dependencies must be a table")), + }; + dependencies = crate::format::expand_dependencies(dependencies).map_err(invalid)?; + for (name, value) in &mut dependencies { + let parsed: Dependency = value.clone().try_into().map_err(invalid)?; + parsed.validate().map_err(invalid)?; + if let Some(gemfile) = self.dependencies.get(name) { + let expected = Value::try_from(gemfile).map_err(invalid)?; + let normalized = Value::try_from(&parsed).map_err(invalid)?; + for key in value + .as_table() + .ok_or_else(|| invalid("dependency must be a string or table"))? + .keys() + { + let key = if key == "ref" { "rev" } else { key }; + if normalized.get(key) != expected.get(key) { + return Err(invalid(format!( + "Conflicting dependency {name}.{key} in Gemfile and rbproject.toml" + ))); + } + } + } + *value = Value::try_from(parsed).map_err(invalid)?; + } + for (name, dependency) in &self.dependencies { + dependencies.insert(name.clone(), Value::try_from(dependency).map_err(invalid)?); + } + project.insert("dependencies".into(), Value::Table(dependencies)); + if !self.gemspecs.is_empty() { + let generated = Value::try_from(&self.gemspecs).map_err(invalid)?; + if project + .get("gemspecs") + .is_some_and(|value| value != &generated) + { + return Err(invalid( + "Conflicting gemspecs in Gemfile and rbproject.toml", + )); + } + project.insert("gemspecs".into(), generated); + } + + let mut bundle = match project.remove("bundle") { + None => Table::new(), + Some(Value::Table(value)) => value, + Some(_) => return Err(invalid("bundle must be a table")), + }; + let generated = Value::try_from(&self.bundle).map_err(invalid)?; + let generated_table = generated.as_table().unwrap(); + let known: Table = bundle + .iter() + .filter(|(key, _)| generated_table.contains_key(*key)) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + let normalized = + Value::try_from(Value::Table(known).try_into::().map_err(invalid)?) + .map_err(invalid)?; + for (key, value) in generated.as_table().unwrap() { + if value.as_array().is_some_and(Vec::is_empty) { + continue; + } + if bundle.contains_key(key) && normalized.get(key) != Some(value) { + return Err(invalid(format!( + "Conflicting bundle.{key} in Gemfile and rbproject.toml" + ))); + } + bundle.insert(key.clone(), value.clone()); + } + project.insert("bundle".into(), Value::Table(bundle)); + Ok(project) + } +} + +fn invalid(error: impl std::fmt::Display) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, error.to_string()) +} diff --git a/crates/rb-gemfile/src/snapshot.rs b/crates/rb-gemfile/src/snapshot.rs new file mode 100644 index 0000000..ac773fc --- /dev/null +++ b/crates/rb-gemfile/src/snapshot.rs @@ -0,0 +1,280 @@ +use crate::{ + Evaluation, Evaluator, + evaluator::{SOURCES, gemfile_path}, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeSet, + fs, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +/// Opt-in cache for deterministic Gemfiles, including their project directory. +/// Add inputs outside that directory with `input`. Time, network and subprocess +/// results are not cache inputs; use `Evaluator::evaluate` for such Gemfiles. +pub struct SnapshotCache { + path: PathBuf, + inputs: Vec, + outputs: Vec, +} + +#[derive(Debug)] +pub struct CachedEvaluation { + pub evaluation: Evaluation, + pub reused: bool, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Snapshot { + fingerprint: String, + evaluation: Evaluation, + checksum: String, +} + +impl SnapshotCache { + pub fn new(path: impl Into) -> Self { + Self { + path: path.into(), + inputs: Vec::new(), + outputs: Vec::new(), + } + } + + /// Declares an additional file or directory that evaluation may inspect. + pub fn input(mut self, path: impl Into) -> Self { + self.inputs.push(path.into()); + self + } + + /// Excludes a generated file that the Gemfile must not read. + pub fn output(mut self, path: impl Into) -> Self { + self.outputs.push(path.into()); + self + } + + pub fn evaluate( + &self, + evaluator: &Evaluator, + gemfile: impl AsRef, + ) -> io::Result { + let gemfile = gemfile_path(gemfile.as_ref())?; + let directory = gemfile.parent().unwrap(); + let path = absolute(&self.path)?; + let filename = path.file_name().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "Snapshot must be a file path") + })?; + fs::create_dir_all(path.parent().unwrap())?; + let path = dunce::canonicalize(path.parent().unwrap())?.join(filename); + let inputs = self + .inputs + .iter() + .map(|path| absolute(path)) + .collect::>>()?; + let ruby = evaluator.ruby_executable()?; + if path == gemfile || path == ruby || inputs.iter().any(|input| input == &path) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Snapshot must not overwrite an input file", + )); + } + let mut excluded = vec![path.clone()]; + for output in &self.outputs { + let output = absolute(output)?; + if output.is_dir() || output == gemfile || output == ruby || inputs.contains(&output) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Generated output must be a file separate from explicit inputs", + )); + } + excluded.push(output); + } + let mut lock_path = path.as_os_str().to_owned(); + lock_path.push(".lock"); + let lock_path = PathBuf::from(lock_path); + if lock_path == gemfile || lock_path == ruby || inputs.contains(&lock_path) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Snapshot lock must not be an input file", + )); + } + let lock = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&lock_path)?; + lock.lock()?; + excluded.push(lock_path); + let before = fingerprint(evaluator, &gemfile, directory, &inputs, &ruby, &excluded)?; + match fs::read(&path) { + Ok(bytes) => { + if let Ok(snapshot) = serde_json::from_slice::(&bytes) + && snapshot.fingerprint == before + && snapshot.checksum == evaluation_checksum(&snapshot.evaluation)? + { + return Ok(CachedEvaluation { + evaluation: snapshot.evaluation, + reused: true, + }); + } + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let evaluation = evaluator.evaluate(&gemfile)?; + let covered = evaluation.inputs.iter().all(|path| { + !excluded.contains(path) + && (path.starts_with(directory) + || inputs + .iter() + .any(|input| path == input || (input.is_dir() && path.starts_with(input)))) + }); + if covered + && before == fingerprint(evaluator, &gemfile, directory, &inputs, &ruby, &excluded)? + { + let snapshot = Snapshot { + fingerprint: before, + checksum: evaluation_checksum(&evaluation)?, + evaluation: evaluation.clone(), + }; + let bytes = serde_json::to_vec(&snapshot).map_err(io::Error::other)?; + atomic_write(&path, &bytes)?; + } + Ok(CachedEvaluation { + evaluation, + reused: false, + }) + } +} + +/// Replaces a generated project file without exposing partial contents. +pub fn write_project(path: impl AsRef, contents: &str) -> io::Result<()> { + atomic_write(path.as_ref(), contents.as_bytes()) +} + +fn evaluation_checksum(evaluation: &Evaluation) -> io::Result { + let bytes = serde_json::to_vec(evaluation).map_err(io::Error::other)?; + Ok(format!("{:x}", Sha256::digest(bytes))) +} + +fn absolute(path: &Path) -> io::Result { + if path.exists() { + return dunce::canonicalize(path); + } + if path.is_absolute() { + Ok(path.to_owned()) + } else { + Ok(std::env::current_dir()?.join(path)) + } +} + +fn fingerprint( + evaluator: &Evaluator, + gemfile: &Path, + directory: &Path, + inputs: &[PathBuf], + ruby: &Path, + excluded: &[PathBuf], +) -> io::Result { + let mut hash = Sha256::new(); + field(&mut hash, b"rb-gemfile snapshot 1"); + field(&mut hash, format!("{gemfile:?}").as_bytes()); + field(&mut hash, std::env::consts::OS.as_bytes()); + field(&mut hash, std::env::consts::ARCH.as_bytes()); + for source in [ + include_str!("evaluator.rs"), + include_str!("format.rs"), + include_str!("manifest.rs"), + include_str!("sources.rs"), + include_str!("snapshot.rs"), + ] { + field(&mut hash, source.as_bytes()); + } + for (name, source) in SOURCES { + field(&mut hash, name.as_bytes()); + field(&mut hash, source.as_bytes()); + } + let mut environment: std::collections::BTreeMap<_, _> = std::env::vars_os().collect(); + environment.extend(evaluator.environment.clone()); + environment.remove(std::ffi::OsStr::new("RUBYOPT")); + for pair in environment { + field(&mut hash, format!("{pair:?}").as_bytes()); + } + let mut visited = BTreeSet::new(); + hash_path(&mut hash, ruby, excluded, &mut visited)?; + hash_path(&mut hash, directory, excluded, &mut visited)?; + for input in inputs { + hash_path(&mut hash, input, excluded, &mut visited)?; + } + Ok(format!("{:x}", hash.finalize())) +} + +fn field(hash: &mut Sha256, bytes: &[u8]) { + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); +} + +fn hash_path( + hash: &mut Sha256, + path: &Path, + excluded: &[PathBuf], + visited: &mut BTreeSet, +) -> io::Result<()> { + if excluded.iter().any(|excluded| path == excluded) { + return Ok(()); + } + field(hash, format!("{path:?}").as_bytes()); + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + field(hash, b"missing"); + return Ok(()); + } + Err(error) => return Err(error), + }; + if metadata.is_symlink() { + field(hash, b"symlink"); + field(hash, format!("{:?}", fs::read_link(path)?).as_bytes()); + let target = dunce::canonicalize(path)?; + if !visited.contains(&target) { + hash_path(hash, &target, excluded, visited)?; + } + } else if metadata.is_dir() { + field(hash, b"directory"); + if !visited.insert(dunce::canonicalize(path)?) { + return Ok(()); + } + let mut entries: Vec<_> = fs::read_dir(path)? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>()?; + entries.sort(); + for entry in entries { + hash_path(hash, &entry, excluded, visited)?; + } + } else if metadata.is_file() { + field(hash, b"file"); + field(hash, &fs::read(path)?); + } else { + return Err(io::Error::other(format!( + "Unsupported cache input: {}", + path.display() + ))); + } + Ok(()) +} + +fn atomic_write(path: &Path, contents: &[u8]) -> io::Result<()> { + let parent = path + .parent() + .filter(|path| !path.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent)?; + let mut file = tempfile::NamedTempFile::new_in(parent)?; + file.write_all(contents)?; + file.as_file().sync_all()?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} diff --git a/crates/rb-gemfile/src/sources.rs b/crates/rb-gemfile/src/sources.rs new file mode 100644 index 0000000..bfcd8bf --- /dev/null +++ b/crates/rb-gemfile/src/sources.rs @@ -0,0 +1,265 @@ +use crate::format::{compact, expand_dependencies, inherit_source}; +use std::collections::BTreeMap; +use toml::{Table, Value}; + +pub(crate) fn explicit_sources(mut value: Value) -> Value { + let root = value.as_table_mut().unwrap(); + let default = root + .get_mut("bundle") + .and_then(Value::as_table_mut) + .and_then(|bundle| bundle.remove("source")); + let mut sources = BTreeMap::::new(); + if let Some(Value::String(url)) = &default { + sources.insert( + url.clone(), + Table::from_iter([ + ("url".into(), Value::String(url.clone())), + ("default".into(), Value::Boolean(true)), + ]), + ); + } + let dependencies = root + .remove("dependencies") + .unwrap() + .as_table() + .unwrap() + .clone(); + let mut local = Table::new(); + for (name, value) in dependencies { + let mut declarations = vec![value]; + while let Some(mut declaration) = declarations.pop() { + let table = declaration.as_table_mut().unwrap(); + if let Some(Value::Array(variants)) = table.remove("variants") { + declarations.extend(variants.into_iter().rev()); + } + let source = table.get("source").cloned().or_else(|| { + if table.contains_key("git") || table.contains_key("path") { + None + } else { + default.clone() + } + }); + if source != default { + table.remove("source"); + } + let target = if let Some(Value::String(url)) = source { + sources + .entry(url.clone()) + .or_insert_with(|| Table::from_iter([("url".into(), Value::String(url))])) + } else { + &mut local + }; + let groups = table + .remove("groups") + .unwrap_or_else(|| Value::Array(vec![Value::String("default".into())])); + if groups + .as_array() + .is_some_and(|groups| groups == &[Value::String("default".into())]) + { + insert_declaration(target, &name, declaration); + } else { + let entries = target + .entry("groups".to_string()) + .or_insert_with(|| Value::Array(Vec::new())) + .as_array_mut() + .unwrap(); + if let Some(existing) = entries + .iter_mut() + .find(|entry| entry.get("names") == Some(&groups)) + { + insert_declaration(existing.as_table_mut().unwrap(), &name, declaration); + } else { + let mut group = Table::from_iter([("names".into(), groups)]); + insert_declaration(&mut group, &name, declaration); + entries.push(Value::Table(group)); + } + } + } + } + root.extend(local); + if !sources.is_empty() { + root.insert( + "sources".into(), + Value::Array(sources.into_values().map(Value::Table).collect()), + ); + } + value +} + +fn insert_declaration(target: &mut Table, name: &str, declaration: Value) { + let dependencies = target + .entry("dependencies".to_string()) + .or_insert_with(|| Value::Table(Table::new())) + .as_table_mut() + .unwrap(); + let declaration = compact(declaration); + match dependencies.get_mut(name) { + None => { + dependencies.insert(name.into(), declaration); + } + Some(Value::Array(values)) => values.push(declaration), + Some(value) => *value = Value::Array(vec![value.clone(), declaration]), + } +} + +pub(crate) fn normalize_document(mut root: Table) -> Result { + let mut dependencies = match root.remove("dependencies") { + None => Table::new(), + Some(Value::Table(value)) => expand_dependencies(value)?, + Some(_) => return Err("dependencies must be a table".into()), + }; + collect_groups(&mut root, None, &mut dependencies)?; + if let Some(sources) = root.remove("sources") { + for source in sources + .as_array() + .ok_or("sources must be an array of tables")? + { + let mut source = source.as_table().ok_or("source must be a table")?.clone(); + let url = source + .remove("url") + .and_then(|url| url.as_str().map(str::to_owned)) + .filter(|url| !url.is_empty()) + .ok_or("source requires a URL")?; + let default = source + .remove("default") + .map(|value| value.as_bool().ok_or("source default must be a boolean")) + .transpose()? + .unwrap_or(false); + if default { + let bundle = root + .entry("bundle".to_string()) + .or_insert_with(|| Value::Table(Table::new())) + .as_table_mut() + .ok_or("bundle must be a table")?; + if bundle + .get("source") + .is_some_and(|value| value.as_str() != Some(&url)) + { + return Err("Conflicting default sources".into()); + } + bundle.insert("source".into(), Value::String(url.clone())); + } + validate_source(&source, &url)?; + let inherited = if default { None } else { Some(url.as_str()) }; + collect_dependencies(&mut source, inherited, None, &mut dependencies)?; + collect_groups(&mut source, inherited, &mut dependencies)?; + if !source.is_empty() { + return Err("Unknown source field".into()); + } + } + } + root.insert("dependencies".into(), Value::Table(dependencies)); + Ok(root) +} + +fn collect_groups( + root: &mut Table, + source: Option<&str>, + dependencies: &mut Table, +) -> Result<(), String> { + if let Some(groups) = root.remove("groups") { + for group in groups + .as_array() + .ok_or("groups must be an array of tables")? + { + let mut group = group.as_table().ok_or("group must be a table")?.clone(); + let names = group.remove("names").ok_or("group requires names")?; + if !names.as_array().is_some_and(|names| { + !names.is_empty() + && names + .iter() + .all(|name| name.as_str().is_some_and(|name| !name.is_empty())) + }) { + return Err("group names must be nonempty strings".into()); + } + collect_dependencies(&mut group, source, Some(&names), dependencies)?; + if !group.is_empty() { + return Err("Unknown group field".into()); + } + } + } + Ok(()) +} + +fn collect_dependencies( + root: &mut Table, + source: Option<&str>, + groups: Option<&Value>, + dependencies: &mut Table, +) -> Result<(), String> { + if let Some(value) = root.remove("dependencies") { + for (name, value) in value.as_table().ok_or("dependencies must be a table")? { + let declarations = match value { + Value::Array(values) => values.clone(), + _ => vec![value.clone()], + }; + if declarations.is_empty() { + return Err("Empty dependency declaration list".into()); + } + for mut value in declarations { + if let Value::String(version) = value { + value = Value::Table(Table::from_iter([( + "version".into(), + Value::String(version), + )])); + } + if let Some(source) = source { + inherit_source(&mut value, source)?; + } + if let Some(groups) = groups { + let table = value + .as_table_mut() + .ok_or("dependency must be a string or table")?; + if table.get("groups").is_some_and(|value| value != groups) { + return Err("Dependency conflicts with its group block".into()); + } + table.insert("groups".into(), groups.clone()); + } + if let Some(current) = dependencies.get_mut(name) { + current + .as_table_mut() + .ok_or("dependency must be a table")? + .entry("variants".to_string()) + .or_insert_with(|| Value::Array(Vec::new())) + .as_array_mut() + .ok_or("variants must be an array")? + .push(value); + } else { + dependencies.insert(name.clone(), value); + } + } + } + } + Ok(()) +} + +fn validate_source(table: &Table, url: &str) -> Result<(), String> { + if let Some(value) = table.get("dependencies") { + for (_, dependency) in value.as_table().ok_or("dependencies must be a table")? { + let values = match dependency { + Value::Array(values) => values.clone(), + value => vec![value.clone()], + }; + for value in values { + let mut value = if let Value::String(version) = value { + Value::Table(Table::from_iter([( + "version".into(), + Value::String(version), + )])) + } else { + value + }; + inherit_source(&mut value, url)?; + } + } + } + if let Some(groups) = table.get("groups") { + for group in groups + .as_array() + .ok_or("groups must be an array of tables")? + { + validate_source(group.as_table().ok_or("group must be a table")?, url)?; + } + } + Ok(()) +} diff --git a/crates/rb-gemfile/tests/corpus.rs b/crates/rb-gemfile/tests/corpus.rs new file mode 100644 index 0000000..498f6f1 --- /dev/null +++ b/crates/rb-gemfile/tests/corpus.rs @@ -0,0 +1,259 @@ +use rb_gemfile::{Evaluator, Manifest, Require, SnapshotCache}; +use std::path::Path; + +fn evaluate(project: &str, count: usize) -> Manifest { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/real-world") + .join(project); + let ruby = std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into()); + let result = Evaluator::new(ruby) + .evaluate(root.join("Gemfile")) + .unwrap_or_else(|error| panic!("{project}: {error}")); + assert_eq!(result.manifest.dependencies.len(), count, "{project}"); + assert_eq!( + result.manifest.bundle.source.as_deref(), + Some("https://rubygems.org"), + "{project}" + ); + assert!( + result.manifest.dependencies.contains_key("rails"), + "{project}" + ); + let expected: serde_json::Value = serde_json::from_slice( + &std::fs::read( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/corpus") + .join(format!("{project}.json")), + ) + .unwrap(), + ) + .unwrap(); + let actual = serde_json::to_value(&result.manifest).unwrap(); + for (name, fields) in expected["dependencies"].as_object().unwrap() { + for (field, value) in fields.as_object().unwrap() { + assert_eq!( + &actual["dependencies"][name][field], value, + "{project}: {name}.{field}" + ); + } + } + for name in expected["absent"].as_array().unwrap() { + assert!( + !result + .manifest + .dependencies + .contains_key(name.as_str().unwrap()), + "{project}: {name}" + ); + } + if let Some(groups) = expected.get("optional_groups") { + assert_eq!(&actual["bundle"]["optional_groups"], groups, "{project}"); + } + let toml = result.manifest.to_toml().unwrap(); + let kdl = result.manifest.to_kdl().unwrap(); + let parsed_kdl = + rb_gemfile::Manifest::from_kdl(&kdl).unwrap_or_else(|error| panic!("{project}: {error}")); + let parsed_toml: rb_gemfile::Manifest = toml::from_str(&toml).unwrap(); + assert_eq!(parsed_kdl, parsed_toml, "{project}"); + + assert_eq!( + parsed_kdl.dependencies.len(), + count, + "{project}: KDL dependency count" + ); + let exported = toml::from_str::(&toml).unwrap(); + assert!( + exported + .dependencies + .values() + .all(|dependency| dependency.enabled + && dependency.variants.iter().all(|variant| variant.enabled)), + "{project}" + ); + assert_eq!(exported.to_toml().unwrap(), toml, "{project}"); + assert_eq!( + exported.dependencies.len(), + count, + "{project}: exported count" + ); + for name in expected["absent"].as_array().unwrap() { + assert!( + !exported.dependencies.contains_key(name.as_str().unwrap()), + "{project}: exported {name}" + ); + } + for (name, dependency) in &result.manifest.dependencies { + assert!(dependency.enabled, "{project}: {name}"); + assert!( + dependency.variants.iter().all(|variant| variant.enabled), + "{project}: {name}" + ); + assert_eq!( + &exported.dependencies[name], dependency, + "{project}: round-trip {name}" + ); + } + let merged: toml::Value = toml::from_str( + &result + .manifest + .merge_project("[project]\nname = 'corpus'\n") + .unwrap(), + ) + .unwrap(); + let plain: toml::Value = toml::from_str(&toml).unwrap(); + assert_eq!(merged.get("dependencies"), plain.get("dependencies")); + assert_eq!(merged.get("sources"), plain.get("sources")); + assert_eq!(merged["project"]["name"].as_str(), Some("corpus")); + let directory = tempfile::tempdir().unwrap(); + let cache = SnapshotCache::new(directory.path().join("snapshot.json")); + let evaluator = + Evaluator::new(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())); + let initial = cache.evaluate(&evaluator, root.join("Gemfile")).unwrap(); + assert!(!initial.reused); + assert_eq!(initial.evaluation.manifest, result.manifest); + let reused = cache.evaluate(&evaluator, root.join("Gemfile")).unwrap(); + assert!(reused.reused); + assert_eq!(reused.evaluation.manifest, result.manifest); + result.manifest +} + +#[test] +fn chatwoot() { + let manifest = evaluate("chatwoot", 152); + assert_eq!(manifest.dependencies["rack-cors"].version, ["2.0.0"]); + assert_eq!( + manifest.dependencies["rack-cors"].require, + Some(Require::Name("rack/cors".into())) + ); +} + +#[test] +fn diaspora() { + let manifest = evaluate("diaspora", 113); + assert_eq!(manifest.dependencies["puma"].version, ["7.2.0"]); + assert_eq!( + manifest.dependencies["puma"].require, + Some(Require::Enabled(false)) + ); +} + +#[test] +fn errbit() { + let manifest = evaluate("errbit", 83); + assert_eq!(manifest.dependencies["rails"].version, ["8.1.3.1"]); + assert_eq!( + manifest.dependencies["simplecov"].require, + Some(Require::Enabled(false)) + ); +} + +#[test] +fn forem() { + let manifest = evaluate("forem", 167); + assert_eq!(manifest.dependencies["stackprof"].platforms, ["ruby"]); + assert_eq!( + manifest.dependencies["stripe-ruby-mock"].require, + Some(Require::Name("stripe_mock".into())) + ); +} + +#[test] +fn foreman() { + let manifest = evaluate("foreman", 105); + assert_eq!(manifest.dependencies["rdoc"].version, [">= 0"]); + assert_eq!(manifest.dependencies["puma"].groups, ["test", "service"]); + assert_eq!( + manifest.dependencies["fog-vsphere"].version, + [">= 3.7.1", "< 4.0"] + ); + assert!(manifest.dependencies.contains_key("theforeman-rubocop")); +} + +#[test] +fn lobsters() { + let manifest = evaluate("lobsters", 58); + assert_eq!( + manifest.dependencies["sqlite3"].force_ruby_platform, + Some(true) + ); + assert_eq!( + manifest.dependencies["svg-graph"].require, + Some(Require::Name("SVG/Graph/TimeSeries".into())) + ); +} + +#[test] +fn manageiq() { + let manifest = evaluate("manageiq", 145); + assert_eq!(manifest.bundle.plugins[0].name, "bundler-inject"); + assert_eq!(manifest.bundle.plugins[0].version, ["~> 2.0"]); + assert!( + manifest + .bundle + .optional_groups + .contains(&"appliance".into()) + ); + assert_eq!( + manifest.dependencies["pg"].source.as_deref(), + Some("https://rubygems.manageiq.org") + ); + assert_eq!( + manifest.dependencies["manageiq-schema"].git.as_deref(), + Some("https://github.com/ManageIQ/manageiq-schema") + ); +} + +#[test] +fn mastodon() { + let manifest = evaluate("mastodon", 154); + assert_eq!(manifest.bundle.ruby, [">= 3.3.0", "< 4.1.0"]); + assert_eq!( + manifest.dependencies["idn-ruby"].require, + Some(Require::Name("idn".into())) + ); +} + +#[test] +fn postal() { + let manifest = evaluate("postal", 50); + assert_eq!( + manifest.dependencies["highline"].require, + Some(Require::Enabled(false)) + ); +} + +#[test] +fn zammad() { + let manifest = evaluate("zammad", 131); + assert_eq!(manifest.dependencies["debug"].platforms, ["mri"]); + assert_eq!( + manifest.dependencies["autodiscover"].git.as_deref(), + Some("https://github.com/zammad-deps/autodiscover") + ); +} + +#[test] +fn corpus_gemfiles_match_their_recorded_upstream_hashes() { + use sha2::{Digest, Sha256}; + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/real-world"); + let mut projects = 0; + for entry in std::fs::read_dir(root).unwrap() { + let directory = entry.unwrap().path(); + if !directory.is_dir() { + continue; + } + projects += 1; + let provenance: serde_json::Value = + serde_json::from_slice(&std::fs::read(directory.join("source.json")).unwrap()).unwrap(); + assert_eq!(provenance["sha"].as_str().unwrap().len(), 40); + assert!(provenance["files_sha256"].get("Gemfile").is_some()); + for (name, expected) in provenance["files_sha256"].as_object().unwrap() { + let path = directory.join(name); + if path.is_file() { + let actual = format!("{:x}", Sha256::digest(std::fs::read(&path).unwrap())); + assert_eq!(actual, expected.as_str().unwrap(), "{}", path.display()); + } + } + } + assert_eq!(projects, 10); +} diff --git a/crates/rb-gemfile/tests/evaluation.rs b/crates/rb-gemfile/tests/evaluation.rs new file mode 100644 index 0000000..c5f04ad --- /dev/null +++ b/crates/rb-gemfile/tests/evaluation.rs @@ -0,0 +1,705 @@ +use rb_gemfile::{Evaluator, Manifest, Require}; +use std::path::Path; + +fn evaluator() -> Evaluator { + Evaluator::new(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())) +} + +fn write(root: &Path, name: &str, content: &str) { + let path = root.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, content).unwrap(); +} + +#[test] +fn evaluates_requirements_groups_and_require_settings_without_bundler() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!( + "fixtures/evaluation/evaluates_requirements_groups_and_require_settings_without_bundler-1.rb" + ), + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + let manifest = result.manifest; + assert_eq!( + manifest.bundle.source.as_deref(), + Some("https://rubygems.org") + ); + assert_eq!(manifest.bundle.ruby, [">= 3.2", "< 5"]); + assert_eq!(manifest.bundle.engine.as_deref(), Some("jruby")); + assert_eq!(manifest.bundle.optional_groups, ["development", "test"]); + assert_eq!( + manifest.dependencies["rails"].version, + ["~> 8.0", ">= 8.0.2"] + ); + assert_eq!(manifest.dependencies["rails"].groups, ["default"]); + assert_eq!( + manifest.dependencies["debug"].require, + Some(Require::Enabled(false)) + ); + assert_eq!( + manifest.dependencies["rake"].groups, + ["development", "test", "tools"] + ); + assert_eq!( + manifest.dependencies["rake"].require, + Some(Require::Names(vec!["rake".into(), "rake/task".into()])) + ); + assert_eq!( + manifest.dependencies["rack"].require, + Some(Require::Name("rack/builder".into())) + ); + let toml = manifest.to_toml().unwrap(); + assert_eq!(toml::from_str::(&toml).unwrap(), manifest); +} + +#[test] +fn preserves_platforms_and_evaluated_install_conditions() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!( + "fixtures/evaluation/preserves_platforms_and_evaluated_install_conditions-1.rb" + ), + ); + let manifest = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest; + assert_eq!(manifest.dependencies["jdbc"].platforms, ["jruby"]); + assert_eq!( + manifest.dependencies["jdbc"].force_ruby_platform, + Some(true) + ); + assert!(!manifest.dependencies["disabled"].enabled); + assert!(!manifest.dependencies["also_disabled"].enabled); + assert!(manifest.dependencies["enabled"].enabled); + assert_eq!( + manifest.dependencies["enabled"].platforms, + ["ruby", "windows"] + ); +} + +#[test] +fn scopes_sources_and_resolves_included_paths() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!("fixtures/evaluation/scopes_sources_and_resolves_included_paths-1.rb"), + ); + write( + root.path(), + "nested/Gemfile", + "path '../local' do\n gem 'local'\nend\n", + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + let deps = result.manifest.dependencies; + assert_eq!( + deps["private-gem"].source.as_deref(), + Some("https://gems.example.test") + ); + assert_eq!( + deps["git-gem"].git.as_deref(), + Some("https://example.test/repo.git") + ); + assert_eq!(deps["git-gem"].rev.as_deref(), Some("abc123")); + assert_eq!(deps["git-gem"].submodules, Some(true)); + assert_eq!( + deps["custom"].git.as_deref(), + Some("https://example.test/custom.git") + ); + assert_eq!(deps["custom"].tag.as_deref(), Some("v1")); + assert_eq!( + Path::new(deps["local"].path.as_ref().unwrap()), + dunce::canonicalize(root.path()).unwrap().join("local") + ); + assert!(deps["normal"].source.is_none()); + assert!(deps["normal"].git.is_none()); + assert_eq!(result.inputs.len(), 2); +} + +#[test] +fn loads_project_gemspec_and_ruby_version_file() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "ruby file: '.ruby-version'\ngemspec development_group: :tools\n", + ); + write(root.path(), ".ruby-version", "ruby-4.0.6\n"); + write( + root.path(), + "sample.gemspec", + include_str!("fixtures/evaluation/loads_project_gemspec_and_ruby_version_file-1.rb"), + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + assert_eq!(result.manifest.bundle.ruby, ["4.0.6"]); + assert_eq!(result.manifest.dependencies["sample"].version, ["= 1.2.3"]); + assert!(result.manifest.dependencies["sample"].path.is_some()); + assert_eq!(result.manifest.dependencies["rake"].groups, ["tools"]); + assert_eq!(result.inputs.len(), 3); +} + +#[test] +fn keeps_gemfile_output_out_of_the_protocol() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "puts 'not JSON'; warn 'a warning'; gem 'rake'\n", + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + assert_eq!(result.stdout.lines().collect::>(), ["not JSON"]); + assert_eq!(result.stderr.lines().collect::>(), ["a warning"]); + assert!(result.manifest.dependencies.contains_key("rake")); +} + +#[test] +fn rejects_unsupported_or_ambiguous_declarations() { + for (source, message) in [ + ("gem 'rake', mystery: true", "Unsupported gem options"), + ( + "gem 'rake', '>= 12'; gem 'rake', '< 10'", + "Conflicting declarations", + ), + ("gem 'rake', git: 'url', path: '.'", "Conflicting sources"), + ("gem 'rake', branch: 'main'", "Git options require"), + ( + "gem 'rake', git: 'url', branch: 'main', tag: 'v1'", + "Conflicting Git selectors", + ), + ("eval_gemfile 'Gemfile'", "Recursive eval_gemfile"), + ("source 'one'; source 'two'", "Multiple global sources"), + ( + "plugin 'unknown', mystery: true", + "Plugin options are unsupported", + ), + ("gem 'rake', '~> nonsense'", "Illformed requirement"), + ( + "gem 'rake', git: 'url', ref: 'one', rev: 'two'", + "Specify ref or rev", + ), + ("gem 'broken", "SyntaxError"), + ] { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", source); + let error = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap_err() + .to_string(); + assert!(error.contains(message), "{source}: {error}"); + assert!(error.contains("Gemfile"), "{error}"); + } +} + +#[test] +fn separate_evaluations_do_not_leak_state() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "gem 'first'\n"); + let evaluator = evaluator(); + assert!( + evaluator + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest + .dependencies + .contains_key("first") + ); + write(root.path(), "Gemfile", "gem 'second'\n"); + let second = evaluator.evaluate(root.path().join("Gemfile")).unwrap(); + assert_eq!(second.manifest.dependencies.len(), 1); + assert!(second.manifest.dependencies.contains_key("second")); +} + +#[test] +fn accepts_positional_option_hashes_and_identical_duplicates() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "gem 'rake', {require: false}\ngem 'rake', require: false\n", + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + assert_eq!(result.manifest.dependencies.len(), 1); + assert_eq!( + result.manifest.dependencies["rake"].require, + Some(Require::Enabled(false)) + ); +} + +#[test] +fn reports_missing_inputs_and_missing_ruby() { + let root = tempfile::tempdir().unwrap(); + assert_eq!( + evaluator() + .evaluate(root.path().join("missing")) + .unwrap_err() + .kind(), + std::io::ErrorKind::NotFound + ); + write(root.path(), "Gemfile", "gem 'rake'"); + assert_eq!( + Evaluator::new(root.path().join("missing-ruby")) + .evaluate(root.path().join("Gemfile")) + .unwrap_err() + .kind(), + std::io::ErrorKind::NotFound + ); + write(root.path(), "Gemfile", "eval_gemfile 'missing'"); + let error = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap_err() + .to_string(); + assert!(error.contains("missing"), "{error}"); +} + +#[test] +fn preserves_duplicate_declarations_with_different_activation_settings() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!( + "fixtures/evaluation/preserves_duplicate_declarations_with_different_activation_settings-1.rb" + ), + ); + let manifest = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest; + let dependency = &manifest.dependencies["rake"]; + assert_eq!(dependency.groups, ["development"]); + assert_eq!(dependency.platforms, ["ruby"]); + assert_eq!(dependency.variants.len(), 1); + assert_eq!(dependency.variants[0].groups, ["production"]); + assert_eq!(dependency.variants[0].platforms, ["jruby"]); + assert_eq!( + dependency.variants[0].require, + Some(Require::Name("rake/task".into())) + ); + assert_eq!( + toml::from_str::(&manifest.to_toml().unwrap()).unwrap(), + manifest + ); +} + +#[test] +fn evaluates_environment_scopes_and_conditions_for_each_declaration() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!( + "fixtures/evaluation/evaluates_environment_scopes_and_conditions_for_each_declaration-1.rb" + ), + ); + let deps = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest + .dependencies; + assert!(deps["present"].enabled); + assert!(!deps["missing"].enabled); + assert!(deps["matching"].enabled); + assert!(deps["first"].enabled); + assert!(!deps["second"].enabled); + assert!(!deps["all"].enabled); +} + +#[test] +fn supports_ruby_version_file_formats_and_custom_lockfiles() { + for text in [ + "ruby-3.4.5\n", + "3.4.5\n", + "nodejs 20\nruby 3.4.5 # comment\n", + "[tools]\nruby = \"3.4.5\"\n", + "ruby = '3.4.5'\n", + ] { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "ruby file: 'versions'\nlockfile 'Gemfile.custom.lock'\n", + ); + write(root.path(), "versions", text); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + assert_eq!(result.manifest.bundle.ruby, ["3.4.5"], "{text}"); + assert!( + result + .manifest + .bundle + .lockfile + .unwrap() + .ends_with("Gemfile.custom.lock") + ); + } +} + +#[test] +fn expands_git_shortcuts_and_preserves_custom_selector_metadata() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!( + "fixtures/evaluation/expands_git_shortcuts_and_preserves_custom_selector_metadata-1.rb" + ), + ); + let deps = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest + .dependencies; + assert_eq!( + deps["github"].git.as_deref(), + Some("https://github.com/rack/rack.git") + ); + assert_eq!( + deps["gitlab"].git.as_deref(), + Some("https://gitlab.com/group/repo.git") + ); + assert_eq!( + deps["gist"].git.as_deref(), + Some("https://gist.github.com/1234.git") + ); + assert_eq!( + deps["bitbucket"].git.as_deref(), + Some("https://owner@bitbucket.org/owner/owner.git") + ); + assert_eq!(deps["review"].rev.as_deref(), Some("refs/pull/1/head")); + assert_eq!(deps["rails"].branch.as_deref(), Some("main")); +} + +#[test] +fn records_bundler_read_file_inputs_without_loading_bundler() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "instance_eval(Bundler.read_file('extra.rb'))\n", + ); + write( + root.path(), + "extra.rb", + "gem 'rake'\nraise 'Bundler gem loaded' if $LOADED_FEATURES.any? { |path| path.include?('/bundler/') }\n", + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + assert_eq!(result.inputs.len(), 2); + assert!(result.inputs.iter().any(|path| path.ends_with("extra.rb"))); + assert!(result.manifest.dependencies.contains_key("rake")); +} + +#[test] +fn nested_sources_do_not_inherit_git_selectors() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!("fixtures/evaluation/nested_sources_do_not_inherit_git_selectors-1.rb"), + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + let deps = result.manifest.dependencies; + assert_eq!( + deps["registry"].source.as_deref(), + Some("https://example.test") + ); + assert_eq!(deps["registry"].branch, None); + assert_eq!(deps["local"].branch, None); + assert_eq!(deps["local"].submodules, None); + assert_eq!(deps["inner"].tag.as_deref(), Some("v1")); + assert_eq!(deps["inner"].branch, None); + assert_eq!(deps["outer"].branch.as_deref(), Some("main")); + assert_eq!(deps["outer"].submodules, Some(true)); +} + +#[test] +fn gemspec_name_uses_package_name_and_retains_package_requirements() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "gemspec name: 'sample'"); + write( + root.path(), + "unrelated-filename.gemspec", + include_str!( + "fixtures/evaluation/gemspec_name_uses_package_name_and_retains_package_requirements-1.rb" + ), + ); + write( + root.path(), + "other.gemspec", + "Gem::Specification.new do |s|\n s.name = 'other'\n s.version = '0.1.0'\nend", + ); + let manifest = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest; + assert_eq!(manifest.gemspecs.len(), 1); + let package = &manifest.gemspecs[0]; + assert_eq!(package.name, "sample"); + assert_eq!(package.version, "1.2.3"); + assert_eq!(package.required_ruby_version, [">= 3.2"]); + assert_eq!(package.runtime_dependencies["rack"], [">= 3", "< 4"]); + assert_eq!(package.development_dependencies["rake"], ["~> 13"]); + let roundtrip: Manifest = toml::from_str(&manifest.to_toml().unwrap()).unwrap(); + assert_eq!(roundtrip, manifest); + let merged: toml::Value = toml::from_str(&manifest.merge_project("").unwrap()).unwrap(); + assert_eq!(merged["gemspecs"][0]["name"].as_str(), Some("sample")); +} + +#[test] +fn gemfile_activation_wins_over_gemspec_development_declaration_in_both_orders() { + for source in [ + "gemspec; gem 'rake', '>= 13.2', group: :tools, require: false", + "gem 'rake', '>= 13.2', group: :tools, require: false; gemspec", + ] { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", source); + write( + root.path(), + "sample.gemspec", + include_str!( + "fixtures/evaluation/gemfile_activation_wins_over_gemspec_development_declaration_in_both_orders-1.rb" + ), + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + let rake = &result.manifest.dependencies["rake"]; + assert_eq!(rake.groups, ["tools"]); + assert_eq!(rake.require, Some(Require::Enabled(false))); + assert!(rake.version.contains(&"~> 13".to_owned())); + assert!(rake.version.contains(&">= 13.2".to_owned())); + } +} + +#[test] +fn rejects_invalid_platform_and_boolean_options() { + for source in [ + "gem 'rake', platform: :linux", + "gem 'rake', submodules: 'yes', git: 'url'", + "gem 'rake', force_ruby_platform: 'yes'", + ] { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", source); + assert!( + evaluator().evaluate(root.path().join("Gemfile")).is_err(), + "{source}" + ); + } +} + +#[test] +fn explicit_dependency_sources_override_scope_sources() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!("fixtures/evaluation/explicit_dependency_sources_override_scope_sources-1.rb"), + ); + let deps = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest + .dependencies; + assert_eq!( + deps["registry"].source.as_deref(), + Some("https://example.test") + ); + assert_eq!(deps["registry"].git, None); + assert_eq!(deps["registry"].branch, None); + assert!(deps["local"].path.is_some()); + assert_eq!(deps["local"].branch, None); + assert_eq!(deps["other"].git.as_deref(), Some("other")); + assert_eq!(deps["other"].branch, None); + assert_eq!(deps["other"].tag.as_deref(), Some("v1")); +} + +#[test] +fn successful_exit_without_manifest_is_an_evaluation_error() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "exit 0"); + let error = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap_err(); + assert!( + error + .to_string() + .contains("Ruby did not produce a Gemfile manifest") + ); +} + +#[test] +fn a_directory_cannot_be_evaluated_as_a_gemfile() { + let root = tempfile::tempdir().unwrap(); + assert_eq!( + evaluator().evaluate(root.path()).unwrap_err().kind(), + std::io::ErrorKind::InvalidInput + ); +} + +#[test] +fn duplicate_gemspec_requirements_are_combined_without_losing_bounds() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "gemspec({glob: 'packages/*.gemspec'}); ruby('>= 3.2', {engine: 'jruby', engine_version: '10.0.0'})", + ); + write( + root.path(), + "sample.gemspec", + include_str!( + "fixtures/evaluation/duplicate_gemspec_requirements_are_combined_without_losing_bounds-1.rb" + ), + ); + let manifest = evaluator() + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest; + assert_eq!( + manifest.gemspecs[0].runtime_dependencies["rack"], + [">= 3", "< 4"] + ); + assert_eq!( + manifest.gemspecs[0].development_dependencies["rake"], + [">= 13", "< 14"] + ); + assert_eq!(manifest.dependencies["rake"].version, [">= 13", "< 14"]); + assert_eq!( + manifest.dependencies["sample"].glob.as_deref(), + Some("packages/*.gemspec") + ); + assert_eq!(manifest.bundle.engine.as_deref(), Some("jruby")); + assert_eq!(manifest.bundle.engine_version.as_deref(), Some("10.0.0")); +} + +#[test] +fn selects_the_local_platform_variant_of_a_package_gemspec() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "puts Gem::Platform.local.to_s; gemspec", + ); + write( + root.path(), + "sample.gemspec", + include_str!( + "fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-1.rb" + ), + ); + write( + root.path(), + "sample-native.gemspec", + include_str!( + "fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-2.rb" + ), + ); + let result = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + assert_eq!(result.manifest.gemspecs.len(), 1); + assert_eq!(result.manifest.gemspecs[0].platform, result.stdout.trim()); + assert!( + result.manifest.gemspecs[0] + .runtime_dependencies + .contains_key("native") + ); + assert!( + !result.manifest.gemspecs[0] + .runtime_dependencies + .contains_key("generic") + ); +} + +#[test] +fn inherited_rubyopt_cannot_activate_bundler_or_break_evaluation() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "raise 'RUBYOPT retained' if ENV.key?('RUBYOPT'); gem 'rake'", + ); + let result = evaluator() + .env("RUBYOPT", "-rrb_gemfile_nonexistent_library") + .evaluate(root.path().join("Gemfile")) + .unwrap(); + assert!(result.manifest.dependencies.contains_key("rake")); +} + +#[test] +fn source_options_preserve_dependencies_without_exporting_cooldowns() { + let manifest = evaluator() + .evaluate( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/ruby/source_options/Gemfile"), + ) + .unwrap() + .manifest; + assert_eq!( + manifest.bundle.source.as_deref(), + Some("https://rubygems.org") + ); + assert_eq!( + manifest.dependencies["scoped"].source.as_deref(), + Some("https://example.test") + ); + let toml = manifest.to_toml().unwrap(); + assert_eq!(toml::from_str::(&toml).unwrap(), manifest); + assert!(!toml.contains("cooldown")); + let kdl = manifest.to_kdl().unwrap(); + assert!(kdl.parse::().is_ok()); + assert!(!kdl.contains("cooldown")); +} + +#[test] +fn explicit_nil_require_disables_autorequire_in_exports() { + let manifest = evaluator() + .evaluate( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/ruby/require_settings/Gemfile"), + ) + .unwrap() + .manifest; + assert_eq!( + manifest.dependencies["nil-require"].require, + Some(Require::Enabled(false)) + ); + assert_eq!( + manifest.dependencies["false-require"].require, + Some(Require::Enabled(false)) + ); + assert_eq!(manifest.dependencies["default-require"].require, None); + assert_eq!( + toml::from_str::(&manifest.to_toml().unwrap()).unwrap(), + manifest + ); + let parsed = Manifest::from_kdl(&manifest.to_kdl().unwrap()).unwrap(); + assert_eq!(parsed, manifest); +} + +#[test] +fn compatibility_helpers_preserve_manifest_and_input_tracking() { + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ruby/compatibility_helpers"); + let evaluation = evaluator().evaluate(fixture.join("Gemfile")).unwrap(); + assert_eq!(evaluation.manifest.dependencies.len(), 3); + assert!(!evaluation.manifest.dependencies.contains_key("keep")); + assert_eq!( + evaluation.manifest.dependencies["replace"].version, + ["~> 3"] + ); + assert_eq!(evaluation.manifest.dependencies["rack"].version, ["~> 3"]); + assert_eq!( + evaluation.manifest.dependencies["tzinfo-data"].platforms, + ["windows"] + ); + assert!( + evaluation + .inputs + .contains(&dunce::canonicalize(fixture.join("sample.gemspec")).unwrap()) + ); + assert_eq!( + toml::from_str::(&evaluation.manifest.to_toml().unwrap()).unwrap(), + evaluation.manifest + ); +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/chatwoot.json b/crates/rb-gemfile/tests/fixtures/corpus/chatwoot.json new file mode 100644 index 0000000..26bbc79 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/chatwoot.json @@ -0,0 +1,29 @@ +{ + "dependencies": { + "rails": { + "version": "7.2.3.1", + "groups": [ + "default" + ] + }, + "puma": { + "version": [ + "~> 7.2", + ">= 7.2.1" + ] + }, + "byebug": { + "platforms": [ + "mri" + ], + "groups": [ + "development", + "test" + ] + } + }, + "absent": [ + "manageiq-schema", + "idn-ruby" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/diaspora.json b/crates/rb-gemfile/tests/fixtures/corpus/diaspora.json new file mode 100644 index 0000000..3d617cc --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/diaspora.json @@ -0,0 +1,27 @@ +{ + "dependencies": { + "rails": { + "version": "6.1.7.10" + }, + "mysql2": { + "version": "0.5.7", + "groups": [ + "mysql" + ] + }, + "pg": { + "version": "1.6.3", + "groups": [ + "postgresql" + ] + } + }, + "optional_groups": [ + "mysql", + "postgresql" + ], + "absent": [ + "manageiq-schema", + "ai-agents" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/errbit.json b/crates/rb-gemfile/tests/fixtures/corpus/errbit.json new file mode 100644 index 0000000..94d5ee0 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/errbit.json @@ -0,0 +1,20 @@ +{ + "dependencies": { + "rails": { + "version": "8.1.3.1" + }, + "listen": { + "version": "~> 3.10", + "groups": [ + "development" + ] + }, + "airbrake": { + "require": false + } + }, + "absent": [ + "manageiq-schema", + "pg" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/forem.json b/crates/rb-gemfile/tests/fixtures/corpus/forem.json new file mode 100644 index 0000000..b349664 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/forem.json @@ -0,0 +1,23 @@ +{ + "dependencies": { + "rails": { + "version": "8.0.5" + }, + "acts_as_follower": { + "git": "https://github.com/forem/acts_as_follower.git", + "branch": "master" + }, + "stackprof": { + "platforms": [ + "ruby" + ], + "groups": [ + "test" + ] + } + }, + "absent": [ + "manageiq-schema", + "idn-ruby" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/foreman.json b/crates/rb-gemfile/tests/fixtures/corpus/foreman.json new file mode 100644 index 0000000..66cc27d --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/foreman.json @@ -0,0 +1,31 @@ +{ + "dependencies": { + "rails": { + "version": "~> 7.0.3" + }, + "fog-vsphere": { + "version": [ + ">= 3.7.1", + "< 4.0" + ], + "groups": [ + "vmware" + ] + }, + "puma": { + "version": [ + ">= 8.0", + "< 9" + ], + "require": false, + "groups": [ + "test", + "service" + ] + } + }, + "absent": [ + "manageiq-schema", + "idn-ruby" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/lobsters.json b/crates/rb-gemfile/tests/fixtures/corpus/lobsters.json new file mode 100644 index 0000000..33af938 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/lobsters.json @@ -0,0 +1,20 @@ +{ + "dependencies": { + "rails": { + "version": ">= 0" + }, + "sqlite3": { + "force_ruby_platform": true + }, + "debug": { + "groups": [ + "test", + "development" + ] + } + }, + "absent": [ + "manageiq-schema", + "pg" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/manageiq.json b/crates/rb-gemfile/tests/fixtures/corpus/manageiq.json new file mode 100644 index 0000000..e748d6e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/manageiq.json @@ -0,0 +1,28 @@ +{ + "dependencies": { + "rails": { + "version": [ + "~>8.0.5", + ">=8.0.5.1" + ] + }, + "pg": { + "version": ">=1.6.3.1", + "source": "https://rubygems.manageiq.org", + "require": false + }, + "manageiq-schema": { + "git": "https://github.com/ManageIQ/manageiq-schema", + "branch": "master" + } + }, + "optional_groups": [ + "qpid_proton", + "systemd", + "appliance" + ], + "absent": [ + "ai-agents", + "idn-ruby" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/mastodon.json b/crates/rb-gemfile/tests/fixtures/corpus/mastodon.json new file mode 100644 index 0000000..e5376c0 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/mastodon.json @@ -0,0 +1,24 @@ +{ + "dependencies": { + "rails": { + "version": "~> 8.1.0" + }, + "webpush": { + "git": "https://github.com/mastodon/webpush.git", + "rev": "9631ac63045cfabddacc69fc06e919b4c13eb913" + }, + "devise_pam_authenticatable2": { + "version": "~> 9.2", + "groups": [ + "pam_authentication" + ] + } + }, + "optional_groups": [ + "pam_authentication" + ], + "absent": [ + "manageiq-schema", + "ai-agents" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/postal.json b/crates/rb-gemfile/tests/fixtures/corpus/postal.json new file mode 100644 index 0000000..b8d04fa --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/postal.json @@ -0,0 +1,24 @@ +{ + "dependencies": { + "rails": { + "version": "= 7.1.6" + }, + "execjs": { + "version": [ + "~> 2.7", + "< 2.8" + ] + }, + "coffee-rails": { + "version": "~> 5.0", + "groups": [ + "development", + "assets" + ] + } + }, + "absent": [ + "manageiq-schema", + "idn-ruby" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/corpus/zammad.json b/crates/rb-gemfile/tests/fixtures/corpus/zammad.json new file mode 100644 index 0000000..2942da8 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/corpus/zammad.json @@ -0,0 +1,25 @@ +{ + "dependencies": { + "rails": { + "version": "~> 8.1.0" + }, + "debug": { + "platforms": [ + "mri" + ], + "groups": [ + "development", + "test" + ], + "require": false + }, + "delayed_job": { + "git": "https://github.com/zammad-deps/delayed_job", + "branch": "threadsafe" + } + }, + "absent": [ + "manageiq-schema", + "ai-agents" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/duplicate_gemspec_requirements_are_combined_without_losing_bounds-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/duplicate_gemspec_requirements_are_combined_without_losing_bounds-1.rb new file mode 100644 index 0000000..81ffca6 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/duplicate_gemspec_requirements_are_combined_without_losing_bounds-1.rb @@ -0,0 +1,8 @@ +Gem::Specification.new do |s| + s.name = 'sample' + s.version = '1.0' + s.add_dependency 'rack', '>= 3' + s.add_dependency 'rack', '< 4' + s.add_development_dependency 'rake', '>= 13' + s.add_development_dependency 'rake', '< 14' +end \ No newline at end of file diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/evaluates_environment_scopes_and_conditions_for_each_declaration-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/evaluates_environment_scopes_and_conditions_for_each_declaration-1.rb new file mode 100644 index 0000000..3886cc9 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/evaluates_environment_scopes_and_conditions_for_each_declaration-1.rb @@ -0,0 +1,18 @@ + +ENV.delete('RB_TEST_MISSING') +ENV['RB_TEST_FEATURE'] = 'yes' +env 'RB_TEST_FEATURE' do + gem 'present' +end +env 'RB_TEST_MISSING' do + gem 'missing' +end +env 'RB_TEST_FEATURE' => /^y/ do + gem 'matching' +end +count = 0 +install_if -> { count += 1; count == 1 } do + gem 'first' + gem 'second' +end +gem 'all', install_if: [-> { true }, -> { false }] diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/evaluates_requirements_groups_and_require_settings_without_bundler-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/evaluates_requirements_groups_and_require_settings_without_bundler-1.rb new file mode 100644 index 0000000..52494ed --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/evaluates_requirements_groups_and_require_settings_without_bundler-1.rb @@ -0,0 +1,12 @@ + +raise 'Bundler gem loaded' if $LOADED_FEATURES.any? { |path| path.include?('/bundler/') } +source 'https://rubygems.org' +ruby '>= 3.2', '< 5', engine: 'jruby', engine_version: '10.0.0' +gem 'rails', '~> 8.0', '>= 8.0.2' +group :development, :test, optional: true do + gem 'debug', require: false + group :tools do + gem 'rake', require: ['rake', 'rake/task'] + end +end +gem 'rack', require: 'rack/builder' diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/expands_git_shortcuts_and_preserves_custom_selector_metadata-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/expands_git_shortcuts_and_preserves_custom_selector_metadata-1.rb new file mode 100644 index 0000000..5bce23c --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/expands_git_shortcuts_and_preserves_custom_selector_metadata-1.rb @@ -0,0 +1,10 @@ + +gem 'github', github: 'rack' +gem 'gitlab', gitlab: 'group/repo' +gem 'gist', gist: '1234' +gem 'bitbucket', bitbucket: 'owner' +git_source(:review) { |name| { 'git' => "https://example.test/#{name}", 'ref' => 'refs/pull/1/head' } } +gem 'review', review: 'repo' +github 'rails/rails', branch: 'main' do + gem 'rails' +end diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/explicit_dependency_sources_override_scope_sources-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/explicit_dependency_sources_override_scope_sources-1.rb new file mode 100644 index 0000000..73c47ca --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/explicit_dependency_sources_override_scope_sources-1.rb @@ -0,0 +1,5 @@ +git 'outer', branch: 'main' do + gem 'registry', source: 'https://example.test' + gem 'local', path: 'local' + gem 'other', git: 'other', tag: 'v1' +end \ No newline at end of file diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/gemfile_activation_wins_over_gemspec_development_declaration_in_both_orders-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/gemfile_activation_wins_over_gemspec_development_declaration_in_both_orders-1.rb new file mode 100644 index 0000000..06b3a55 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/gemfile_activation_wins_over_gemspec_development_declaration_in_both_orders-1.rb @@ -0,0 +1,5 @@ +Gem::Specification.new do |s| + s.name = 'sample' + s.version = '1.0' + s.add_development_dependency 'rake', '~> 13' +end \ No newline at end of file diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/gemspec_name_uses_package_name_and_retains_package_requirements-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/gemspec_name_uses_package_name_and_retains_package_requirements-1.rb new file mode 100644 index 0000000..f707521 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/gemspec_name_uses_package_name_and_retains_package_requirements-1.rb @@ -0,0 +1,9 @@ +Gem::Specification.new do |s| + s.name = 'sample' + s.version = '1.2.3' + s.summary = 'Sample' + s.authors = ['Example'] + s.required_ruby_version = '>= 3.2' + s.add_dependency 'rack', '>= 3', '< 4' + s.add_development_dependency 'rake', '~> 13' +end \ No newline at end of file diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/loads_project_gemspec_and_ruby_version_file-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/loads_project_gemspec_and_ruby_version_file-1.rb new file mode 100644 index 0000000..337bc18 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/loads_project_gemspec_and_ruby_version_file-1.rb @@ -0,0 +1,9 @@ + +Gem::Specification.new do |s| + s.name = 'sample' + s.version = '1.2.3' + s.summary = 'sample' + s.authors = ['Example'] + s.add_dependency 'rack', '~> 3.0' + s.add_development_dependency 'rake', '>= 13' +end diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/nested_sources_do_not_inherit_git_selectors-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/nested_sources_do_not_inherit_git_selectors-1.rb new file mode 100644 index 0000000..3ef3619 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/nested_sources_do_not_inherit_git_selectors-1.rb @@ -0,0 +1,12 @@ +git 'outer', branch: 'main', submodules: true do + source 'https://example.test' do + gem 'registry' + end + path 'local' do + gem 'local' + end + git 'inner', tag: 'v1' do + gem 'inner' + end + gem 'outer' +end \ No newline at end of file diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/preserves_duplicate_declarations_with_different_activation_settings-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/preserves_duplicate_declarations_with_different_activation_settings-1.rb new file mode 100644 index 0000000..d999173 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/preserves_duplicate_declarations_with_different_activation_settings-1.rb @@ -0,0 +1,11 @@ + +platforms :ruby do + group :development do + gem 'rake', '>= 13', require: false + end +end +platforms :jruby do + group :production do + gem 'rake', '>= 13', require: 'rake/task' + end +end diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/preserves_platforms_and_evaluated_install_conditions-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/preserves_platforms_and_evaluated_install_conditions-1.rb new file mode 100644 index 0000000..4820696 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/preserves_platforms_and_evaluated_install_conditions-1.rb @@ -0,0 +1,11 @@ + +platforms :jruby do + gem 'jdbc', force_ruby_platform: true +end +install_if -> { false } do + gem 'disabled' + install_if -> { true } do + gem 'also_disabled' + end +end +gem 'enabled', platforms: [:ruby, :windows], install_if: -> { true } diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/scopes_sources_and_resolves_included_paths-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/scopes_sources_and_resolves_included_paths-1.rb new file mode 100644 index 0000000..386d1d0 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/scopes_sources_and_resolves_included_paths-1.rb @@ -0,0 +1,12 @@ + +source 'https://rubygems.org' +source 'https://gems.example.test' do + gem 'private-gem' +end +git 'https://example.test/repo.git', ref: 'abc123', submodules: true do + gem 'git-gem' +end +git_source(:company) { |name| "https://example.test/#{name}.git" } +gem 'custom', company: 'custom', tag: 'v1' +eval_gemfile 'nested/Gemfile' +gem 'normal' diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-1.rb b/crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-1.rb new file mode 100644 index 0000000..1d94c91 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-1.rb @@ -0,0 +1,5 @@ +Gem::Specification.new do |s| + s.name = 'sample' + s.version = '1.0' + s.add_dependency 'generic' +end \ No newline at end of file diff --git a/crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-2.rb b/crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-2.rb new file mode 100644 index 0000000..91009c9 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/evaluation/selects_the_local_platform_variant_of_a_package_gemspec-2.rb @@ -0,0 +1,6 @@ +Gem::Specification.new do |s| + s.name = 'sample' + s.version = '1.0' + s.platform = Gem::Platform.local + s.add_dependency 'native' +end \ No newline at end of file diff --git a/crates/rb-gemfile/tests/fixtures/format/complex_variants_and_escaping_survive_both_formats-1.toml b/crates/rb-gemfile/tests/fixtures/format/complex_variants_and_escaping_survive_both_formats-1.toml new file mode 100644 index 0000000..5c86062 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/complex_variants_and_escaping_survive_both_formats-1.toml @@ -0,0 +1,4 @@ +[bundle] +source = "https://rubygems.org" +[dependencies."https://gems.example.com/?name=\"special\""] +"strange.name" = { version = [">= 1", "< 2"], groups = ["test", "development"], platforms = ["mri", "jruby"], require = ["a/b", "c\\d"], variants = [{groups=["other"], require=false}] } diff --git a/crates/rb-gemfile/tests/fixtures/format/default_registry_pin.toml b/crates/rb-gemfile/tests/fixtures/format/default_registry_pin.toml new file mode 100644 index 0000000..46eea3e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/default_registry_pin.toml @@ -0,0 +1,9 @@ +[[sources]] +url = "https://rubygems.org" +default = true +[sources.dependencies] +implicit = "~> 1.0" +[[sources]] +url = "https://rubygems.org" +[sources.dependencies] +pinned = "~> 2.0" diff --git a/crates/rb-gemfile/tests/fixtures/format/evaluate-1.rb b/crates/rb-gemfile/tests/fixtures/format/evaluate-1.rb new file mode 100644 index 0000000..5774021 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/evaluate-1.rb @@ -0,0 +1,16 @@ + +source 'https://rubygems.org' +gem 'rails', '~> 8.0' +gem 'rake' +group :development do + gem 'debug', require: false +end +source 'https://gems.example.com' do + gem 'internal', '~> 2.0' + gem 'another', require: false +end +gem 'git-gem', git: 'https://github.com/example/gem', tag: 'v1.0' +gem 'a.b', '~> 1.0' +install_if -> { false } do + gem 'excluded' +end diff --git a/crates/rb-gemfile/tests/fixtures/format/explicit_sources.toml b/crates/rb-gemfile/tests/fixtures/format/explicit_sources.toml new file mode 100644 index 0000000..499acac --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/explicit_sources.toml @@ -0,0 +1,17 @@ +[[sources]] +url = "https://rubygems.org" +default = true +[sources.dependencies] +rails = "~> 8.0" +[[sources.groups]] +names = ["development", "test"] +[sources.groups.dependencies] +rake = { version = "~> 13", require = false } +[[sources.groups]] +names = ["production"] +[sources.groups.dependencies] +rake = { version = "~> 13", require = "rake/task" } +[[sources]] +url = "https://gems.example.com" +[sources.dependencies] +internal = "~> 2.0" diff --git a/crates/rb-gemfile/tests/fixtures/format/group_source.kdl b/crates/rb-gemfile/tests/fixtures/format/group_source.kdl new file mode 100644 index 0000000..68748c5 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/group_source.kdl @@ -0,0 +1,7 @@ +group "development" { + group "test" { + source "https://gems.example.com" { + gem "internal" "~> 2.0" require=#false + } + } +} diff --git a/crates/rb-gemfile/tests/fixtures/format/inline_sources_and_variants_with_different_sources_remain_unambiguous-1.toml b/crates/rb-gemfile/tests/fixtures/format/inline_sources_and_variants_with_different_sources_remain_unambiguous-1.toml new file mode 100644 index 0000000..c9a22aa --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/inline_sources_and_variants_with_different_sources_remain_unambiguous-1.toml @@ -0,0 +1,5 @@ +[bundle] +source = "https://rubygems.org" +[dependencies] +custom = {source="custom-registry"} +mixed = {source="https://one.test", variants=[{source="https://two.test", groups=["test"]}]} diff --git a/crates/rb-gemfile/tests/fixtures/format/kdl_uses_source_blocks_and_preserves_metadata_and_options-1.toml b/crates/rb-gemfile/tests/fixtures/format/kdl_uses_source_blocks_and_preserves_metadata_and_options-1.toml new file mode 100644 index 0000000..ba7ac59 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/kdl_uses_source_blocks_and_preserves_metadata_and_options-1.toml @@ -0,0 +1,4 @@ +[project] +name='tea room' +[scripts] +test='rspec' diff --git a/crates/rb-gemfile/tests/fixtures/format/multi_source/Gemfile b/crates/rb-gemfile/tests/fixtures/format/multi_source/Gemfile new file mode 100644 index 0000000..2f803fb --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/multi_source/Gemfile @@ -0,0 +1,15 @@ +source 'https://rubygems.org' +gem 'rails', '~> 8.0' +group :development, :test do + gem 'rake', '~> 13', require: false +end +group :production do + gem 'rake', '~> 13', require: 'rake/task' +end +source 'https://gems.example.com' do + gem 'internal', '~> 2.0' +end +source 'https://plugins.example.com' do + gem 'plugin', platforms: :ruby +end +gem 'git-gem', git: 'https://github.com/example/gem', tag: 'v1.0' diff --git a/crates/rb-gemfile/tests/fixtures/format/multi_source/project.kdl b/crates/rb-gemfile/tests/fixtures/format/multi_source/project.kdl new file mode 100644 index 0000000..efed11f --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/multi_source/project.kdl @@ -0,0 +1,18 @@ +gem "git-gem" git="https://github.com/example/gem" tag="v1.0" +source "https://rubygems.org" default=#true { + gem "rails" "~> 8.0" + group "development" "test" { + gem "rake" "~> 13" require=#false + } + group "production" { + gem "rake" "~> 13" require="rake/task" + } +} +source "https://gems.example.com" { + gem "internal" "~> 2.0" +} +source "https://plugins.example.com" { + gem "plugin" { + platforms "ruby" + } +} diff --git a/crates/rb-gemfile/tests/fixtures/format/multi_source/project.toml b/crates/rb-gemfile/tests/fixtures/format/multi_source/project.toml new file mode 100644 index 0000000..96e51fe --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/multi_source/project.toml @@ -0,0 +1,23 @@ +[dependencies] +git-gem = { git = "https://github.com/example/gem", tag = "v1.0" } +[[sources]] +url = "https://rubygems.org" +default = true +[sources.dependencies] +rails = "~> 8.0" +[[sources.groups]] +names = ["development", "test"] +[sources.groups.dependencies] +rake = { version = "~> 13", require = false } +[[sources.groups]] +names = ["production"] +[sources.groups.dependencies] +rake = { version = "~> 13", require = "rake/task" } +[[sources]] +url = "https://gems.example.com" +[sources.dependencies] +internal = "~> 2.0" +[[sources]] +url = "https://plugins.example.com" +[sources.dependencies] +plugin = { platforms = ["ruby"] } diff --git a/crates/rb-gemfile/tests/fixtures/format/package_named_item.toml b/crates/rb-gemfile/tests/fixtures/format/package_named_item.toml new file mode 100644 index 0000000..d5f4efd --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/package_named_item.toml @@ -0,0 +1,10 @@ +[[gemspecs]] +name = "sample" +version = "1.0.0" +platform = "ruby" +path = "." +required_ruby_version = [">= 3.3"] +required_rubygems_version = [">= 0"] +[gemspecs.runtime_dependencies] +item = ["~> 1"] +[gemspecs.development_dependencies] diff --git a/crates/rb-gemfile/tests/fixtures/format/reads_mixed_and_expanded_dependencies_and_checks_source_conflicts-1.toml b/crates/rb-gemfile/tests/fixtures/format/reads_mixed_and_expanded_dependencies_and_checks_source_conflicts-1.toml new file mode 100644 index 0000000..07a0e1a --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/reads_mixed_and_expanded_dependencies_and_checks_source_conflicts-1.toml @@ -0,0 +1,8 @@ +[dependencies] +rails = "~> 8.0" +[dependencies.debug] +groups = ["development"] +require = false +[dependencies."https://gems.example.com"] +internal = "~> 2.0" +extra = { version = [">= 1", "< 2"], require = false } diff --git a/crates/rb-gemfile/tests/fixtures/format/repeated_declarations.toml b/crates/rb-gemfile/tests/fixtures/format/repeated_declarations.toml new file mode 100644 index 0000000..6dc1a0e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/repeated_declarations.toml @@ -0,0 +1,7 @@ +[[sources]] +url = "https://rubygems.org" +[[sources.groups]] +names = ["development"] +[sources.groups.dependencies] +rake = [{ version = "~> 13", require = ["rake/task"] }, { version = "~> 13", require = false }] +debug = { require = false } diff --git a/crates/rb-gemfile/tests/fixtures/format/source_group.kdl b/crates/rb-gemfile/tests/fixtures/format/source_group.kdl new file mode 100644 index 0000000..e863b1a --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/format/source_group.kdl @@ -0,0 +1,5 @@ +source "https://gems.example.com" { + group "development" "test" { + gem "internal" "~> 2.0" require=#false + } +} diff --git a/crates/rb-gemfile/tests/fixtures/project/exports_only_active_declarations_and_omits_redundant_fields-1.rb b/crates/rb-gemfile/tests/fixtures/project/exports_only_active_declarations_and_omits_redundant_fields-1.rb new file mode 100644 index 0000000..eb58384 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/project/exports_only_active_declarations_and_omits_redundant_fields-1.rb @@ -0,0 +1,21 @@ + +source 'https://rubygems.org' +install_if -> { false } do + gem 'excluded' + group :test do + gem 'mixed', require: false + end +end +group :development do + gem 'mixed', require: 'mixed/runtime' +end +install_if -> { false } do + group :test do + gem 'active_first' + end +end +gem 'active_first' +gem 'retained', require: false +platforms :jruby do + gem 'retained', require: 'retained/java' +end diff --git a/crates/rb-gemfile/tests/fixtures/project/merges_root_settings_and_additional_dependencies-1.toml b/crates/rb-gemfile/tests/fixtures/project/merges_root_settings_and_additional_dependencies-1.toml new file mode 100644 index 0000000..c7dd06e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/project/merges_root_settings_and_additional_dependencies-1.toml @@ -0,0 +1,10 @@ +[project] +name = "sample" +[scripts] +test = "rspec" +[bundle] +source = "https://rubygems.org" +without = ["development"] +[dependencies] +rake = ">= 13" +rack = "~> 3" diff --git a/crates/rb-gemfile/tests/fixtures/real-world/README.md b/crates/rb-gemfile/tests/fixtures/real-world/README.md new file mode 100644 index 0000000..3830671 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/README.md @@ -0,0 +1,7 @@ +# Real-world Gemfiles + +Copied unchanged from `examples/real-world` on `new-beginning`. Each project includes its original `source.json` with upstream repository, revision, and file hashes, plus its license where present. Lockfiles and the prototype's migrated manifests are excluded: these tests exercise declaration evaluation only. + +Foreman's `bundler.d` files and Errbit's `UserGemfile` are included because the Gemfiles evaluate them. ManageIQ's plugin declaration is retained as metadata; plugin code is not installed or executed. + +The corpus tests check dependency counts and specific requirements, groups, sources, and require settings. They run offline and do not install any project dependencies. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/Gemfile new file mode 100644 index 0000000..cdce859 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/Gemfile @@ -0,0 +1,283 @@ +source 'https://rubygems.org' + +ruby '3.4.4' + +##-- base gems for rails --## + +gem 'rack-cors', '2.0.0', require: 'rack/cors' +gem 'rails', '7.2.3.1' + +# Reduces boot times through caching; required in config/boot.rb +gem 'bootsnap', require: false + +##-- rails application helper gems --## +gem 'acts-as-taggable-on' +gem 'attr_extras' +gem 'browser' +gem 'hashie' +gem 'jbuilder' +gem 'kaminari' +gem 'responders', '>= 3.1.1' +gem 'rest-client' +gem 'telephone_number' +gem 'time_diff' +gem 'tzinfo-data' +gem 'valid_email2' +gem 'email-provider-info' +gem 'gemoji' +# compress javascript config.assets.js_compressor +gem 'uglifier' +##-- used for single column multiple binary flags in notification settings/feature flagging --## +gem 'flag_shih_tzu' +# Random name generator for user names +gem 'haikunator' +# Template parsing safely +gem 'liquid' +# Parse Markdown to HTML +gem 'commonmarker' +# Validate Data against JSON Schema +gem 'json_schemer' +# used in swagger build +gem 'json_refs' +# Rack middleware for blocking & throttling abusive requests +gem 'rack-attack', '>= 6.7.0' +# a utility tool for streaming, flexible and safe downloading of remote files +gem 'down' +# SSRF-safe URL fetching +gem 'ssrf_filter', '~> 1.5' +# authentication type to fetch and send mail over oauth2.0 +gem 'gmail_xoauth' +# Lock net-smtp to 0.3.4 to avoid issues with gmail_xoauth2 +gem 'net-smtp', '~> 0.3.4' +# Prevent CSV injection +gem 'csv-safe' + +##-- for active storage --## +gem 'aws-sdk-s3', require: false +gem 'azure-blob', require: false +gem 'google-cloud-storage', '>= 1.48.0', require: false +gem 'image_processing' + +##-- for actionmailbox --## +gem 'aws-actionmailbox-ses', '~> 0' + +##-- gems for database --# +gem 'groupdate' +gem 'pg' +gem 'redis' +gem 'redis-namespace' +# super fast record imports in bulk +gem 'activerecord-import' + +gem 'searchkick' +gem 'opensearch-ruby' +gem 'faraday_middleware-aws-sigv4' + +##--- gems for server & infra configuration ---## +gem 'dotenv-rails', '>= 3.0.0' +gem 'foreman' +gem 'puma', '~> 7.2', '>= 7.2.1' +gem 'vite_rails' +# metrics on heroku +gem 'barnes' + +##--- gems for authentication & authorization ---## +gem 'devise', '>= 4.9.4' +# 2.2.3 requires Devise 5; Chatwoot remains on Devise 4 for this upgrade stack. +gem 'devise-secure_password', '2.2.1' +gem 'devise_token_auth', '>= 1.2.3' +gem 'rails-i18n', '~> 7.0' +# two-factor authentication +gem 'devise-two-factor', '>= 5.0.0' +# authorization +gem 'jwt', '~> 2.10', '>= 2.10.3' +gem 'pundit' + +# super admin +gem 'administrate', '>= 0.20.1' +gem 'administrate-field-active_storage', '>= 1.0.3' +gem 'administrate-field-belongs_to_search', '>= 0.10.0' + +##--- gems for pubsub service ---## +# https://karolgalanciak.com/blog/2019/11/30/from-activerecord-callbacks-to-publish-slash-subscribe-pattern-and-event-driven-design/ +gem 'wisper', '2.0.0' + +##--- gems for channels ---## +gem 'facebook-messenger' +gem 'line-bot-api' +gem 'twilio-ruby' +# twitty will handle subscription of twitter account events +# gem 'twitty', git: 'https://github.com/chatwoot/twitty' +gem 'twitty', '~> 0.1.5' +# facebook client +gem 'koala' +# slack client +gem 'slack-ruby-client', '~> 2.7.0' +# for dialogflow integrations +gem 'google-cloud-dialogflow-v2', '>= 0.24.0' +gem 'grpc' +# Translate integrations +# 'google-cloud-translate' gem depends on faraday 2.0 version +# this dependency breaks the slack-ruby-client gem +gem 'google-cloud-translate-v3', '>= 0.7.0' + +##-- apm and error monitoring ---# +# loaded only when environment variables are set. +# ref application.rb +gem 'datadog', '~> 2.0', require: false +gem 'elastic-apm', require: false +gem 'newrelic_rpm', require: false +gem 'newrelic-sidekiq-metrics', '>= 1.6.2', require: false +gem 'scout_apm', require: false +gem 'sentry-rails', '>= 5.19.0', require: false +gem 'sentry-ruby', require: false +gem 'sentry-sidekiq', '>= 5.19.0', require: false + +##-- background job processing --## +gem 'sidekiq', '~> 7.3.10' +# We want cron jobs +gem 'sidekiq-cron', '>= 2.4.0' +# for sidekiq healthcheck +gem 'sidekiq_alive' +# publishes Sidekiq queue metrics to CloudWatch for autoscaling (opt-in via ENABLE_SIDEKIQ_CLOUDWATCH) +gem 'speedshop-cloudwatch', '~> 0.2.1', require: false + +##-- Push notification service --## +gem 'fcm' +gem 'web-push', '>= 3.0.1' + +##-- geocoding / parse location from ip --## +# http://www.rubygeocoder.com/ +gem 'geocoder' +# to parse maxmind db +gem 'maxminddb' + +# to create db triggers +gem 'hairtrigger' + +gem 'procore-sift' + +# parse email +gem 'email_reply_trimmer' + +gem 'html2text' + +# to calculate working hours +gem 'working_hours' + +# full text search for articles +gem 'pg_search' + +# Subscriptions, Billing +gem 'stripe', '~> 18.0' + +## - helper gems --## +## to populate db with sample data +gem 'faker' + +# Include logrange conditionally in intializer using env variable +gem 'lograge', '~> 0.14.0', require: false + +# worked with microsoft refresh token +gem 'omniauth-oauth2' + +gem 'audited', '~> 5.4', '>= 5.4.1' + +# need for google auth +gem 'omniauth', '>= 2.1.2' +gem 'omniauth-saml' +gem 'omniauth-google-oauth2', '>= 1.1.3' +gem 'omniauth-rails_csrf_protection', '~> 1.0', '>= 1.0.2' + +## Gems for reponse bot +# adds cosine similarity to postgres using vector extension +gem 'neighbor' +gem 'pgvector' +# Convert Website HTML to Markdown +gem 'reverse_markdown' + +gem 'iso-639' +gem 'ruby-openai' +gem 'ai-agents', '>= 0.12.0' + +# TODO: Move this gem as a dependency of ai-agents +gem 'ruby_llm', '>= 1.14.1' +gem 'ruby_llm-schema' + +gem 'cld3', '~> 3.7' + +# OpenTelemetry for LLM observability +gem 'opentelemetry-sdk' +gem 'opentelemetry-exporter-otlp' + +gem 'shopify_api' + +gem 'firecrawl-sdk', '~> 1.0', require: 'firecrawl' + +### Gems required only in specific deployment environments ### +############################################################## + +group :production do + # we dont want request timing out in development while using byebug + gem 'rack-timeout' + # for heroku autoscaling + gem 'judoscale-rails', require: false + gem 'judoscale-sidekiq', require: false +end + +group :development do + gem 'annotaterb' + gem 'bullet' + gem 'letter_opener' + gem 'scss_lint', require: false + gem 'web-console', '>= 4.2.1' + + # When we want to squash migrations + gem 'squasher' + + # profiling + gem 'rack-mini-profiler', '>= 3.2.0', require: false + gem 'stackprof' + # Should install the associated chrome extension to view query logs + gem 'meta_request', '>= 0.8.3' + + gem 'tidewave' +end + +group :test do + # fast cleaning of database + gem 'database_cleaner' + # mock http calls + gem 'webmock' + # test profiling + gem 'test-prof' + gem 'simplecov_json_formatter', require: false +end + +group :development, :test do + gem 'active_record_query_trace' + ##--- gems for debugging and error reporting ---## + # static analysis + gem 'brakeman' + gem 'bundle-audit', require: false + gem 'byebug', platform: :mri + gem 'climate_control' + gem 'debug', '~> 1.8' + gem 'factory_bot_rails', '>= 6.4.3' + gem 'listen' + gem 'mock_redis' + gem 'pry-rails' + gem 'rspec_junit_formatter' + gem 'rspec-rails', '>= 6.1.5' + gem 'rubocop', require: false + gem 'rubocop-performance', require: false + gem 'rubocop-rails', require: false + gem 'rubocop-rspec', require: false + gem 'rubocop-factory_bot', require: false + gem 'seed_dump' + gem 'shoulda-matchers' + gem 'simplecov', '>= 0.21', require: false + gem 'skooma' + gem 'spring' + gem 'spring-watcher-listen' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/LICENSE b/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/LICENSE new file mode 100644 index 0000000..d0425a7 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2017-2026 Chatwoot Inc. + +Portions of this software are licensed as follows: + +* All content that resides under the "enterprise/" directory of this repository, if that directory exists, is licensed under the license defined in "enterprise/LICENSE". +* All third party components incorporated into the Chatwoot Software are licensed under the original license provided by the owner of the applicable component. +* Content outside of the above mentioned directories or restrictions above is available under the "MIT Expat" license as defined below. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/source.json b/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/source.json new file mode 100644 index 0000000..7119999 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/chatwoot/source.json @@ -0,0 +1,14 @@ +{ + "repo": "chatwoot/chatwoot", + "sha": "359c4d4ce72e3873710c010d2b00323cc9b06f80", + "files_sha256": { + "Gemfile": "8e850a219d4673653eeba21f045399f4dd336692caff2c69568397613739681e", + "Gemfile.lock": "c8bc2c87255f2e1852bded2d22bb1df6c2bc96622a8006b982f5b68b8b7ac7ba", + "LICENSE": "602d38a808315f221a5e72e2e90e40cb9300f09aa4b317a6a8f1a0c7a3d2175d" + }, + "direct_dependencies": 152, + "locked_gem_names": 381, + "remotes": [ + "https://rubygems.org/" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/diaspora/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/diaspora/Gemfile new file mode 100644 index 0000000..9c53727 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/diaspora/Gemfile @@ -0,0 +1,277 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +gem "rails", "6.1.7.10" + +# needed for actionmailer, can be removed when upgrading to rails 7 +gem "net-imap", require: false +gem "net-pop", require: false +gem "net-smtp", require: false + +# concurrent-ruby >= 1.3.5 has dropped their internal dependency on Logger, +# which causes a crash with rails 6. Therefore, we have to pin that to 1.3.4 +# until we upgrade to rails 7 +gem "concurrent-ruby", "1.3.4" + +# Legacy Rails features, remove me! +# responders (class level) +gem "responders", "3.1.1" + +# Appserver + +gem "puma", "7.2.0", require: false + +# Federation + +gem "diaspora_federation-json_schema", "1.2.0" +gem "diaspora_federation-rails", "1.2.0" + +# API and JSON + +gem "acts_as_api", "1.0.1" +gem "json", "2.19.3" +gem "json-schema", "6.2.0" +gem "yajl-ruby", "1.4.3" + +# Authentication + +gem "devise", "4.9.4" +gem "devise_lastseenable", "0.0.6" +gem "devise-two-factor", "4.1.0" +gem "rqrcode", "3.2.0" + +# Captcha + +gem "simple_captcha2", "0.5.0", require: "simple_captcha" + +# Background processing + +gem "sidekiq", "7.3.10" + +# Scheduled processing + +gem "sidekiq-cron", "2.3.1" + +# Compression + +gem "terser", "1.2.7" + +# Configuration + +gem "configurate", "0.6.0" +gem "toml-rb", "4.1.0" + +# Cross-origin resource sharing + +gem "rack-cors", "2.0.2", require: "rack/cors" + +# CSS + +gem "autoprefixer-rails", "10.4.21.0" +gem "bootstrap-sass", "3.4.1" +gem "bootstrap-switch-rails", "3.3.3" # 3.3.4 and 3.3.5 is broken, see https://github.com/Bttstrp/bootstrap-switch/issues/691 +gem "sassc-rails", "2.1.2" +gem "sprockets-rails", "3.5.2" + +# Database + +group :mysql, optional: true do + gem "mysql2", "0.5.7" +end +group :postgresql, optional: true do + gem "pg", "1.6.3" +end + +gem "activerecord-import", "2.2.0" + +# File uploading + +gem "carrierwave", "3.1.2" +gem "fog-aws", "3.33.1" +gem "mini_magick", "4.13.2" + +# GUID generation +gem "uuid", "2.3.9" + +# JavaScript + +gem "babel-transpiler", "0.7.0" +gem "handlebars_assets", "0.23.9" +gem "jquery-rails", "4.6.1" +gem "jquery-ui-rails", "8.0.0" +gem "js_image_paths", "0.2.0" +gem "js-routes", "2.3.6" + +# Localization + +gem "http_accept_language", "2.1.1" +gem "rails-i18n", "7.0.10" + +# Map +gem "leaflet-rails", "1.9.5" + +# Parsing + +gem "nokogiri", "1.19.2" +gem "open_graph_reader", "0.9.1" # also update User-Agent in features/support/webmock.rb and open_graph_cache_spec.rb +gem "redcarpet", "3.6.1" +gem "ruby-oembed", "0.18.1" +gem "twitter-text", "3.1.0" + +# Rate limitting + +gem "rack-attack", "6.8.0" + +# RTL support + +gem "string-direction", "1.2.2" + +# Security Headers + +gem "secure_headers", "7.2.0" + +# Services + +gem "omniauth", "2.1.4" +gem "omniauth-rails_csrf_protection", "2.0.1" + +# OpenID Connect +gem "openid_connect", "2.3.1" + +# Serializers + +gem "active_model_serializers", "0.9.13" + +# Tags + +gem "acts-as-taggable-on", "10.0.0" + +# URIs and HTTP + +gem "addressable", "2.9.0", require: "addressable/uri" +gem "faraday", "2.14.1" +gem "faraday-cookie_jar", "0.0.8" +gem "faraday-follow_redirects", "0.5.0" +gem "faraday-typhoeus", "2.0.0", require: false +gem "ssrf_filter", "1.5.0" +gem "typhoeus", "1.6.0" + +# Views + +gem "gon", "6.6.0" +gem "hamlit", "4.0.0" +gem "mobile-fu", "1.4.0" +gem "rails-timeago", "2.20.0" +gem "will_paginate", "4.0.1" + +# Using 1.19 makes Gon dump the entire user object into Gon, including the +# private key and ends up breaking the entire layout. 1.18 works in that regard, +# but the gon tagFollowings preloads are broken, which breaks following tags. +# So let's just pin it to a version that's known to work until we have time to +# debug further. +gem "multi_json", "1.15.0" + +# Logging + +gem "logging-rails", "0.6.0", require: "logging/rails" +gem "syslog", "0.4.0" + + +# Reading and writing zip files + +gem "rubyzip", "2.4.1", require: "zip" + +# Prevent occasions where minitest is not bundled in +# packaged versions of ruby. See following issues/prs: +# https://github.com/gitlabhq/gitlabhq/issues/3826 +# https://github.com/gitlabhq/gitlabhq/pull/3852 +# https://github.com/discourse/discourse/pull/238 +gem "minitest", "6.0.3" + +gem "versionist", "2.0.1" + +group :production do # we don"t install these on travis to speed up test runs + # Analytics + + gem "rack-piwik", "0.3.0", require: "rack/piwik" + + # Process management + + gem "foreman", "0.90.0", require: false + + # Redirects + + gem "rack-rewrite", "1.5.1", require: false + + # Third party asset hosting + + gem "asset_sync", "2.19.3", require: false +end + +group :development do + # Linters + gem "haml_lint", "0.72.0", require: false + gem "pronto", "0.11.5", require: false + gem "pronto-eslint", "0.11.1", require: false + gem "pronto-haml", "0.11.1", require: false + gem "pronto-rubocop", "0.11.6", require: false + gem "pronto-scss", "0.11.0", require: false + gem "rubocop", "1.86.0", require: false + gem "rubocop-rails", "2.34.3", require: false + + gem "faraday-retry", require: false # used by pronto/octokit + + # Debugging + gem "pry" + gem "pry-byebug" + + # test coverage + gem "simplecov", "0.22.0", require: false + + gem "turbo_dev_assets", "0.0.2" + + gem "listen", "3.10.0" +end + +group :test do + # RSpec (unit tests, some integration tests) + + gem "fixture_builder", "0.5.2" + gem "fuubar", "2.5.1" + gem "rspec-json_expectations", "~> 2.1" + + # Cucumber (integration tests) + + gem "capybara", "3.40.0" + gem "cuprite", "0.17" + gem "database_cleaner-active_record", "2.2.2" + + gem "cucumber-api-steps", "0.14", require: false + + # General helpers + + gem "factory_bot_rails", "6.5.1" + gem "shoulda-matchers", "6.5.0" + gem "timecop", "0.9.10" + gem "webmock", "3.26.2", require: false + + gem "diaspora_federation-test", "1.2.0" +end + +group :development, :test do + # RSpec (unit tests, some integration tests) + gem "rspec-rails", "6.1.5" + + # Cucumber (integration tests) + gem "cucumber-rails", "4.0.1", require: false + + # Jasmine (client side application tests (JS)) + gem "chrome_remote", "0.3.0" + gem "jasmine", "3.10.0" + gem "jasmine-jquery-rails", "2.0.3" + gem "sinon-rails", "1.15.0" + + # For `assigns` in controller specs + gem "rails-controller-testing", "1.0.5" +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/diaspora/LICENSE b/crates/rb-gemfile/tests/fixtures/real-world/diaspora/LICENSE new file mode 100644 index 0000000..a871fcf --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/diaspora/LICENSE @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/crates/rb-gemfile/tests/fixtures/real-world/diaspora/source.json b/crates/rb-gemfile/tests/fixtures/real-world/diaspora/source.json new file mode 100644 index 0000000..da83ad9 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/diaspora/source.json @@ -0,0 +1,14 @@ +{ + "repo": "diaspora/diaspora", + "sha": "f96527862dc1ba2e5b95c4196efb0d1f0cc4b6e5", + "files_sha256": { + "Gemfile": "6d84dbb1f9860b30f84779b466392ca72ff8c504769a23f00d388794ffd0de2e", + "Gemfile.lock": "9b88c8df726b2f8c15a7d919c80ba9e9d4319193664935c511403e78fb306d3e", + "LICENSE": "432d251a78dbc966e6add13f9f3b40a53daca222208e50cb514cfc77e7d85af6" + }, + "direct_dependencies": 113, + "locked_gem_names": 284, + "remotes": [ + "https://rubygems.org/" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/errbit/.ruby-version b/crates/rb-gemfile/tests/fixtures/real-world/errbit/.ruby-version new file mode 100644 index 0000000..43beb40 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/errbit/.ruby-version @@ -0,0 +1 @@ +4.0.7 diff --git a/crates/rb-gemfile/tests/fixtures/real-world/errbit/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/errbit/Gemfile new file mode 100644 index 0000000..31b1e1b --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/errbit/Gemfile @@ -0,0 +1,114 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +ruby file: ".ruby-version" + +gem "rails", "8.1.3.1" + +gem "sprockets-rails" +gem "stimulus-rails" +gem "importmap-rails" +gem "turbo-rails" +gem "activemodel-serializers-xml" +gem "actionmailer_inline_css" +gem "decent_exposure" +gem "devise" +gem "devise-i18n" +gem "pundit" +gem "dotenv" +gem "draper" +gem "errbit_plugin" +gem "errbit_github_plugin" +gem "font-awesome-rails" +gem "htmlentities" +gem "kaminari" +gem "kaminari-mongoid" +gem "kaminari-i18n" +gem "mongoid" +gem "faraday-retry" +gem "octokit" +gem "omniauth" +gem "omniauth-rails_csrf_protection" +gem "omniauth-github" +gem "omniauth-google-oauth2" +gem "rails_autolink" +gem "rails-i18n" +gem "inline_svg" +gem "useragent" +gem "nokogiri" +gem "uri" +gem "rack-timeout" +gem "puma" +gem "ostruct" +gem "securerandom" +gem "airbrake", require: false + +# Notification services +# --------------------------------------- +gem "campy" +# Hoiio (SMS) +gem "hoi" +# Pushover.net (iOS/Android Push notifications) +gem "pushover2" +# Hubot +gem "httparty" + +gem "icalendar" +gem "json" + +gem "pry-rails" + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", ">= 1.4.4", require: false + +# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] +gem "thruster", require: false + +group :development, :test do + gem "rubydex", require: false + gem "rubocop", require: false + gem "rubocop-rails", require: false + gem "rubocop-rake", require: false + gem "rubocop-capybara", require: false + gem "rubocop-rspec", require: false + gem "rubocop-rspec_rails", require: false + gem "rubocop-performance", require: false + gem "rubocop-disable_syntax", require: false + gem "rubocop-thread_safety", require: false + gem "rubocop-factory_bot", require: false + gem "rubocop-erb", require: false + gem "standard", "1.56.0", require: false + gem "faker" + gem "factory_bot_rails" + gem "brakeman", require: false + gem "herb", require: false +end + +group :development do + gem "listen", "~> 3.10" + gem "bundler-audit", require: false +end + +group :test do + gem "rails-controller-testing" + gem "rspec-rails", require: false + gem "rspec-rebound", require: false + gem "rspec-activemodel-mocks" + gem "mongoid-rspec" + gem "pundit-matchers" + gem "capybara" + gem "selenium-webdriver" + gem "launchy" + gem "email_spec" + gem "simplecov", require: false + gem "super_diff" + gem "webmock" + gem "vcr" +end + +gem "jquery-rails" +gem "pjax_rails" +gem "underscore-rails" + +eval_gemfile "./UserGemfile" diff --git a/crates/rb-gemfile/tests/fixtures/real-world/errbit/LICENSE b/crates/rb-gemfile/tests/fixtures/real-world/errbit/LICENSE new file mode 100644 index 0000000..356b875 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/errbit/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2010-2026 Errbit Team + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/errbit/UserGemfile b/crates/rb-gemfile/tests/fixtures/real-world/errbit/UserGemfile new file mode 100644 index 0000000..8e9b8f9 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/errbit/UserGemfile @@ -0,0 +1 @@ +# frozen_string_literal: true diff --git a/crates/rb-gemfile/tests/fixtures/real-world/errbit/source.json b/crates/rb-gemfile/tests/fixtures/real-world/errbit/source.json new file mode 100644 index 0000000..d0d908e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/errbit/source.json @@ -0,0 +1,16 @@ +{ + "repo": "errbit/errbit", + "sha": "eec7c6e99b4145112698446e1958107850241ca6", + "files_sha256": { + ".ruby-version": "f6b1c526e9020e3805af187b44a8f2d22b9e21fe9f02a50cbaa8368f8faaf189", + "Gemfile": "30f8c7fb9bd975c2245b466c671f5cfd142f2da6681407a522a469c79302d87a", + "Gemfile.lock": "c05e506d9b5892a99053fc3b79ef6200fccb490a214e6a86ad7d42e3cf89dc04", + "LICENSE": "9d9230d09511ae03e5721bea8a0d8b7559a5092113dbc81d839d890a4cdc8eb5", + "UserGemfile": "2c0982c561aaad7d568157012a2fe86979ba51542cdc4b5b8cd07d1237264cec" + }, + "direct_dependencies": 83, + "locked_gem_names": 216, + "remotes": [ + "https://rubygems.org/" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/forem/.ruby-version b/crates/rb-gemfile/tests/fixtures/real-world/forem/.ruby-version new file mode 100644 index 0000000..15a2799 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/forem/.ruby-version @@ -0,0 +1 @@ +3.3.0 diff --git a/crates/rb-gemfile/tests/fixtures/real-world/forem/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/forem/Gemfile new file mode 100644 index 0000000..bc34e6b --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/forem/Gemfile @@ -0,0 +1,189 @@ +# coding: utf-8 + +git_source(:github) { |name| "https://github.com/#{name}.git" } +source "https://rubygems.org" +ruby File.read(File.join(File.dirname(__FILE__), ".ruby-version")).strip + +group :production do + gem "hypershield", "~> 0.2.2" # Allow admins to query data via internal + gem "nakayoshi_fork", "~> 0.0.4" # solves CoW friendly problem on MRI 2.2 and later + gem "rack-host-redirect", "~> 1.3" # Lean and simple host redirection via Rack middleware +end + +gem "active_record_union", "~> 1.4" # Adds proper union and union_all methods to ActiveRecord::Relation +gem "acts-as-taggable-on", "~> 13.0" # A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts +gem "acts_as_follower", github: "forem/acts_as_follower", branch: "master" # Allow any model to follow any other model +gem "addressable", "~> 2.8" # A replacement for the URI implementation that is part of Ruby's standard library +gem "ahoy_email", "~> 2.2.0" # Email analytics for Rails +gem "ahoy_matey", "~> 5.0.2" # Tracking analytics for Rails +gem "algoliasearch-rails", "~> 2.3" # Algolia Search API Client +gem "analytics-ruby", "~> 2.5" # Segment-compatible analytics client; used by Trackers::CustomerioCdp pointed at cdp.customer.io +gem "ancestry", "~> 4.2" # Ancestry allows the records of a ActiveRecord model to be organized in a tree structure +gem "blazer", "~> 2.6" # Allows admins to query data +gem "bootsnap", ">= 1.1.0", require: false # Boot large ruby/rails apps faster +gem "carrierwave", "~> 3.1" # Upload files in your Ruby applications, map them to a range of ORMs, store them on different backends +gem "carrierwave-bombshelter", "~> 0.2" # Protect your carrierwave from image bombs +gem "cgi", "~> 0.3.6" # Support for the Common Gateway Interface protocol. +gem "cld3", "~> 3.5" # Ruby interface for Compact Language Detector v3 +gem "cloudinary", "~> 1.23" # Client library for easily using the Cloudinary service +gem "counter_culture", "~> 3.2" # counter_culture provides turbo-charged counter caches that are kept up-to-date +gem "countries", "~> 5.5" # All sorts of useful information about every country packaged as pretty little country objects. It includes data from ISO 3166 +gem "customerio", "~> 6.1" # Customer.io App API client; transactional email delivery (see DeliveryMethods::CustomerIo) +gem "ddtrace", "~> 1.16.2" # ddtrace is Datadog’s tracing client for Ruby. +gem "devise", "~> 4.8" # Flexible authentication solution for Rails +gem "devise_invitable", "~> 2.0.6" # Allows invitations to be sent for joining +gem "dogstatsd-ruby", "~> 5.6" # A client for DogStatsD, an extension of the StatsD metric server for Datadog +gem "email_validator", "~> 2.2" # Email validator for Rails and ActiveModel +gem "emoji_regex", "~> 3.2" # A pair of Ruby regular expressions for matching Unicode Emoji symbols +gem "fastimage", "~> 2.2" # FastImage finds the size or type of an image given its uri by fetching as little as needed. +gem "fastly", "~> 3.0" # Client library for the Fastly acceleration system +gem "feedjira", "~> 3.2" # A feed fetching and parsing library +gem "field_test", "~> 0.5" # A/B testing +gem "flipper", "~> 1.4" # Feature flipping / flags for Ruby +gem "flipper-active_record", "~> 1.4" # Store Flipper flags in ActiveRecord +gem "flipper-active_support_cache_store", "~> 1.4" # Cache feature flags for a short time +gem "flipper-ui", "~> 1.4" # UI for the Flipper gem +gem "fog-aws", "~> 3.14" # 'fog' gem to support Amazon Web Services +gem "front_matter_parser", "~> 1.0" # Parse a front matter from syntactically correct strings or files +gem "gemoji", "~> 4.1.0" # Character information and metadata for standard and custom emoji +gem "gibbon", "~> 3.4" # API wrapper for MailChimp's API +gem "hairtrigger", "~> 1.3.1" # HairTrigger lets you create and manage database triggers in a concise, db-agnostic, Rails-y way. +gem "honeybadger", "~> 5.1" # Used for tracking application errors +gem "honeycomb-beeline", "~> 2.11.0" # Monitoring and Observability gem +gem "html_truncator", "~> 0.4" # Truncate an HTML string properly +gem "httparty", "~> 0.20" # Makes http fun! Also, makes consuming restful web services dead easy +gem "httpclient", "~> 2.9.0" # Gives something like the functionality of libwww-perl (LWP) in Ruby +gem "i18n-js", "~> 3.9.2" # Helps with internationalization in Rails. +gem "imgproxy", "~> 2.1" # A gem that easily generates imgproxy URLs for your images +gem "inline_svg", "~> 1.8" # Embed SVG documents in your Rails views and style them with CSS +gem "jbuilder", "~> 2.11" # Create JSON structures via a Builder-style DSL +gem "js-routes", "~> 2.2" # Brings Rails named routes to javascript +gem "jsbundling-rails", "~> 1.2" # A Rails plugin to bundle JavaScript +gem "jsonapi-serializer", "~> 2.2" # Serializer for Ruby objects +gem "jwt", "2.10.3" # Verify delegated access tokens +gem "kaminari", "~> 1.2" # A Scope and Engine based, clean, powerful, customizable and sophisticated paginator +gem "katex", "~> 0.9.0" # This rubygem enables you to render TeX math to HTML using KaTeX. It uses ExecJS under the hood +gem "liquid", "~> 5.4" # A secure, non-evaling end user template engine with aesthetic markup +gem "metainspector", "~> 5.12" # To get and parse website metadata for Open Graph rich objects +gem "mini_magick", "~> 4.13" # Manipulate images with minimal use of memory via ImageMagick / GraphicsMagick +gem "nokogiri", "~> 1.18" # HTML, XML, SAX, and Reader parser +gem "octokit", "~> 5.2" # Simple wrapper for the GitHub API +gem "oj", "~> 3.13" # JSON parser and object serializer +gem "omniauth", "~> 2.1" # A generalized Rack framework for multiple-provider authentication +gem "omniauth-apple", "~> 1.0" # OmniAuth strategy for Sign In with Apple +gem "omniauth-facebook", "~> 9.0" # OmniAuth strategy for Facebook +gem "omniauth-github", "~> 2.0" # OmniAuth strategy for GitHub +gem "omniauth-google-oauth2", "~> 1.0" # OmniAuth strategy for Google OAuth2 +gem "omniauth-mlh", "~> 4.2" +gem "omniauth-rails_csrf_protection", "~> 2.0" # Provides CSRF protection on OmniAuth request endpoint on Rails application. +gem "omniauth-twitter", "~> 1.4" # OmniAuth strategy for Twitter +gem "parallel", "~> 1.22" # Run any kind of code in parallel processes +gem "pg", "~> 1.6" # Pg is the Ruby interface to the PostgreSQL RDBMS +gem "pg_query", ">= 6.0.0" # Allows PGHero to analyze queries +gem "pg_search", "~> 2.3.6" # PgSearch builds Active Record named scopes that take advantage of PostgreSQL's full text search +gem "pghero", "~> 3.6" # Dashboard for Postgres +gem "puma", "~> 5.6.4" # Puma is a simple, fast, threaded, and highly concurrent HTTP 1.1 server +gem "pundit", "~> 2.2" # Object oriented authorization for Rails applications +gem "public_suffix", "~> 6.0" # Domain name parser based on the Public Suffix List +gem "rack-attack", "~> 6.8.0" # Used to throttle requests to prevent brute force attacks +gem "rack-cors", "~> 1.1" # Middleware that will make Rack-based apps CORS compatible +gem "rack-timeout", "~> 0.7.0" # Rack middleware which aborts requests that have been running for longer than a specified timeout +gem "rails", "8.0.5" # Ruby on Rails +gem "ransack", "~> 4.2" # Searching and sorting +gem "recaptcha", "~> 5.10", require: "recaptcha/rails" # Helpers for the reCAPTCHA API +gem "redcarpet", "~> 3.5" # A fast, safe and extensible Markdown to (X)HTML parser + +gem "redis", "~> 4.7.1" # Redis ruby client +gem "redis-actionpack", "~> 5.5.0" # Redis session store for ActionPack. Used for storing the Rails session in Redis. +gem "rpush", "~> 9.2" # Push Notification library for Rails +gem "rpush-redis", "~> 1.2" # Redis module capability for rpush library + +gem "request_store", "~> 1.7" # RequestStore gives you per-request global storage +gem "reverse_markdown", "~> 2.1" # Map simple html back into markdown +gem "rolify", "~> 6.0" # Very simple Roles library +gem "rouge", "~> 4.2" # A pure-ruby code highlighter +gem "rss", "~> 0.2.9" # Ruby's standard library for RSS +gem "rubyzip", "~> 2.4" # Rubyzip is a ruby library for reading and writing zip files +gem "s3_direct_upload", "~> 0.1" # Direct Upload to Amazon S3 +gem "sidekiq", "~> 6.5.3" # Sidekiq is used to process background jobs with the help of Redis +gem "sidekiq-throttled", "~> 1.5" # Concurrency control for Sidekiq +gem "sidekiq-cron", "~> 1.7" # Allows execution of scheduled cron jobs as specific times +gem "sidekiq-unique-jobs", "~> 7.1.27" # Ensures that Sidekiq jobs are unique when enqueued +gem "slack-notifier", "~> 2.4" # A slim ruby wrapper for posting to slack webhooks +gem "sprockets-rails", "~> 3.4" # Sprockets Rails integration +gem "sterile", "~> 1.0" # Transliterate Unicode and Latin1 text to 7-bit ASCII for URLs +gem "stripe", "~> 5.55" # Ruby library for the Stripe API +gem "strong_migrations", "~> 1.7" # Catch unsafe migrations +gem "terser", "~> 1.1" # Terser is a Ruby wrapper for the terser JavaScript parser and minifier +gem "twitter", "~> 7.0" # A Ruby interface to the Twitter API +gem "validate_url", "~> 1.0" # Library for validating urls in Rails +gem "vault", "~> 0.20" # Used to store secrets +gem "warning", "~> 1.3" # Adds custom processing for warnings, including the ability to ignore specific warning messages +gem "wcag_color_contrast", "~> 0.1" # Detect contrast of colors to determine readability and a11y. + +group :development do + gem "better_errors", "~> 2.9" # Provides a better error page for Rails and other Rack apps + + gem "brakeman", "~> 5.2", require: false # Brakeman detects security vulnerabilities in Ruby on Rails applications via static analysis + gem "bundler-audit", "~> 0.9" # bundler-audit provides patch-level verification for Bundled apps + gem "derailed_benchmarks", "~> 2.1", require: false # A series of things you can use to benchmark a Rails or Ruby app + gem "easy_translate", "~> 0.5.1" # Google translate tie-in to be used with i18n tasks + gem "erb_lint", "~> 0.3", require: false # ERB Linter tool + gem "guard", "~> 2.18", require: false # Guard is a command line tool to easily handle events on file system modifications + gem "guard-rspec", "~> 4.7", require: false # Guard::Rspec includes a DSL for running tests on change + gem "i18n-tasks", "~> 1.0.11" # Helpers to find and manage missing and unused translations + gem "listen", "~> 3.7", require: false # Helps 'listen' to file system modifications events (also used by other gems like guard) + gem "memory_profiler", "~> 1.0", require: false # Memory profiling routines for Ruby 2.3+ + gem "solargraph", "~> 0.45", require: false # For LSP support (such as symbol renaming, documentation lookup) + gem "solargraph-rails", "~> 0.3.1", require: false # For LSP support with Rails + gem "web-console", "~> 4.2" # Rails Console on the Browser + gem "yard", "~> 0.9" # Documentation format + gem "yard-activerecord", "~> 0.0" # Yard extension for ActiveRecord + gem "yard-activesupport-concern", "~> 0.0" # Yard extension for ActiveRecord::Concern + gem "kamal", "~> 2.3" +end + +group :development, :test do + gem "amazing_print", "~> 2.0" # Great Ruby debugging companion: pretty print Ruby objects to visualize their structure + gem "bullet", "~> 8.0" # help to kill N+1 queries and unused eager loading + gem "capybara", "~> 3.37.1" # Capybara is an integration testing tool for rack based web applications + gem "cypress-rails", "~> 0.5" # For end to end tests (E2E) + gem "debug", ">= 1.0.0" # Provide a debug with step capabilities + gem "dotenv-rails", "~> 3.2" # For loading ENV variables locally + gem "faker", "~> 3.5" # A library for generating fake data such as names, addresses, and phone numbers + gem "knapsack_pro", "~> 5.1" # Help parallelize Ruby spec builds + gem "pry", "~> 0.14" # An IRB alternative and runtime developer console + gem "pry-rails", "~> 0.3" # Use Pry as your rails console + gem "rspec-rails", "~> 6.0", ">= 6.0.3" # rspec-rails is a testing framework for Rails 3+ + gem "rspec_junit_formatter", "~> 0.6" # RSpec formatter for JUnit XML output + gem "rswag-specs", "~> 2.11" # RSwag - Swagger-based DSL for rspec & accompanying rake task for generating Swagger files + gem "rubocop", "~> 1.42", require: false # Automatic Ruby code style checking tool + gem "rubocop-performance", "~> 1.14", require: false # A collection of RuboCop cops to check for performance optimizations in Ruby code + gem "rubocop-rails", "~> 2.15", require: false # Automatic Rails code style checking tool + gem "rubocop-rspec", "~> 2.12", require: false # Code style checking for RSpec files + gem "sassc-rails", "~> 2.1.2" # Integrate SassC-Ruby into Rails +end + +group :test do + gem "cuprite", "~> 0.13" # Capybara driver for Chrome + gem "exifr", ">= 1.3.6" # EXIF Reader is a module to read EXIF from JPEG and TIFF images + gem "factory_bot_rails", "~> 6.2" # factory_bot is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies + gem "fakeredis", "~> 0.8.0" # Fake (In-memory) driver for redis-rb. Useful for testing environment and machines without Redis. + gem "launchy", "~> 2.5" # Launchy is helper class for launching cross-platform applications in a fire and forget manner. + gem "pundit-matchers", "~> 1.7" # A set of RSpec matchers for testing Pundit authorisation policies + gem "rails-controller-testing", "~> 1.0" # Testing helpers for Rails controllers + gem "rspec-retry", "~> 0.6" # retry intermittently failing rspec examples + gem "ruby-prof", "~> 1.4", require: false # ruby-prof is a fast code profiler for Ruby + gem "shoulda-matchers", "~> 5.3", require: false # Simple one-liner tests for common Rails functionality + gem "simplecov", "~> 0.21.2", require: false # Code coverage with a powerful configuration library and automatic merging of coverage across test suites + gem "stackprof", "~> 0.2", require: false, platforms: :ruby # stackprof is a fast sampling profiler for ruby code, with cpu, wallclock and object allocation samplers + gem "stripe-ruby-mock", "3.1.0.rc3", require: "stripe_mock" # A drop-in library to test stripe without hitting their servers + gem "test-prof", "~> 1.0" # Ruby Tests Profiling Toolbox + gem "timecop", "~> 0.9" # A gem providing "time travel" and "time freezing" capabilities, making it dead simple to test time-dependent code + gem "vcr", "~> 6.3" # Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests + gem "webmock", "~> 3.17", require: false # WebMock allows stubbing HTTP requests and setting expectations on HTTP requests + gem "with_model", "~> 2.1.7" # Dynamically build a model within an RSpec context + gem "zonebie", "~> 0.6.1" # Runs your tests in a random timezone +end + +gem "neighbor", "~> 0.5.2" diff --git a/crates/rb-gemfile/tests/fixtures/real-world/forem/LICENSE.md b/crates/rb-gemfile/tests/fixtures/real-world/forem/LICENSE.md new file mode 100644 index 0000000..d091a92 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/forem/LICENSE.md @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/forem/source.json b/crates/rb-gemfile/tests/fixtures/real-world/forem/source.json new file mode 100644 index 0000000..4740029 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/forem/source.json @@ -0,0 +1,16 @@ +{ + "repo": "forem/forem", + "sha": "b0db42193946c988e057430cfd4b13e4b76b9e82", + "files_sha256": { + "Gemfile": "0b738c86e5fb6eaaeed24eef43526311c5f8d9e58c8e58f8737918ce03302710", + "Gemfile.lock": "2b4dd737889c14143c6fc44e28954c8777e496cb7b3fdbeb9d96d3f2c1afeef5", + "LICENSE.md": "0523190ce40c0e0c6e1deb4208926030d72fc6bbbbf99d92722a565bbe955f90", + ".ruby-version": "5eee6c0c5c6901f5e523f0a434bca4106e1ff7136deb451f982b0bb1a7b13716" + }, + "direct_dependencies": 167, + "locked_gem_names": 412, + "remotes": [ + "https://github.com/forem/acts_as_follower.git", + "https://rubygems.org/" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/foreman/Gemfile new file mode 100644 index 0000000..9724cff --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/Gemfile @@ -0,0 +1,55 @@ +# foreman plugins import this file therefore __FILE__ cannot be used +FOREMAN_GEMFILE = __FILE__ unless defined? FOREMAN_GEMFILE + +source 'https://rubygems.org' + +gem 'rails', '~> 7.0.3' +gem 'rest-client', '>= 2.0.0', '< 3', :require => 'rest_client' +gem 'audited', '~> 5.0', '!= 5.1.0' +gem 'will_paginate', '~> 3.3' +gem 'ancestry', '~> 4.0' +gem 'scoped_search', '>= 4.3.1', '< 6' +gem 'ldap_fluff', '>= 0.9.0', '< 1.0' +gem 'apipie-rails', '>= 0.8.0', '< 2' +gem 'apipie-dsl', '>= 2.6.2' +# Pin rdoc to prevent updating bundled psych (https://github.com/ruby/rdoc/commit/ebe185c8775b2afe844eb3da6fa78adaa79e29a4) +# Rails 6.0 is incompatible with Psych 4, Rails 6.1 should work +gem 'rdoc', RUBY_VERSION < '3.1' ? '< 6.4' : nil +gem 'rabl', '>= 0.15.0', '< 1' +gem 'oauth', '~> 1.0' +gem 'deep_cloneable', '>= 3', '< 4' +gem 'validates_lengths_from_database', '~> 0.5' +gem 'friendly_id', '>= 5.4.2', '< 6' +gem 'secure_headers', '>= 6.3', '< 8' +gem 'safemode', '>= 2.0', '< 3' +gem 'fast_gettext', '~> 2.1' +gem 'gettext_i18n_rails', '~> 1.8' +gem 'rails-i18n', '~> 7.0' +gem 'logging', '>= 1.8.0', '< 3.0.0' +gem 'fog-core', '~> 2.1' +gem 'net-scp' +gem 'net-ssh' +gem 'net-ldap', '>= 0.16.0' +gem 'net-ping', :require => false +gem 'activerecord-session_store', '>= 2.0.0', '< 3' +gem 'sprockets', '~> 4.0' +gem 'sprockets-rails', '~> 3.0' +gem 'responders', '~> 3.0' +gem 'roadie-rails', '~> 3.0' +gem 'deacon', '~> 1.0' +gem 'mail', '~> 2.7' +gem 'dynflow', '>= 1.6.5', '< 3.0.0' +gem 'daemons' +gem 'bcrypt', '~> 3.1' +gem 'get_process_mem' +gem 'rack-cors', '~> 1.1', require: 'rack/cors' +gem 'jwt', '>= 2.2.2', '< 3.0' +gem 'graphql', '~> 1.13.0' +gem 'graphql-batch' + +# A bundled gem since Ruby 3.0 +gem 'rss' + +Dir["#{File.dirname(FOREMAN_GEMFILE)}/bundler.d/*.rb"].each do |bundle| + instance_eval(Bundler.read_file(bundle)) +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/LICENSE b/crates/rb-gemfile/tests/fixtures/real-world/foreman/LICENSE new file mode 100644 index 0000000..7123098 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/LICENSE @@ -0,0 +1,1460 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . + +----------------------------------------------------------------------------- + +Revised BSD license + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----------------------------------------------------------------------------- + +2-clause BSD license + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those +of the authors and should not be interpreted as representing official policies, +either expressed or implied, of the author. + +----------------------------------------------------------------------------- + +MIT license + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +----------------------------------------------------------------------------- + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +----------------------------------------------------------------------------- + + MOZILLA PUBLIC LICENSE + Version 1.1 + --------------- + +1. Definitions. + + 1.0.1. "Commercial Use" means distribution or otherwise making the + Covered Code available to a third party. + + 1.1. "Contributor" means each entity that creates or contributes to + the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original + Code, prior Modifications used by a Contributor, and the Modifications + made by that particular Contributor. + + 1.3. "Covered Code" means the Original Code or Modifications or the + combination of the Original Code and Modifications, in each case + including portions thereof. + + 1.4. "Electronic Distribution Mechanism" means a mechanism generally + accepted in the software development community for the electronic + transfer of data. + + 1.5. "Executable" means Covered Code in any form other than Source + Code. + + 1.6. "Initial Developer" means the individual or entity identified + as the Initial Developer in the Source Code notice required by Exhibit + A. + + 1.7. "Larger Work" means a work which combines Covered Code or + portions thereof with code not governed by the terms of this License. + + 1.8. "License" means this document. + + 1.8.1. "Licensable" means having the right to grant, to the maximum + extent possible, whether at the time of the initial grant or + subsequently acquired, any and all of the rights conveyed herein. + + 1.9. "Modifications" means any addition to or deletion from the + substance or structure of either the Original Code or any previous + Modifications. When Covered Code is released as a series of files, a + Modification is: + A. Any addition to or deletion from the contents of a file + containing Original Code or previous Modifications. + + B. Any new file that contains any part of the Original Code or + previous Modifications. + + 1.10. "Original Code" means Source Code of computer software code + which is described in the Source Code notice required by Exhibit A as + Original Code, and which, at the time of its release under this + License is not already Covered Code governed by this License. + + 1.10.1. "Patent Claims" means any patent claim(s), now owned or + hereafter acquired, including without limitation, method, process, + and apparatus claims, in any patent Licensable by grantor. + + 1.11. "Source Code" means the preferred form of the Covered Code for + making modifications to it, including all modules it contains, plus + any associated interface definition files, scripts used to control + compilation and installation of an Executable, or source code + differential comparisons against either the Original Code or another + well known, available Covered Code of the Contributor's choice. The + Source Code can be in a compressed or archival form, provided the + appropriate decompression or de-archiving software is widely available + for no charge. + + 1.12. "You" (or "Your") means an individual or a legal entity + exercising rights under, and complying with all of the terms of, this + License or a future version of this License issued under Section 6.1. + For legal entities, "You" includes any entity which controls, is + controlled by, or is under common control with You. For purposes of + this definition, "control" means (a) the power, direct or indirect, + to cause the direction or management of such entity, whether by + contract or otherwise, or (b) ownership of more than fifty percent + (50%) of the outstanding shares or beneficial ownership of such + entity. + +2. Source Code License. + + 2.1. The Initial Developer Grant. + The Initial Developer hereby grants You a world-wide, royalty-free, + non-exclusive license, subject to third party intellectual property + claims: + (a) under intellectual property rights (other than patent or + trademark) Licensable by Initial Developer to use, reproduce, + modify, display, perform, sublicense and distribute the Original + Code (or portions thereof) with or without Modifications, and/or + as part of a Larger Work; and + + (b) under Patents Claims infringed by the making, using or + selling of Original Code, to make, have made, use, practice, + sell, and offer for sale, and/or otherwise dispose of the + Original Code (or portions thereof). + + (c) the licenses granted in this Section 2.1(a) and (b) are + effective on the date Initial Developer first distributes + Original Code under the terms of this License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is + granted: 1) for code that You delete from the Original Code; 2) + separate from the Original Code; or 3) for infringements caused + by: i) the modification of the Original Code or ii) the + combination of the Original Code with other software or devices. + + 2.2. Contributor Grant. + Subject to third party intellectual property claims, each Contributor + hereby grants You a world-wide, royalty-free, non-exclusive license + + (a) under intellectual property rights (other than patent or + trademark) Licensable by Contributor, to use, reproduce, modify, + display, perform, sublicense and distribute the Modifications + created by such Contributor (or portions thereof) either on an + unmodified basis, with other Modifications, as Covered Code + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or + selling of Modifications made by that Contributor either alone + and/or in combination with its Contributor Version (or portions + of such combination), to make, use, sell, offer for sale, have + made, and/or otherwise dispose of: 1) Modifications made by that + Contributor (or portions thereof); and 2) the combination of + Modifications made by that Contributor with its Contributor + Version (or portions of such combination). + + (c) the licenses granted in Sections 2.2(a) and 2.2(b) are + effective on the date Contributor first makes Commercial Use of + the Covered Code. + + (d) Notwithstanding Section 2.2(b) above, no patent license is + granted: 1) for any code that Contributor has deleted from the + Contributor Version; 2) separate from the Contributor Version; + 3) for infringements caused by: i) third party modifications of + Contributor Version or ii) the combination of Modifications made + by that Contributor with other software (except as part of the + Contributor Version) or other devices; or 4) under Patent Claims + infringed by Covered Code in the absence of Modifications made by + that Contributor. + +3. Distribution Obligations. + + 3.1. Application of License. + The Modifications which You create or to which You contribute are + governed by the terms of this License, including without limitation + Section 2.2. The Source Code version of Covered Code may be + distributed only under the terms of this License or a future version + of this License released under Section 6.1, and You must include a + copy of this License with every copy of the Source Code You + distribute. You may not offer or impose any terms on any Source Code + version that alters or restricts the applicable version of this + License or the recipients' rights hereunder. However, You may include + an additional document offering the additional rights described in + Section 3.5. + + 3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be + made available in Source Code form under the terms of this License + either on the same media as an Executable version or via an accepted + Electronic Distribution Mechanism to anyone to whom you made an + Executable version available; and if made available via Electronic + Distribution Mechanism, must remain available for at least twelve (12) + months after the date it initially became available, or at least six + (6) months after a subsequent version of that particular Modification + has been made available to such recipients. You are responsible for + ensuring that the Source Code version remains available even if the + Electronic Distribution Mechanism is maintained by a third party. + + 3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a + file documenting the changes You made to create that Covered Code and + the date of any change. You must include a prominent statement that + the Modification is derived, directly or indirectly, from Original + Code provided by the Initial Developer and including the name of the + Initial Developer in (a) the Source Code, and (b) in any notice in an + Executable version or related documentation in which You describe the + origin or ownership of the Covered Code. + + 3.4. Intellectual Property Matters + (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's + intellectual property rights is required to exercise the rights + granted by such Contributor under Sections 2.1 or 2.2, + Contributor must include a text file with the Source Code + distribution titled "LEGAL" which describes the claim and the + party making the claim in sufficient detail that a recipient will + know whom to contact. If Contributor obtains such knowledge after + the Modification is made available as described in Section 3.2, + Contributor shall promptly modify the LEGAL file in all copies + Contributor makes available thereafter and shall take other steps + (such as notifying appropriate mailing lists or newsgroups) + reasonably calculated to inform those who received the Covered + Code that new knowledge has been obtained. + + (b) Contributor APIs. + If Contributor's Modifications include an application programming + interface and Contributor has knowledge of patent licenses which + are reasonably necessary to implement that API, Contributor must + also include this information in the LEGAL file. + + (c) Representations. + Contributor represents that, except as disclosed pursuant to + Section 3.4(a) above, Contributor believes that Contributor's + Modifications are Contributor's original creation(s) and/or + Contributor has sufficient rights to grant the rights conveyed by + this License. + + 3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source + Code. If it is not possible to put such notice in a particular Source + Code file due to its structure, then You must include such notice in a + location (such as a relevant directory) where a user would be likely + to look for such a notice. If You created one or more Modification(s) + You may add your name as a Contributor to the notice described in + Exhibit A. You must also duplicate this License in any documentation + for the Source Code where You describe recipients' rights or ownership + rights relating to Covered Code. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Code. However, You + may do so only on Your own behalf, and not on behalf of the Initial + Developer or any Contributor. You must make it absolutely clear than + any such warranty, support, indemnity or liability obligation is + offered by You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred by the + Initial Developer or such Contributor as a result of warranty, + support, indemnity or liability terms You offer. + + 3.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the + requirements of Section 3.1-3.5 have been met for that Covered Code, + and if You include a notice stating that the Source Code version of + the Covered Code is available under the terms of this License, + including a description of how and where You have fulfilled the + obligations of Section 3.2. The notice must be conspicuously included + in any notice in an Executable version, related documentation or + collateral in which You describe recipients' rights relating to the + Covered Code. You may distribute the Executable version of Covered + Code or ownership rights under a license of Your choice, which may + contain terms different from this License, provided that You are in + compliance with the terms of this License and that the license for the + Executable version does not attempt to limit or alter the recipient's + rights in the Source Code version from the rights set forth in this + License. If You distribute the Executable version under a different + license You must make it absolutely clear that any terms which differ + from this License are offered by You alone, not by the Initial + Developer or any Contributor. You hereby agree to indemnify the + Initial Developer and every Contributor for any liability incurred by + the Initial Developer or such Contributor as a result of any such + terms You offer. + + 3.7. Larger Works. + You may create a Larger Work by combining Covered Code with other code + not governed by the terms of this License and distribute the Larger + Work as a single product. In such a case, You must make sure the + requirements of this License are fulfilled for the Covered Code. + +4. Inability to Comply Due to Statute or Regulation. + + If it is impossible for You to comply with any of the terms of this + License with respect to some or all of the Covered Code due to + statute, judicial order, or regulation then You must: (a) comply with + the terms of this License to the maximum extent possible; and (b) + describe the limitations and the code they affect. Such description + must be included in the LEGAL file described in Section 3.4 and must + be included with all distributions of the Source Code. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Application of this License. + + This License applies to code to which the Initial Developer has + attached the notice in Exhibit A and to related Covered Code. + +6. Versions of the License. + + 6.1. New Versions. + Netscape Communications Corporation ("Netscape") may publish revised + and/or new versions of the License from time to time. Each version + will be given a distinguishing version number. + + 6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the + License, You may always continue to use it under the terms of that + version. You may also choose to use such Covered Code under the terms + of any subsequent version of the License published by Netscape. No one + other than Netscape has the right to modify the terms applicable to + Covered Code created under this License. + + 6.3. Derivative Works. + If You create or use a modified version of this License (which you may + only do in order to apply it to code which is not already Covered Code + governed by this License), You must (a) rename Your license so that + the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", + "MPL", "NPL" or any confusingly similar phrase do not appear in your + license (except to note that your license differs from this License) + and (b) otherwise make it clear that Your version of the license + contains terms which differ from the Mozilla Public License and + Netscape Public License. (Filling in the name of the Initial + Developer, Original Code or Contributor in the notice described in + Exhibit A shall not of themselves be deemed to be modifications of + this License.) + +7. DISCLAIMER OF WARRANTY. + + COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, + WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF + DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. + THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE + IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, + YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE + COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER + OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +8. TERMINATION. + + 8.1. This License and the rights granted hereunder will terminate + automatically if You fail to comply with terms herein and fail to cure + such breach within 30 days of becoming aware of the breach. All + sublicenses to the Covered Code which are properly granted shall + survive any termination of this License. Provisions which, by their + nature, must remain in effect beyond the termination of this License + shall survive. + + 8.2. If You initiate litigation by asserting a patent infringement + claim (excluding declatory judgment actions) against Initial Developer + or a Contributor (the Initial Developer or Contributor against whom + You file such action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly + infringes any patent, then any and all rights granted by such + Participant to You under Sections 2.1 and/or 2.2 of this License + shall, upon 60 days notice from Participant terminate prospectively, + unless if within 60 days after receipt of notice You either: (i) + agree in writing to pay Participant a mutually agreeable reasonable + royalty for Your past and future use of Modifications made by such + Participant, or (ii) withdraw Your litigation claim with respect to + the Contributor Version against such Participant. If within 60 days + of notice, a reasonable royalty and payment arrangement are not + mutually agreed upon in writing by the parties or the litigation claim + is not withdrawn, the rights granted by Participant to You under + Sections 2.1 and/or 2.2 automatically terminate at the expiration of + the 60 day notice period specified above. + + (b) any software, hardware, or device, other than such Participant's + Contributor Version, directly or indirectly infringes any patent, then + any rights granted to You by such Participant under Sections 2.1(b) + and 2.2(b) are revoked effective as of the date You first made, used, + sold, distributed, or had made, Modifications made by that + Participant. + + 8.3. If You assert a patent infringement claim against Participant + alleging that such Participant's Contributor Version directly or + indirectly infringes any patent where such claim is resolved (such as + by license or settlement) prior to the initiation of patent + infringement litigation, then the reasonable value of the licenses + granted by such Participant under Sections 2.1 or 2.2 shall be taken + into account in determining the amount or value of any payment or + license. + + 8.4. In the event of termination under Sections 8.1 or 8.2 above, + all end user license agreements (excluding distributors and resellers) + which have been validly granted by You or any distributor hereunder + prior to termination shall survive termination. + +9. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL + DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, + OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR + ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY + CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, + WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY + RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW + PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE + EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO + THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +10. U.S. GOVERNMENT END USERS. + + The Covered Code is a "commercial item," as that term is defined in + 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer + software" and "commercial computer software documentation," as such + terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 + C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), + all U.S. Government End Users acquire Covered Code with only those + rights set forth herein. + +11. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. This License shall be governed by + California law provisions (except to the extent applicable law, if + any, provides otherwise), excluding its conflict-of-law provisions. + With respect to disputes in which at least one party is a citizen of, + or an entity chartered or registered to do business in the United + States of America, any litigation relating to this License shall be + subject to the jurisdiction of the Federal Courts of the Northern + District of California, with venue lying in Santa Clara County, + California, with the losing party responsible for costs, including + without limitation, court costs and reasonable attorneys' fees and + expenses. The application of the United Nations Convention on + Contracts for the International Sale of Goods is expressly excluded. + Any law or regulation which provides that the language of a contract + shall be construed against the drafter shall not apply to this + License. + +12. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or indirectly, + out of its utilization of rights under this License and You agree to + work with Initial Developer and Contributors to distribute such + responsibility on an equitable basis. Nothing herein is intended or + shall be deemed to constitute any admission of liability. + +13. MULTIPLE-LICENSED CODE. + + Initial Developer may designate portions of the Covered Code as + "Multiple-Licensed". "Multiple-Licensed" means that the Initial + Developer permits you to utilize portions of the Covered Code under + Your choice of the MPL or the alternative licenses, if any, specified + by the Initial Developer in the file described in Exhibit A. + +EXHIBIT A -Mozilla Public License. + + ``The contents of this file are subject to the Mozilla Public License + Version 1.1 (the "License"); you may not use this file except in + compliance with the License. You may obtain a copy of the License at + https://www.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + License for the specific language governing rights and limitations + under the License. + + The Original Code is ______________________________________. + + The Initial Developer of the Original Code is ________________________. + Portions created by ______________________ are Copyright (C) ______ + _______________________. All Rights Reserved. + + Contributor(s): ______________________________________. + + Alternatively, the contents of this file may be used under the terms + of the _____ license (the "[___] License"), in which case the + provisions of [______] License are applicable instead of those + above. If you wish to allow use of your version of this file only + under the terms of the [____] License and not to allow others to use + your version of this file under the MPL, indicate your decision by + deleting the provisions above and replace them with the notice and + other provisions required by the [___] License. If you do not delete + the provisions above, a recipient may use your version of this file + under either the MPL or the [___] License." + + [NOTE: The text of this Exhibit A may differ slightly from the text of + the notices in the Source Code files of the Original Code. You should + use the text of this Exhibit A rather than the text found in the + Original Code Source Code for Your Modifications.] + + +----------------------------------------------------------------------------- + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/assets.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/assets.rb new file mode 100644 index 0000000..7c8b01a --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/assets.rb @@ -0,0 +1,8 @@ +group :assets do + gem 'patternfly-sass', '~> 3.59.4' + gem 'gettext_i18n_rails_js', '~> 1.4' + gem 'po_to_json', '~> 1.1' + gem 'execjs', '>= 1.4.0', '< 3.0' + gem 'terser', '~> 1.1' + gem 'sass-rails', '~> 6.0' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/console.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/console.rb new file mode 100644 index 0000000..da3a7b0 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/console.rb @@ -0,0 +1,4 @@ +group :console do + gem 'wirb', '>= 1.0', '< 3.0' + gem 'amazing_print', '~> 1.1', :require => 'ap' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/development.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/development.rb new file mode 100644 index 0000000..436a043 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/development.rb @@ -0,0 +1,28 @@ +group :development do + gem 'maruku', '~> 0.7' + + # for generating i18n files + gem 'gettext', '>= 3.2.1', '< 4.0.0', :require => false + + # for generating foreign key migrations + gem 'immigrant', '~> 0.1' + + # debugging and REPL tools + gem 'byebug' + gem 'pry' + gem 'pry-rails' + gem 'pry-doc' + gem 'pry-stack_explorer' + gem 'pry-remote' # will not work when running via foreman + + gem 'rainbow', '>= 2.2.1' + + gem 'bullet', '>= 6.1.0' + gem "parallel_tests" + # TODO: https://projects.theforeman.org/issues/38419 + gem 'spring', '4.2.1' + gem 'benchmark-ips', '>= 2.8.2' + gem 'foreman' + gem('bootsnap', :require => false) + gem 'graphiql-rails', '~> 1.7' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/dynflow_sidekiq.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/dynflow_sidekiq.rb new file mode 100644 index 0000000..20dd20b --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/dynflow_sidekiq.rb @@ -0,0 +1,4 @@ +group :dynflow_sidekiq do + gem 'sidekiq', '~> 6.5' + gem 'gitlab-sidekiq-fetcher', require: false +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/ec2.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/ec2.rb new file mode 100644 index 0000000..105abc5 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/ec2.rb @@ -0,0 +1,3 @@ +group :ec2 do + gem 'fog-aws', '>= 3.6.2', '< 4' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/facter.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/facter.rb new file mode 100644 index 0000000..0c18837 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/facter.rb @@ -0,0 +1,3 @@ +group :facter do + gem 'facter' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/journald.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/journald.rb new file mode 100644 index 0000000..dc525d8 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/journald.rb @@ -0,0 +1,4 @@ +# disable to avoid journald native gem in development setup +group :journald do + gem 'logging-journald', '~> 2.0', :require => false +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/jsonp.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/jsonp.rb new file mode 100644 index 0000000..2eb4a7d --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/jsonp.rb @@ -0,0 +1,3 @@ +group :jsonp do + gem 'rack-jsonp', :require => 'rack/jsonp' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/libvirt.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/libvirt.rb new file mode 100644 index 0000000..e688384 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/libvirt.rb @@ -0,0 +1,4 @@ +group :libvirt do + gem 'fog-libvirt', '>= 0.14.0' + gem 'ruby-libvirt', '~> 0.5', :require => 'libvirt' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/nulldb.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/nulldb.rb new file mode 100644 index 0000000..3184a94 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/nulldb.rb @@ -0,0 +1 @@ +gem 'activerecord-nulldb-adapter' diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openid.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openid.rb new file mode 100644 index 0000000..575de4f --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openid.rb @@ -0,0 +1,3 @@ +group :openid do + gem 'rack-openid', '~> 1.3' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openstack.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openstack.rb new file mode 100644 index 0000000..6cc59c1 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/openstack.rb @@ -0,0 +1,3 @@ +group :openstack do + gem 'fog-openstack', '>= 1.0.8', '< 2.0.0' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/postgresql.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/postgresql.rb new file mode 100644 index 0000000..01cd9c1 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/postgresql.rb @@ -0,0 +1,4 @@ +group :postgresql do + # Matches gem requirement specified in ActiveRecord connection adapter + gem 'pg', '>= 0.18', '< 2.0' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/redis.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/redis.rb new file mode 100644 index 0000000..7310938 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/redis.rb @@ -0,0 +1,3 @@ +group :redis do + gem 'redis', '~> 4.5.0' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/service.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/service.rb new file mode 100644 index 0000000..3e2b36b --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/service.rb @@ -0,0 +1 @@ +gem 'puma', '>= 8.0', '< 9', groups: [:test, :service], require: false diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/telemetry.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/telemetry.rb new file mode 100644 index 0000000..b70ff83 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/telemetry.rb @@ -0,0 +1,4 @@ +group :telemetry do + gem 'prometheus-client', '>= 1.0', '< 5' + gem 'statsd-instrument', '< 3' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/test.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/test.rb new file mode 100644 index 0000000..bf45f33 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/test.rb @@ -0,0 +1,23 @@ +group :test do + gem 'mocha', '~> 2.1' + gem 'minitest', '~> 5.1' + gem 'minitest-reporters', '~> 1.4', :require => false + gem 'minitest-retry', '~> 0.0', :require => false + gem 'minitest-spec-rails', '~> 7.1' + gem 'minitest_reporters_github', '~> 1.0', :require => false + gem 'capybara', '~> 3.33', :require => false + gem 'show_me_the_cookies', '~> 6.0', :require => false + gem 'database_cleaner', '~> 1.3', :require => false + gem 'launchy', '~> 2.4' + gem 'facterdb', '~> 1.7' + gem 'factory_bot_rails', '~> 5.0', :require => false + gem 'selenium-webdriver', :require => false + gem 'shoulda-matchers', '~> 5.0' + gem 'shoulda-context', '~> 1.2' + gem 'as_deprecation_tracker', '~> 1.6' + gem 'rails-controller-testing', '~> 1.0' + gem 'rfauxfactory', '~> 0.1', '>= 0.1.5' + gem 'robottelo_reporter', '~> 0.1' + gem 'theforeman-rubocop', '~> 0.1.2', require: false + gem 'webmock' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/vmware.rb b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/vmware.rb new file mode 100644 index 0000000..6d045e3 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/bundler.d/vmware.rb @@ -0,0 +1,3 @@ +group :vmware do + gem 'fog-vsphere', '>= 3.7.1', '< 4.0' +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/foreman/source.json b/crates/rb-gemfile/tests/fixtures/real-world/foreman/source.json new file mode 100644 index 0000000..fdc9b4e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/foreman/source.json @@ -0,0 +1,32 @@ +{ + "repo": "theforeman/foreman", + "sha": "a21273a13820103c2f569a4d5446806dfff3dae0", + "files_sha256": { + "Gemfile": "83100e5b2186bdc12c01f55e5005a574bd63e7fdb21e9044218280269d1895ea", + "LICENSE": "2535014d0a3dafa7940a2ed0ef7a7881000eebc14456ce687aa8c7cc278f06a7", + "bundler.d/assets.rb": "601e17ede96b8499b20cb399e832bb2e80e694e24a4d79cb123c5797e17f1072", + "bundler.d/console.rb": "bc29f5ed63422d2efdf3881c415fca7208c7f15d8cbacde3bdf7289686b5af41", + "bundler.d/development.rb": "a0dcbe136b4d277f51d9fad8002136178a40205dd3c3f8be551c763883bc2431", + "bundler.d/dynflow_sidekiq.rb": "49fc7c7efb7498452bb0b677df21a7cd4468d753cf0b6858c99c670f782c84df", + "bundler.d/ec2.rb": "ff54fb0c1d5c8f542984a2ac46b5f4b02076e9131da4808efc5813113de93248", + "bundler.d/facter.rb": "f004b8c5bc36e6a822a5c8d92bc5ee06e7f0aeaef7da0b32376712c9bbf020c5", + "bundler.d/journald.rb": "6d94f25eb02b7c16bf0bf6bbb0eeb585c24ae12e4d56c3cb1a61ab034659b2b4", + "bundler.d/jsonp.rb": "e98e9de9ae4eb551998b4a4ba7c3e891c7d2d5e9f3c88fb2924be8bff90681c2", + "bundler.d/libvirt.rb": "f413fb1451a0b8a073f11bd0b573d212a38f938f04aac9a964b039fbce659444", + "bundler.d/nulldb.rb": "801255245771db638843e340d5999178aaec08e072341f57eb75e70b5be3d12e", + "bundler.d/openid.rb": "ebc7f8eecf8735fcb5b9783f28c6b473e6c2da02aed78d3db95ab58811471738", + "bundler.d/openstack.rb": "f864ae613c09266d0ff4a2ac2ce8678bccdeedcd8af79ef0f7e9b423ff7ccee4", + "bundler.d/postgresql.rb": "64dc76665b4990e475fe8911a97ac1b77c394e4eb538bcf32619adbd4441977e", + "bundler.d/redis.rb": "bb658341848af85faa43c06ef53f8205832da31d1c05b18fa5c81d5eed15ef1f", + "bundler.d/service.rb": "1b0199e5b7d174769cffa7a57518a18ed0f98eae3daf23887856761d70317b52", + "bundler.d/telemetry.rb": "378c68487da292154edb9851149bf7bac83e02d2a5ac27ec18d6a189d71409b5", + "bundler.d/test.rb": "a15025cd18015f6844276e055697539d2f2e4a5f9d5084859de1741f4db63ff4", + "bundler.d/vmware.rb": "f0055800a2f426c2869eca1eb9a0442628f1d1b2190ef6c2330bdc52a54c69f6" + }, + "direct_dependencies": null, + "locked_gem_names": null, + "remotes": [ + "https://rubygems.org" + ], + "lockfile_note": "No root Gemfile.lock committed at this upstream revision." +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/lobsters/.ruby-version b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/.ruby-version new file mode 100644 index 0000000..fcdb2e1 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/.ruby-version @@ -0,0 +1 @@ +4.0.0 diff --git a/crates/rb-gemfile/tests/fixtures/real-world/lobsters/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/Gemfile new file mode 100644 index 0000000..18f12f2 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/Gemfile @@ -0,0 +1,84 @@ +source "https://rubygems.org" + +ruby file: ".ruby-version" + +gem "rails" + +# database and caching +gem "solid_cache" +gem "sqlite3", force_ruby_platform: true # compile flags in .bundle/config + +# jobs +gem "solid_queue" +gem "mission_control-jobs" + +# rails +gem "activerecord-typedstore" +gem "importmap-rails", "~> 2.0" +gem "propshaft" +gem "sentry-rails" +gem "typeid" + +# js +gem "json" + +# deployment +gem "actionpack-page_caching" +gem "puma" + +# security +gem "bcrypt" +gem "rotp" +gem "rqrcode" + +# parsing +gem "cgi" +gem "commonmarker", "~> 2.6.3" +gem "htmlentities" +gem "pdf-reader" +gem "nokogiri" +gem "parslet" + +# perf +gem "flamegraph" +gem "memory_profiler" +gem "rack-mini-profiler" +gem "stackprof" + +gem "builder" # for rss +gem "faker" # for factory data and /cabinet +gem "oauth" # for linking accounts +gem "mail" # for parsing incoming mail +gem "sitemap_generator" # for better search engine indexing +gem "svg-graph", require: "SVG/Graph/TimeSeries" # for charting, note workaround in lib/time_series.rb +gem "rexml" # no release for https://github.com/lumean/svg-graph2/pull/48/files +gem "rack-attack" # rate-limiting +gem "lograge" # for JSON logging +gem "silencer" # to disable default logging in prod + +# image +gem "ruby-vips" + +group :test, :development do + gem "active_record_doctor" + gem "benchmark-perf" + gem "brakeman" + gem "debug" + gem "capybara" + gem "crass" + gem "database_cleaner" + gem "database_consistency" + gem "factory_bot_rails" + gem "foreman" + gem "letter_opener" + gem "listen" + gem "ostruct" # for foreman on Ruby 4, probably safe to delete after 2026-06 + gem "rspec-rails" + gem "simplecov", require: false + gem "standard" + gem "standard-performance" + gem "standard-rails" + gem "super_diff" + gem "vcr" + gem "webmock" # used to support vcr +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/lobsters/LICENSE b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/LICENSE new file mode 100644 index 0000000..1e864e1 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012-2019 +Created by joshua stein +For full list of contributors run `git log --format='%aN <%aE>' | sort -u` + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/lobsters/source.json b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/source.json new file mode 100644 index 0000000..2b7f1fc --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/lobsters/source.json @@ -0,0 +1,15 @@ +{ + "repo": "lobsters/lobsters", + "sha": "0613f4d5dec85e4babcccbcfebe6782978875d29", + "files_sha256": { + ".ruby-version": "e1d49c569ae09b2ede16e2d83820a3809b35eb6c44c13ba9b5330598d6b8f43c", + "Gemfile": "665ccb2a58e0a90018b0e0e9dd902f20690ccb9246408503a8538cafe0135e91", + "Gemfile.lock": "9efe9531313688cd7da2cf15a03cbbf900955866e9d8a070a35b65b43b288d8a", + "LICENSE": "78ccbc4bf0878a34c891b49020e83f3501e98ac3c96146faf39f6de0cbb36752" + }, + "direct_dependencies": 58, + "locked_gem_names": 180, + "remotes": [ + "https://rubygems.org/" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/manageiq/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/manageiq/Gemfile new file mode 100644 index 0000000..5c250e6 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/manageiq/Gemfile @@ -0,0 +1,328 @@ +ruby ">= 3.3.1", "< 3.5.0" +warn "Ruby versions >= 3.4.0 are untested!" if RUBY_VERSION >= "3.4.0" +source 'https://rubygems.org' + +plugin "bundler-inject", "~> 2.0" +require File.join(Bundler::Plugin.index.load_paths("bundler-inject")[0], "bundler-inject") rescue nil + +# +# VMDB specific gems +# +gem "manageiq-gems-pending", ">0", :git => "https://github.com/ManageIQ/manageiq-gems-pending.git", :branch => "master" + +# when using this Gemfile inside a providers Gemfile, the dependency for the provider is already declared +def manageiq_plugin(plugin_name) + unless dependencies.detect { |d| d.name == plugin_name } + gem plugin_name, :git => "https://github.com/ManageIQ/#{plugin_name}", :branch => "master" + end +end + +manageiq_plugin "manageiq-schema" + +# Unmodified gems +gem "activerecord-session_store", "~>2.0" +gem "activerecord-virtual_attributes", "~>8.0.0" +gem "acts_as_tree", "~>2.7" # acts_as_tree needs to be required so that it loads before ancestry +gem "ancestry", "~>4.1.0", :require => false +gem "awesome_spawn", "~>1.6", :require => false +gem "aws-sdk-s3", "~>1.0", :require => false # For FileDepotS3 +gem "bcrypt", "~> 3.1.10", :require => false +gem "bootsnap", ">= 1.8.1", :require => false # for psych 3.3.2+ / 4 unsafe_load +gem "bundler", ">= 2.5.20", "< 5", :require => false +gem "byebug", :require => false +gem "config", "~>5.1", :require => false +gem "connection_pool", "~>2.5", :require => false # For Dalli +gem "dalli", "~>3.2.3", :require => false +gem "default_value_for", "~>4.0" +gem "docker-api", "~>1.33.6", :require => false +gem "drb", "~>2.2", :require => false +gem "fast_gettext", "~>3.1" +gem "ffi", "< 1.17.0", :require => false # Locked down due to build issue assertion failure on 1.17.3 +gem "gettext_i18n_rails", "~>1.11" +gem "gettext_i18n_rails_js", "~>1.3.0" +gem "hamlit", "~>2.11.0" +gem "inifile", "~>3.0", :require => false +gem "inventory_refresh", "~>2.3", :require => false +gem "kubeclient", "~>4.0", :require => false # For scaling pods at runtime +gem "linux_admin", ">=3.0", "<5", :require => false +gem "listen", "~>3.2", :require => false +gem "manageiq-api-client", "~>0.7", :require => false +gem "manageiq-loggers", "~>2.0", :require => false +gem "manageiq-messaging", "~>2.1", :require => false +gem "manageiq-password", "~>1.0", :require => false +gem "manageiq-postgres_ha_admin", "~>3.5", :require => false +gem "manageiq-ssh-util", "~>0.2.0", :require => false +gem "memoist", "~>0.16.0", :require => false +gem "money", "~>6.13.5", :require => false +gem "more_core_extensions" # min version should be set in manageiq-gems-pending, not here +gem "net-ping", "~>1.7.4", :require => false +gem "openscap", "~>0.4.8", :require => false +gem "optimist", "~>3.0", :require => false +gem "pg", ">=1.6.3.1", :require => false, :source => "https://rubygems.manageiq.org" +gem "pg-dsn_parser", "~>0.1.1", :require => false +gem "prism", ">=0.25.0", :require => false # Used by DescendantLoader +gem "psych", ">=3.1", :require => false # 3.1 safe_load changed positional to kwargs like aliases: true: https://github.com/ruby/psych/commit/4d4439d6d0adfcbd211ea295779315f1baa7dadd +gem "query_relation", "~>0.2.0", :require => false +gem "rack", ">=2.2.23", :require => false +gem "rack-attack", "~>6.8.0", :require => false +gem "rails", "~>8.0.5", ">=8.0.5.1" +gem "rails-i18n", "~>8.0.2" +gem "rake", ">=12.3.3", :require => false +gem "rest-client", "~>2.1.0", :require => false +gem "ruby_parser", :require => false # Required for i18n string extraction, and DescentdantLoader (via prism) +gem "ruby-progressbar", "~>1.13.0", :require => false +gem "rugged", "~>1.9", :require => false +gem "ruport", "~>1.8.0" +gem "snmp", "~>1.3.0", :require => false +gem "sprockets", "~>3.7.2", :require => false +gem "sync", "~>0.5", :require => false +gem "terminal", :require => false +gem "wim_parser", "~>1.0", :require => false + +# gems to resolve security issues +gem "cgi", "~> 0.5" +gem "erb", ">= 6.0.4" # CVE-2026-41316: https://github.com/advisories/GHSA-q339-8rmv-2mhv; Dependency of irb -> rdoc -> erb +gem "faraday", "~> 2.14", ">= 2.14.2" # CVE-2026-33637: https://github.com/advisories/GHSA-5rv5-xj5j-3484 +gem "uri", "~> 0.13.3" # CVE-2025-61594: https://www.ruby-lang.org/en/news/2025/10/07/uri-cve-2025-61594/ + # Avoid URI 1.0.0 for now due to: https://github.com/ruby/uri/issues/125 +gem "thor", ">= 1.4.0" # CVE-2025-54314: https://github.com/advisories/GHSA-mqcp-p2hv-vw6x + +# Custom gem that replaces mime-types in order to redirect mime-types calls to mini_mime +# Source is located at https://github.com/ManageIQ/mime-types-redirector +gem "mime-types", "~>3.0", :require => false, :source => "https://rubygems.manageiq.org" + +# Modified gems (forked on Github) +gem "handsoap", "=0.2.5.5", :require => false, :source => "https://rubygems.manageiq.org" # for manageiq-gems-pending only + +# In 1.9.3: Time.parse uses british version dd/mm/yyyy instead of american version mm/dd/yyyy +# american_date fixes this to be compatible with 1.8.7 until all callers can be converted to the 1.9.3 format prior to parsing. +# See miq_expression_spec Date/Time Support examples. +# https://github.com/jeremyevans/ruby-american_date +gem "american_date" + +# Make sure to tag your new bundler group with the manageiq_default group in addition to your specific bundler group name. +# This default is used to automatically require all of our gems in processes that don't specify which bundler groups they want. +# +### providers +group :amazon, :manageiq_default do + manageiq_plugin "manageiq-providers-amazon" + gem "amazon_ssa_support", :require => false, :git => "https://github.com/ManageIQ/amazon_ssa_support.git", :branch => "master" # Temporary dependency to be moved to manageiq-providers-amazon when officially release +end + +group :ansible_tower, :manageiq_default do + manageiq_plugin "manageiq-providers-ansible_tower" +end + +group :autosde, :manageiq_default do + manageiq_plugin "manageiq-providers-autosde" +end + +group :awx, :manageiq_default do + manageiq_plugin "manageiq-providers-awx" +end + +group :azure, :manageiq_default do + manageiq_plugin "manageiq-providers-azure" +end + +group :azure_stack, :manageiq_default do + manageiq_plugin "manageiq-providers-azure_stack" + gem "azure_mgmt_compute", "~> 0.22.0.1", :require => false, :source => "https://rubygems.manageiq.org" + gem "azure_mgmt_monitor", "~> 0.19.0.1", :require => false, :source => "https://rubygems.manageiq.org" + gem "azure_mgmt_network", "~> 0.26.1.1", :require => false, :source => "https://rubygems.manageiq.org" + gem "azure_mgmt_resources", "~> 0.18.2.1", :require => false, :source => "https://rubygems.manageiq.org" + gem "ms_rest", "~> 0.7.6.1", :require => false, :source => "https://rubygems.manageiq.org" + gem "ms_rest_azure", "~> 0.12.0.1", :require => false, :source => "https://rubygems.manageiq.org" +end + +group :cisco_intersight, :manageiq_default do + manageiq_plugin "manageiq-providers-cisco_intersight" +end + +group :embedded_terraform, :manageiq_default do + manageiq_plugin "manageiq-providers-embedded_terraform" +end + +group :foreman, :manageiq_default do + manageiq_plugin "manageiq-providers-foreman" +end + +group :google, :manageiq_default do + manageiq_plugin "manageiq-providers-google" +end + +group :ibm_cic, :manageiq_default do + manageiq_plugin "manageiq-providers-ibm_cic" +end + +group :ibm_cloud, :manageiq_default do + manageiq_plugin "manageiq-providers-ibm_cloud" +end + +group :ibm_power_hmc, :manageiq_default do + manageiq_plugin "manageiq-providers-ibm_power_hmc" +end + +group :ibm_power_vc, :manageiq_default do + manageiq_plugin "manageiq-providers-ibm_power_vc" +end + +group :ibm_terraform, :manageiq_default do + manageiq_plugin "manageiq-providers-ibm_terraform" +end + +group :kubernetes, :openshift, :manageiq_default do + manageiq_plugin "manageiq-providers-kubernetes" +end + +group :kubevirt, :manageiq_default do + manageiq_plugin "manageiq-providers-kubevirt" +end + +group :lenovo, :manageiq_default do + manageiq_plugin "manageiq-providers-lenovo" +end + +group :nsxt, :manageiq_default do + manageiq_plugin "manageiq-providers-nsxt" +end + +group :nutanix, :manageiq_default do + manageiq_plugin "manageiq-providers-nutanix" +end + +group :oracle_cloud, :manageiq_default do + manageiq_plugin "manageiq-providers-oracle_cloud" +end + +group :proxmox, :manageiq_default do + manageiq_plugin "manageiq-providers-proxmox" +end + +group :redfish, :manageiq_default do + manageiq_plugin "manageiq-providers-redfish" +end + +group :red_hat_virtualization, :manageiq_default do + manageiq_plugin "manageiq-providers-red_hat_virtualization" +end + +group :scvmm, :manageiq_default do + manageiq_plugin "manageiq-providers-scvmm" +end + +group :terraform_enterprise, :manageiq_default do + manageiq_plugin "manageiq-providers-terraform_enterprise" +end + +group :qpid_proton, :optional => true do + gem "qpid_proton", "~>0.37.0", :require => false +end + +group :systemd, :optional => true do + gem "dbus-systemd", "~>1.1.0", :require => false + gem "sd_notify", "~>0.1.0", :require => false + gem "systemd-journal", "~>1.4.2", :require => false +end + +group :openshift, :manageiq_default do + manageiq_plugin "manageiq-providers-openshift" +end + +group :openstack, :manageiq_default do + manageiq_plugin "manageiq-providers-openstack" +end + +group :ovirt, :manageiq_default do + manageiq_plugin "manageiq-providers-ovirt" +end + +group :vmware, :manageiq_default do + manageiq_plugin "manageiq-providers-vmware" +end + +group :workflows, :manageiq_default do + manageiq_plugin "manageiq-providers-workflows" +end + +### end of provider bundler groups + +group :automate, :seed, :manageiq_default do + manageiq_plugin "manageiq-automation_engine" +end + +group :replication, :manageiq_default do + gem "pg-logical_replication", "~>1.2", :require => false +end + +group :rest_api, :manageiq_default do + manageiq_plugin "manageiq-api" +end + +group :scheduler, :manageiq_default do + gem "rufus-scheduler", ">=3.9.2" # CVE-2024-43380 + gem "et-orbi", ">= 1.3" # indirect of rufus-scheduler +end + +group :seed, :manageiq_default do + manageiq_plugin "manageiq-content" +end + +group :smartstate, :manageiq_default do + gem "manageiq-smartstate", "~>0.13", :require => false +end + +group :consumption, :manageiq_default do + manageiq_plugin "manageiq-consumption" +end + +group :ui_dependencies do # Added to Bundler.require in config/application.rb + manageiq_plugin "manageiq-decorators" + manageiq_plugin "manageiq-ui-classic" + # Modified gems (forked on Github) + gem "jquery-rjs", "=0.1.1.5", :source => "https://rubygems.manageiq.org" +end + +group :web_server, :manageiq_default do + gem "puma", "~>8.0", ">=8.0.2" + gem "ruby-dbus" # For external auth + gem "secure_headers", "~>7.3" +end + +group :web_socket, :manageiq_default do + gem "surro-gate", "~>1.0.6", :require => false + gem "websocket-driver", "~>0.8", ">=0.8.2", :require => false +end + +group :appliance, :optional => true do + gem "manageiq-appliance_console", "~>12.0", :require => false +end + +### Development and test gems are excluded from appliance and container builds to reduce size and license issues +group :development do + gem "foreman" + gem "manageiq-style", "~>1.6", ">=1.6.1", :require => false + gem "PoParser" + gem "yard", ">= 0.9.36" +end + +group :test do + gem "brakeman", "~>8.0", :require => false + gem "bundler-audit", :require => false + gem "db-query-matchers", "~>0.15.0" + gem "factory_bot", "~>6.5", :require => false + gem "simplecov", ">=0.21.2", :require => false + gem "timecop", "~>0.9", "!= 0.9.7", :require => false + gem "vcr", "~>6.1", :require => false + gem "webmock", "~>3.7", :require => false +end + +group :development, :test do + gem "cypress-on-rails", "~>1.20.0", :require => false # Dependency is needed in the rails app. It's required in ui-classic engine.rb. + gem "database_cleaner", "~>2.1", :require => false # Used by cypress-on-rails. + gem "factory_bot_rails", "~>6.5.1", :require => false # Used by cypress-on-rails. + + gem "parallel_tests", "~>5.6", :require => false + gem "routes_lazy_routes" + gem "rspec-rails", "~>7.0" +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/manageiq/LICENSE.txt b/crates/rb-gemfile/tests/fixtures/real-world/manageiq/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/manageiq/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/manageiq/source.json b/crates/rb-gemfile/tests/fixtures/real-world/manageiq/source.json new file mode 100644 index 0000000..1d79f8f --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/manageiq/source.json @@ -0,0 +1,55 @@ +{ + "repo": "ManageIQ/manageiq", + "sha": "15281f91e1c11ca7f26fef4998f77cb74a5fb6d4", + "files_sha256": { + "Gemfile": "eaad776f15dc7d21fc44d78fce1ded9957b3fdc0df16a1cc37ebdff531e59953", + "LICENSE.txt": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" + }, + "direct_dependencies": null, + "locked_gem_names": null, + "remotes": [ + "https://rubygems.org", + "https://rubygems.manageiq.org", + "https://github.com/ManageIQ/amazon_ssa_support", + "https://github.com/ManageIQ/manageiq-api", + "https://github.com/ManageIQ/manageiq-automation_engine", + "https://github.com/ManageIQ/manageiq-consumption", + "https://github.com/ManageIQ/manageiq-content", + "https://github.com/ManageIQ/manageiq-decorators", + "https://github.com/ManageIQ/manageiq-gems-pending", + "https://github.com/ManageIQ/manageiq-providers-amazon", + "https://github.com/ManageIQ/manageiq-providers-ansible_tower", + "https://github.com/ManageIQ/manageiq-providers-autosde", + "https://github.com/ManageIQ/manageiq-providers-awx", + "https://github.com/ManageIQ/manageiq-providers-azure", + "https://github.com/ManageIQ/manageiq-providers-azure_stack", + "https://github.com/ManageIQ/manageiq-providers-cisco_intersight", + "https://github.com/ManageIQ/manageiq-providers-embedded_terraform", + "https://github.com/ManageIQ/manageiq-providers-foreman", + "https://github.com/ManageIQ/manageiq-providers-google", + "https://github.com/ManageIQ/manageiq-providers-ibm_cic", + "https://github.com/ManageIQ/manageiq-providers-ibm_cloud", + "https://github.com/ManageIQ/manageiq-providers-ibm_power_hmc", + "https://github.com/ManageIQ/manageiq-providers-ibm_power_vc", + "https://github.com/ManageIQ/manageiq-providers-ibm_terraform", + "https://github.com/ManageIQ/manageiq-providers-kubernetes", + "https://github.com/ManageIQ/manageiq-providers-kubevirt", + "https://github.com/ManageIQ/manageiq-providers-lenovo", + "https://github.com/ManageIQ/manageiq-providers-nsxt", + "https://github.com/ManageIQ/manageiq-providers-nutanix", + "https://github.com/ManageIQ/manageiq-providers-openshift", + "https://github.com/ManageIQ/manageiq-providers-openstack", + "https://github.com/ManageIQ/manageiq-providers-oracle_cloud", + "https://github.com/ManageIQ/manageiq-providers-ovirt", + "https://github.com/ManageIQ/manageiq-providers-proxmox", + "https://github.com/ManageIQ/manageiq-providers-red_hat_virtualization", + "https://github.com/ManageIQ/manageiq-providers-redfish", + "https://github.com/ManageIQ/manageiq-providers-scvmm", + "https://github.com/ManageIQ/manageiq-providers-terraform_enterprise", + "https://github.com/ManageIQ/manageiq-providers-vmware", + "https://github.com/ManageIQ/manageiq-providers-workflows", + "https://github.com/ManageIQ/manageiq-schema", + "https://github.com/ManageIQ/manageiq-ui-classic" + ], + "lockfile_note": "No root Gemfile.lock committed at this upstream revision." +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/mastodon/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/mastodon/Gemfile new file mode 100644 index 0000000..f839e40 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/mastodon/Gemfile @@ -0,0 +1,235 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' +ruby '>= 3.3.0', '< 4.1.0' + +gem 'propshaft' +gem 'puma' +gem 'rails', '~> 8.1.0' +gem 'thor', '~> 1.2' + +gem 'dotenv' +gem 'haml-rails', '~>3.0' +gem 'pg', '~> 1.5' +gem 'pghero' + +gem 'aws-sdk-core', require: false +gem 'aws-sdk-s3', '~> 1.123', require: false +gem 'blurhash', '~> 0.1' +gem 'fog-core', '<= 2.6.0' +gem 'fog-openstack', '~> 1.0', require: false +gem 'jd-paperclip-azure', '~> 3.0', require: false +gem 'kt-paperclip', '~> 8.0' +gem 'ruby-vips', '~> 2.2', require: false + +gem 'active_model_serializers', '~> 0.10' +gem 'addressable', '~> 2.8' +gem 'bootsnap', require: false +gem 'browser' +gem 'charlock_holmes', '~> 0.7.7' +gem 'chewy' +gem 'devise' +gem 'devise-two-factor' + +group :pam_authentication, optional: true do + gem 'devise_pam_authenticatable2', '~> 9.2' +end + +gem 'net-ldap', '~> 0.18' + +gem 'omniauth', '~> 2.0' +gem 'omniauth-cas', '~> 3.0.0.beta.1' +gem 'omniauth_openid_connect', '~> 0.8.0' +gem 'omniauth-rails_csrf_protection', '~> 2.0' +gem 'omniauth-saml', '~> 2.0' + +gem 'color_diff', '~> 0.1' +gem 'csv', '~> 3.2' +gem 'discard', '~> 2.0' +gem 'doorkeeper', '~> 5.6' +gem 'faraday-httpclient' +gem 'fast_blank', '~> 1.0' +gem 'fastimage' +gem 'hiredis-client' +gem 'htmlentities', '~> 4.3' +gem 'http', '~> 5.3.0' +gem 'http_accept_language', '~> 2.1' +gem 'httplog', '~> 1.8.0', require: false +gem 'i18n' +gem 'idn-ruby', require: 'idn' +gem 'inline_svg' +gem 'ipaddr', '~> 1.2' +gem 'irb', '~> 1.8' +gem 'kaminari', '~> 1.2' +gem 'link_header', '~> 0.0' +gem 'linzer', '~> 0.8.0' +gem 'mario-redis-lock', '~> 1.2', require: 'redis_lock' +gem 'mime-types', '~> 3.7.0', require: 'mime/types/columnar' +gem 'mutex_m' +gem 'nokogiri', '~> 1.15' +gem 'ox', '~> 2.14' +gem 'parslet' +gem 'premailer-rails' +gem 'public_suffix', '~> 7.0' +gem 'pundit', '~> 2.3' +gem 'rack-attack', '~> 6.6' +gem 'rack-cors', require: 'rack/cors' +gem 'rack-proxy', require: 'rack/proxy' +gem 'rails-i18n', '~> 8.0' +gem 'redcarpet', '~> 3.6' +gem 'redis', '~> 5' +gem 'rqrcode', '~> 3.0' +gem 'ruby-progressbar', '~> 1.13' +gem 'sanitize', '~> 7.0' +gem 'scenic', '~> 1.7' +gem 'sidekiq', '< 9' +gem 'sidekiq-bulk', '~> 0.2.0' +gem 'sidekiq-scheduler', '~> 6.0' +gem 'sidekiq-unique-jobs', '> 8' +gem 'simple_form', '~> 5.2' +gem 'simple-navigation', '~> 4.4' +gem 'stoplight' +gem 'strong_migrations' +gem 'tty-prompt', '~> 0.23', require: false +gem 'twitter-text', '~> 3.1.0' +gem 'tzinfo-data', '~> 1.2023' +gem 'webauthn', '~> 3.0' +gem 'webpush', github: 'mastodon/webpush', ref: '9631ac63045cfabddacc69fc06e919b4c13eb913' + +gem 'json' +gem 'json-canonicalization', '~> 1.0' +gem 'json-ld' +gem 'json-ld-preloaded', '~> 3.2' +gem 'rdf-normalize', '~> 0.5' + +gem 'prometheus_exporter', '~> 2.2', require: false + +gem 'opentelemetry-api', '~> 1.11.0' + +group :opentelemetry do + gem 'opentelemetry-exporter-otlp', '~> 0.36.0', require: false + gem 'opentelemetry-instrumentation-active_job', '~> 0.13.0', require: false + gem 'opentelemetry-instrumentation-active_model_serializers', '~> 0.25.0', require: false + gem 'opentelemetry-instrumentation-concurrent_ruby', '~> 0.25.0', require: false + gem 'opentelemetry-instrumentation-excon', '~> 0.29.0', require: false + gem 'opentelemetry-instrumentation-faraday', '~> 0.33.0', require: false + gem 'opentelemetry-instrumentation-http', '~> 0.30.0', require: false + gem 'opentelemetry-instrumentation-http_client', '~> 0.29.0', require: false + gem 'opentelemetry-instrumentation-net_http', '~> 0.29.0', require: false + gem 'opentelemetry-instrumentation-pg', '~> 0.37.0', require: false + gem 'opentelemetry-instrumentation-rack', '~> 0.31.0', require: false + gem 'opentelemetry-instrumentation-rails', '~> 0.42.0', require: false + gem 'opentelemetry-instrumentation-redis', '~> 0.29.0', require: false + gem 'opentelemetry-instrumentation-sidekiq', '~> 0.29.0', require: false + gem 'opentelemetry-sdk', '~> 1.4', require: false +end + +group :test do + # Enable usage of all available CPUs/cores during spec runs + gem 'flatware-rspec' + + # Adds RSpec Error/Warning annotations to GitHub PRs on the Files tab + gem 'rspec-github', '~> 3.0', require: false + + # Extra RSpec extension methods and helpers for sidekiq + gem 'rspec-sidekiq', '~> 5.0' + + # Browser integration testing + gem 'capybara', '~> 3.39' + gem 'capybara-playwright-driver' + gem 'playwright-ruby-client', require: false + + # Used to reset the database between system tests + gem 'database_cleaner-active_record' + + # Used to mock environment variables + gem 'climate_control' + + # Validate schemas in specs + gem 'json-schema', '~> 6.0' + + # Test harness fo rack components + gem 'rack-test', '~> 2.1' + + gem 'shoulda-matchers' + + # Coverage formatter for RSpec + gem 'simplecov', require: false + gem 'simplecov-lcov', '~> 0.8', require: false + + # Stub web requests for specs + gem 'webmock', '~> 3.18' + + # Websocket driver for testing integration between rails/sidekiq and streaming + gem 'websocket-driver', '~> 0.8', require: false +end + +group :development do + # Code linting CLI and plugins + gem 'rubocop', require: false + gem 'rubocop-capybara', require: false + gem 'rubocop-i18n', require: false + gem 'rubocop-performance', require: false + gem 'rubocop-rails', require: false + gem 'rubocop-rspec', require: false + gem 'rubocop-rspec_rails', require: false + + # Annotates modules with schema + gem 'annotaterb', '~> 4.13', require: false + + # Enhanced error message pages for development + gem 'better_errors', '~> 2.9' + gem 'binding_of_caller' + + # Preview mail in the browser + gem 'letter_opener', '~> 1.8' + gem 'letter_opener_web', '~> 3.0' + + # Security analysis CLI tools + gem 'brakeman', '~> 8.0', require: false + gem 'bundler-audit', '~> 0.9', require: false + + # Linter CLI for HAML files + gem 'haml_lint', require: false + + # Validate missing i18n keys + gem 'i18n-tasks', '~> 1.0', require: false +end + +group :development, :test do + # Interactive Debugging tools + gem 'debug', '~> 1.8', require: false + + # Generate fake data values + gem 'faker', '~> 3.2' + + # Generate factory objects + gem 'fabrication' + + # Profiling tools + gem 'memory_profiler', require: false + gem 'ruby-prof', require: false + gem 'stackprof', require: false + gem 'test-prof', require: false + + # RSpec runner for rails + gem 'rspec-rails', '~> 8.0' +end + +group :production do + gem 'lograge', '~> 0.12' +end + +gem 'cocoon', '~> 1.2' +gem 'concurrent-ruby', require: false +gem 'connection_pool', require: false +gem 'xorcist', '~> 1.1' + +gem 'net-http', '~> 0.9.0' +gem 'rubyzip', '~> 3.0' + +gem 'hcaptcha', '~> 7.1' + +gem 'mail', '~> 2.8' + +gem 'base58', '~> 0.2.3' diff --git a/crates/rb-gemfile/tests/fixtures/real-world/mastodon/LICENSE b/crates/rb-gemfile/tests/fixtures/real-world/mastodon/LICENSE new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/mastodon/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/mastodon/source.json b/crates/rb-gemfile/tests/fixtures/real-world/mastodon/source.json new file mode 100644 index 0000000..2dce0a6 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/mastodon/source.json @@ -0,0 +1,15 @@ +{ + "repo": "mastodon/mastodon", + "sha": "0d413257191e343a313c5e74c203bd9a87a1bf2d", + "files_sha256": { + "Gemfile": "6e4094c8499e2b4c29508d6d76b14f4c6005336ed1627111052e01b6582cadb7", + "Gemfile.lock": "095c9b068c9f80d4481e553c4c733738fbdcf65392fcc2142c812f2030d06d74", + "LICENSE": "57c8ff33c9c0cfc3ef00e650a1cc910d7ee479a8bc509f6c9209a7c2a11399d6" + }, + "direct_dependencies": 154, + "locked_gem_names": 345, + "remotes": [ + "https://github.com/mastodon/webpush.git", + "https://rubygems.org/" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/postal/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/postal/Gemfile new file mode 100644 index 0000000..4d3c0de --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/postal/Gemfile @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +source "https://rubygems.org" +gem "abbrev" +gem "authie" +gem "autoprefixer-rails" +gem "bcrypt" +gem "chronic" +gem "domain_name" +gem "dotenv" +gem "dynamic_form" +gem "execjs", "~> 2.7", "< 2.8" +gem "gelf" +gem "haml" +gem "hashie" +gem "highline", require: false +gem "jwt" +gem "kaminari" +gem "klogger-logger" +gem "konfig-config", "~> 3.0" +gem "logger" +gem "mail" +gem "mutex_m" +gem "mysql2" +gem "nifty-utils" +gem "nilify_blanks" +gem "nio4r" +gem "ostruct" +gem "prometheus-client" +gem "puma" +gem "rackup" +gem "rails", "= 7.1.6" +gem "resolv" +gem "secure_headers" +gem "sentry-rails" +gem "turbolinks", "~> 5" +gem "webrick" + +group :oidc do + # These are gems which are needed for OpenID connect. They are only required by the application + # when OIDC is enabled in the Postal configuration. + gem "omniauth_openid_connect" + gem "omniauth-rails_csrf_protection" +end + +group :development, :assets do + gem "coffee-rails", "~> 5.0" + gem "jquery-rails" + gem "sass-rails" + gem "uglifier", ">= 1.3.0" +end + +group :development do + gem "annotate" + gem "rubocop" + gem "rubocop-rails" +end + +group :test do + gem "database_cleaner-active_record" + gem "factory_bot_rails" + gem "rspec" + gem "rspec-rails" + gem "shoulda-matchers" + gem "timecop" + gem "webmock" +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/postal/source.json b/crates/rb-gemfile/tests/fixtures/real-world/postal/source.json new file mode 100644 index 0000000..7a71f28 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/postal/source.json @@ -0,0 +1,14 @@ +{ + "repo": "postalserver/postal", + "sha": "ced77a3860c23779889aec8dacd2642f20d10cea", + "files_sha256": { + "Gemfile": "dc1ae39e1d2279a95e0e331ffc164a01ba0dd739e48757cfc0d21fc5752dd5c2", + "Gemfile.lock": "da9a25a9214c4cff93cbfaf4254b225c65a48a963377d43f9bdb65044a0f297b" + }, + "direct_dependencies": 50, + "locked_gem_names": 162, + "remotes": [ + "https://rubygems.org/" + ], + "license_note": "No LICENSE or COPYING file found in the upstream tree at this revision." +} diff --git a/crates/rb-gemfile/tests/fixtures/real-world/zammad/Gemfile b/crates/rb-gemfile/tests/fixtures/real-world/zammad/Gemfile new file mode 100644 index 0000000..ecaddee --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/zammad/Gemfile @@ -0,0 +1,293 @@ +# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/ + +source 'https://rubygems.org' + +# core - base +ruby '3.4.9' +gem 'rails', '~> 8.1.0' +gem 'rake' + +# core - rails additions +gem 'activerecord-import' +gem 'activerecord-session_store' +gem 'bootsnap', require: false +gem 'json' +gem 'parallel' + +# core - application servers +gem 'puma', group: :puma + +# core - supported ORMs +gem 'pg', '~> 1.5', '>= 1.5.4', group: :postgres + +# core - asynchrous task execution +gem 'benchmark' # undeclared delayed_job dependency +gem 'daemons' +gem 'delayed_job', git: 'https://github.com/zammad-deps/delayed_job', branch: 'threadsafe' +gem 'delayed_job_active_record', git: 'https://github.com/zammad-deps/delayed_job_active_record', branch: 'update-limit-143' + +# core - command line interface +gem 'thor' + +# core - websocket +gem 'em-websocket' +gem 'eventmachine' +gem 'hiredis-client' +# Action Cable's Redis pubsub adapter declares `gem 'redis', '>= 4', '< 6'`, so +# activating redis 6 breaks every subscription broadcast at runtime. +# Rails main already reimplemented the adapter on top of redis-client, but that +# is not part of any 8.0.x release yet, so keep redis below 6 until we upgrade. +# See https://github.com/rails/rails/blob/v8.0.5.1/actioncable/lib/action_cable/subscription_adapter/redis.rb#L5 +gem 'redis', '< 6' + +# core - password security +gem 'argon2' + +# core - state machine +gem 'aasm' + +# core - authorization +gem 'pundit' + +# core - graphql handling +gem 'graphql' +gem 'graphql-batch', require: 'graphql/batch' +gem 'graphql-fragment_cache' + +# core - image processing +gem 'rszr' + +# core - use same timezone data on any host +gem 'tzinfo-data' + +# performance - Memcached +gem 'dalli', require: false + +# Vite is required by the web server +gem 'vite_rails' + +# asset handling - config.assets for pipeline +gem 'sprockets-rails' + +# Only load gems for asset compilation if they are needed to avoid +# having unneeded runtime dependencies like NodeJS. +group :assets do + # asset handling - javascript execution for e.g. linux + gem 'execjs', require: false + + # asset handling - coffee-script + gem 'coffee-rails', require: false + + # asset handling - frontend templating + gem 'eco', require: false + + # asset handling - SASS + # We cannot use sassc-rails, as it can lead to crashes on modern platforms like CentOS 9. + # See https://jcmaciel.com/apple-silicon-ruby-on-rails-crash-segfault-sassc/ + # https://github.com/sass/sassc-ruby/issues/197 + # Use dartsass-rails which uses Dart Sass (no sassc dependency). + gem 'dartsass-rails', require: false + + # asset handling - pipeline + gem 'sprockets', '~> 4', require: false + gem 'terser', require: false + + gem 'autoprefixer-rails', require: false +end + +# authentication - provider +gem 'doorkeeper' +gem 'oauth2' + +# authentication - two factor +gem 'rotp', require: false +gem 'webauthn', require: false + +# authentication - third party +gem 'omniauth-rails_csrf_protection' + +# authentication - third party providers +gem 'omniauth-facebook' +gem 'omniauth-github' +gem 'omniauth-gitlab' +gem 'omniauth-google-oauth2' +gem 'omniauth-linkedin-oauth2' +gem 'omniauth-microsoft-office365' +gem 'omniauth_openid_connect' +gem 'omniauth-saml' +gem 'omniauth-twitter' +gem 'omniauth-weibo-oauth2' + +# Rate limiting +gem 'rack-attack' + +# channels +gem 'koala' +gem 'telegram-bot-ruby' +gem 'whatsapp_sdk' + +# channels - email additions +gem 'email_address' +gem 'htmlentities' +gem 'mail' +gem 'mime-types' +gem 'rchardet', '>= 1.8.0' + +# networking libraries were removed from stdlib in ruby 3.1.. +gem 'net-http', require: false +gem 'net-imap', require: false +gem 'net-pop', require: false +gem 'net-smtp', require: false + +# convert from punycode ACE strings to unicode UTF-8 strings and visa versa +gem 'simpleidn' + +# feature - business hours +gem 'biz' + +# feature - signature diffing +gem 'diffy' + +# feature - excel output +gem 'write_xlsx', require: false + +# feature - csv import/export +gem 'csv', require: false + +# feature - device logging +gem 'browser' + +# feature - iCal export +gem 'icalendar' +gem 'icalendar-recurrence' + +# feature - phone number formatting +gem 'telephone_number' + +# feature - SMS +gem 'messagebird-rest' +gem 'twilio-ruby', require: false + +# feature - ordering +gem 'acts_as_list' + +# integrations +gem 'clearbit', require: false +gem 'net-ldap' +gem 'zendesk_api', require: false + +# integrations - exchange +gem 'autodiscover', git: 'https://github.com/zammad-deps/autodiscover', require: false +gem 'viewpoint', require: false + +# integrations - S/MIME +gem 'openssl' + +# Translation sync +gem 'byk', require: false +gem 'PoParser', require: false + +# Simple storage +gem 'aws-sdk-s3', require: false + +# Debugging and profiling +gem 'pry-rails' +gem 'pry-remote' +gem 'pry-rescue' +gem 'pry-stack_explorer' +gem 'pry-theme' + +# monitoring / system report +gem 'macaddr' + +# watch file changes (also relevant for graphql generation in context of CDs) +gem 'listen' + +# language detection +gem 'cld' + +# CLDR wrapper for i18n and l10n +gem 'twitter_cldr' + +# AI integration +gem 'elasticsearch', '8.11.2', require: false + +# Gems used only for develop/test and not required +# in production environments by default. +group :development, :test do + + # test frameworks + gem 'rspec-rails' + gem 'rspec-retry' + gem 'shoulda-matchers' + + # for testing Pundit authorisation policies in RSpec + gem 'pundit-matchers' + + # UI tests w/ Selenium + gem 'capybara' + gem 'selenium-webdriver' + + # Playwright pilot (throwaway evaluation). playwright-ruby-client is pulled in + # by the driver; it is declared here so Renovate sees it and can keep it in + # lockstep with the playwright npm package. + gem 'capybara-playwright-driver' + gem 'playwright-ruby-client' + + # code QA + gem 'brakeman', require: false + gem 'overcommit', require: false + gem 'rubocop', require: false + gem 'rubocop-capybara', require: false + gem 'rubocop-factory_bot', require: false + gem 'rubocop-faker', require: false + gem 'rubocop-graphql', require: false + gem 'rubocop-inflector', require: false + gem 'rubocop-performance', require: false + gem 'rubocop-rails', require: false + gem 'rubocop-rake', require: false + gem 'rubocop-rspec', require: false + gem 'rubocop-rspec_rails', require: false + + # generate random test data + gem 'factory_bot_rails' + gem 'faker' + + # mock http calls + gem 'webmock' + + # record and replay TCP/HTTP transactions + gem 'tcr', require: false + gem 'vcr', require: false + + # handle deprecations in core and addons + gem 'deprecation_toolkit' + + # image comparison in tests + gem 'chunky_png' + + # Slack helper for testing + gem 'slack-ruby-client', require: false + + # Self-signed localhost certificates for puma / capybara. + gem 'localhost' + + # Keycloak admin tool for setting up SAML auth tests + gem 'ruby-keycloak-admin' + + # Debugging and profiling + gem 'pry-doc', require: false # This gem is very large, so don't include it in production. + + # editor support - language server + # Listed here so that the Ruby LSP uses the project bundle directly instead of + # generating and maintaining its own custom bundle in .ruby-lsp/. + gem 'debug', require: false, platforms: :mri + gem 'ruby-lsp', require: false + gem 'ruby-lsp-rails', require: false + gem 'ruby-lsp-rspec', require: false +end + +# To permanently extend Zammad with additional gems, you can specify them in Gemfile.local. +Dir['Gemfile.local*'].each do |file| + eval_gemfile file +end diff --git a/crates/rb-gemfile/tests/fixtures/real-world/zammad/LICENSE b/crates/rb-gemfile/tests/fixtures/real-world/zammad/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/zammad/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/crates/rb-gemfile/tests/fixtures/real-world/zammad/source.json b/crates/rb-gemfile/tests/fixtures/real-world/zammad/source.json new file mode 100644 index 0000000..9f0443e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/real-world/zammad/source.json @@ -0,0 +1,17 @@ +{ + "repo": "zammad/zammad", + "sha": "4166a43ae0aec358b4b8d18da0a4f75adadcdfcd", + "files_sha256": { + "Gemfile": "198dba51985355b22548913b3a02d04e5df4552bfb23f033c0114f493395b1d9", + "Gemfile.lock": "2df4fac48e33b0ceff6d182ea009b6f77ba16ee7640847dafc9baf30f8f51905", + "LICENSE": "8486a10c4393cee1c25392769ddd3b2d6c242d6ec7928e1414efff7dfb2f07ef" + }, + "direct_dependencies": 131, + "locked_gem_names": 318, + "remotes": [ + "https://github.com/zammad-deps/autodiscover", + "https://github.com/zammad-deps/delayed_job", + "https://github.com/zammad-deps/delayed_job_active_record", + "https://rubygems.org/" + ] +} diff --git a/crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/Gemfile b/crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/Gemfile new file mode 100644 index 0000000..2bd6b51 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/Gemfile @@ -0,0 +1,12 @@ +gem 'keep', '>= 2' +gem 'replace', '~> 1' +@dependencies.reject! { |dependency| dependency.name == 'replace' } +gem 'replace', '~> 3' +names = @dependencies.to_a.map(&:name) +raise 'missing declarations' unless names.sort == %w[keep replace] +spec = Bundler.load_gemspec(File.expand_path('sample.gemspec', __dir__)) +spec.runtime_dependencies.each { |dependency| gem dependency.name, *dependency.requirement.as_list } +@dependencies.reject! { |dependency| dependency.name == 'keep' } +platforms(Gem::Version.new(Bundler::VERSION) >= Gem::Version.new('2.5') ? :windows : :mingw) do + gem 'tzinfo-data' +end diff --git a/crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/sample.gemspec b/crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/sample.gemspec new file mode 100644 index 0000000..8037928 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/ruby/compatibility_helpers/sample.gemspec @@ -0,0 +1,5 @@ +Gem::Specification.new do |spec| + spec.name = 'sample' + spec.version = '1.0.0' + spec.add_runtime_dependency 'rack', '~> 3' +end diff --git a/crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/Gemfile b/crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/Gemfile new file mode 100644 index 0000000..8be17cb --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/Gemfile @@ -0,0 +1 @@ +gemspec require: false diff --git a/crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/sample.gemspec b/crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/sample.gemspec new file mode 100644 index 0000000..ac3ab0e --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/ruby/gemspec_options/sample.gemspec @@ -0,0 +1,4 @@ +Gem::Specification.new do |spec| + spec.name = 'sample' + spec.version = '1.0.0' +end diff --git a/crates/rb-gemfile/tests/fixtures/ruby/nested_sources.rb b/crates/rb-gemfile/tests/fixtures/ruby/nested_sources.rb new file mode 100644 index 0000000..a6bc4e5 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/ruby/nested_sources.rb @@ -0,0 +1,7 @@ +git 'outer', branch: 'main' do + source 'https://example.test' do + gem 'registry' + end + gem 'outer' +end +gem 'normal' diff --git a/crates/rb-gemfile/tests/fixtures/ruby/require_settings/Gemfile b/crates/rb-gemfile/tests/fixtures/ruby/require_settings/Gemfile new file mode 100644 index 0000000..da84a51 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/ruby/require_settings/Gemfile @@ -0,0 +1,3 @@ +gem 'nil-require', require: nil +gem 'false-require', require: false +gem 'default-require' diff --git a/crates/rb-gemfile/tests/fixtures/ruby/source_options/Gemfile b/crates/rb-gemfile/tests/fixtures/ruby/source_options/Gemfile new file mode 100644 index 0000000..98cda2c --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/ruby/source_options/Gemfile @@ -0,0 +1,5 @@ +source 'https://rubygems.org', cooldown: 7 +source 'https://example.test', 'cooldown' => 5 do + gem 'scoped' +end +gem 'rake' diff --git a/crates/rb-gemfile/tests/fixtures/snapshot/changing_condition_inputs_updates_exported_dependencies-1.rb b/crates/rb-gemfile/tests/fixtures/snapshot/changing_condition_inputs_updates_exported_dependencies-1.rb new file mode 100644 index 0000000..4141112 --- /dev/null +++ b/crates/rb-gemfile/tests/fixtures/snapshot/changing_condition_inputs_updates_exported_dependencies-1.rb @@ -0,0 +1,4 @@ +install_if -> { ENV['WITH_DEBUG'] == '1' } do + gem 'debug', require: false +end +gem 'rake' diff --git a/crates/rb-gemfile/tests/format.rs b/crates/rb-gemfile/tests/format.rs new file mode 100644 index 0000000..e67fda9 --- /dev/null +++ b/crates/rb-gemfile/tests/format.rs @@ -0,0 +1,260 @@ +use rb_gemfile::{Evaluator, ExportFormat, Manifest}; + +fn evaluate() -> Manifest { + let root = tempfile::tempdir().unwrap(); + std::fs::write( + root.path().join("Gemfile"), + include_str!("fixtures/format/evaluate-1.rb"), + ) + .unwrap(); + Evaluator::new(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())) + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest +} + +fn round_trip(manifest: &Manifest) { + let toml = manifest.to_toml().unwrap(); + let parsed: Manifest = toml::from_str(&toml).unwrap(); + let kdl = manifest.to_kdl().unwrap(); + let from_kdl = Manifest::from_kdl(&kdl).unwrap(); + assert_eq!(parsed, from_kdl); + assert_eq!(parsed.to_toml().unwrap(), toml); + assert_eq!(from_kdl.to_kdl().unwrap(), kdl); + assert!(!toml.contains("variants")); + assert!(!kdl.contains("variant")); +} + +#[test] +fn explicit_sources_preserve_default_registry_and_local_dependencies() { + let manifest = evaluate(); + round_trip(&manifest); + let output = manifest.to_toml().unwrap(); + let document: toml::Value = toml::from_str(&output).unwrap(); + let sources = document["sources"].as_array().unwrap(); + assert_eq!(sources.len(), 2); + assert!(sources.iter().any( + |source| source["url"].as_str() == Some("https://rubygems.org") + && source["default"].as_bool() == Some(true) + )); + assert!(document["bundle"].get("source").is_none()); + assert!(output.contains("rails = \"~> 8.0\"")); + assert!(output.contains("[sources.dependencies]")); + assert!(output.contains("[[sources.groups]]")); + assert!(!output.contains("enabled")); + assert!(!output.contains("excluded")); + let parsed: Manifest = toml::from_str(&output).unwrap(); + assert_eq!(parsed.dependencies["debug"].groups, ["development"]); + assert_eq!( + parsed.dependencies["internal"].source.as_deref(), + Some("https://gems.example.com") + ); + assert_eq!( + parsed.dependencies["git-gem"], + manifest.dependencies["git-gem"] + ); + assert_eq!(parsed.dependencies["rails"], manifest.dependencies["rails"]); + assert!( + manifest + .to_kdl() + .unwrap() + .contains("source \"https://rubygems.org\" default=#true") + ); +} + +#[test] +fn legacy_input_remains_readable_and_conflicting_sources_are_rejected() { + let manifest = evaluate(); + let output = manifest.merge_project(include_str!("fixtures/format/reads_mixed_and_expanded_dependencies_and_checks_source_conflicts-1.toml")).unwrap(); + let parsed: Manifest = toml::from_str(&output).unwrap(); + assert_eq!(parsed.dependencies["extra"].version, [">= 1", "< 2"]); + assert_eq!( + parsed.dependencies["extra"].source.as_deref(), + Some("https://gems.example.com") + ); + for input in [ + "[[sources]]\nurl='https://other.test'\n[sources.dependencies]\nrails='~> 8.0'", + "[[sources]]\nurl='https://other.test'\n[sources.dependencies]\nx={git='https://github.com/example/x'}", + "[[sources]]\nurl='https://other.test'\n[sources.dependencies]\nx={source='https://another.test'}", + "[[sources]]\nurl='https://other.test'\ndefault=true", + ] { + assert!(manifest.merge_project(input).is_err(), "{input}"); + } +} + +#[test] +fn repeated_declarations_and_escaping_survive_both_formats() { + for input in [ + include_str!("fixtures/format/complex_variants_and_escaping_survive_both_formats-1.toml"), + include_str!( + "fixtures/format/inline_sources_and_variants_with_different_sources_remain_unambiguous-1.toml" + ), + include_str!("fixtures/format/explicit_sources.toml"), + ] { + let manifest: Manifest = toml::from_str(input).unwrap(); + round_trip(&manifest); + assert_eq!( + toml::from_str::(&manifest.to_toml().unwrap()).unwrap(), + manifest + ); + } +} + +#[test] +fn source_and_group_nesting_is_equivalent() { + let first = Manifest::from_kdl(include_str!("fixtures/format/source_group.kdl")).unwrap(); + let second = Manifest::from_kdl(include_str!("fixtures/format/group_source.kdl")).unwrap(); + assert_eq!(first, second); + assert_eq!( + first.dependencies["internal"].groups, + ["development", "test"] + ); + round_trip(&first); +} + +#[test] +fn malformed_or_conflicting_blocks_are_rejected() { + for input in [ + "source \"one\" default=#true; source \"two\" default=#true", + "source \"one\" { gem \"x\" source=\"two\"; }", + "source \"one\" { gem \"x\" git=\"two\"; }", + "group { gem \"x\"; }", + "gem \"x\" unknown=#true", + "gem \"x\" require=#false require=#true", + "source \"one\" unknown=#true", + "group \"test\" { gem \"x\" { groups \"development\"; }; }", + ] { + assert!(Manifest::from_kdl(input).is_err(), "{input}"); + } +} + +#[test] +fn kdl_preserves_project_metadata() { + let output = evaluate() + .merge_project_format( + include_str!( + "fixtures/format/kdl_uses_source_blocks_and_preserves_metadata_and_options-1.toml" + ), + ExportFormat::Kdl, + ) + .unwrap(); + let document: kdl::KdlDocument = output.parse().unwrap(); + assert_eq!( + document + .get("project") + .unwrap() + .children() + .unwrap() + .get("name") + .unwrap() + .get(0) + .unwrap() + .as_string(), + Some("tea room") + ); + assert!(output.starts_with("// Generated by Ruby Butler. Do not edit.\n")); +} + +#[test] +fn repeated_gems_in_the_same_context_and_singleton_arrays_round_trip() { + let input = include_str!("fixtures/format/repeated_declarations.toml"); + let manifest: Manifest = toml::from_str(input).unwrap(); + round_trip(&manifest); + assert_eq!(manifest.dependencies["rake"].variants.len(), 1); + assert_eq!( + manifest.dependencies["rake"].require, + Some(rb_gemfile::Require::Names(vec!["rake/task".into()])) + ); + let document: toml::Value = toml::from_str(&manifest.to_toml().unwrap()).unwrap(); + let source = &document["sources"][0]; + assert_eq!(source["groups"].as_array().unwrap().len(), 1); + assert_eq!( + source["groups"][0]["dependencies"]["rake"] + .as_array() + .unwrap() + .len(), + 2 + ); +} + +#[test] +fn invalid_toml_source_and_group_settings_are_rejected() { + for input in [ + "[[sources]]\nurl='one'\ndefault=true\n[sources.dependencies]\nx={git='two'}", + "[[sources]]\nurl='one'\ndefault=true\n[sources.dependencies]\nx={source='two'}", + "[[sources]]\nurl=''", + "[[sources]]\nurl='one'\ndefault='yes'", + "[[sources]]\nurl='one'\nunknown=true", + "[[groups]]\nnames=[]", + "[dependencies]\nx=[]", + ] { + assert!(toml::from_str::(input).is_err(), "{input}"); + } + let manifest: Manifest = toml::from_str("").unwrap(); + round_trip(&manifest); +} + +#[test] +fn explicit_pins_to_the_default_registry_are_preserved() { + let manifest: Manifest = + toml::from_str(include_str!("fixtures/format/default_registry_pin.toml")).unwrap(); + assert_eq!(manifest.dependencies["implicit"].source, None); + assert_eq!( + manifest.dependencies["pinned"].source.as_deref(), + Some("https://rubygems.org") + ); + round_trip(&manifest); +} + +#[test] +fn malformed_repeated_declarations_return_errors() { + assert!(Manifest::from_kdl("gem x variants=wrong; gem x").is_err()); + for input in [ + "[[sources]]\nurl='one'\n[sources.dependencies]\nx=[]", + "[[groups]]\nnames=['test']\n[groups.dependencies]\nx=[]", + ] { + assert!(toml::from_str::(input).is_err(), "{input}"); + } +} + +#[test] +fn project_metadata_named_like_dependency_blocks_survives_export() { + let input = "[project]\ngroups=['staff']\nsources=['manual']"; + let expected: toml::Value = toml::from_str(input).unwrap(); + let output = evaluate().merge_project(input).unwrap(); + let actual: toml::Value = toml::from_str(&output).unwrap(); + assert_eq!(actual["project"], expected["project"]); +} + +#[test] +fn gemfile_toml_and_kdl_examples_have_the_same_declarations() { + let root = tempfile::tempdir().unwrap(); + std::fs::write( + root.path().join("Gemfile"), + include_str!("fixtures/format/multi_source/Gemfile"), + ) + .unwrap(); + let evaluated = + Evaluator::new(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())) + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest; + let exported: Manifest = toml::from_str(&evaluated.to_toml().unwrap()).unwrap(); + let toml: Manifest = + toml::from_str(include_str!("fixtures/format/multi_source/project.toml")).unwrap(); + let kdl = Manifest::from_kdl(include_str!("fixtures/format/multi_source/project.kdl")).unwrap(); + assert_eq!(exported, toml); + assert_eq!(toml, kdl); + assert_eq!(toml.dependencies.len(), 5); + assert_eq!(toml.dependencies["rake"].variants.len(), 1); + assert_eq!(toml.dependencies["plugin"].platforms, ["ruby"]); + round_trip(&toml); +} + +#[test] +fn package_dependency_named_item_remains_a_table() { + let manifest: Manifest = + toml::from_str(include_str!("fixtures/format/package_named_item.toml")).unwrap(); + assert_eq!(manifest.gemspecs[0].runtime_dependencies["item"], ["~> 1"]); + round_trip(&manifest); +} diff --git a/crates/rb-gemfile/tests/project.rs b/crates/rb-gemfile/tests/project.rs new file mode 100644 index 0000000..b6d7662 --- /dev/null +++ b/crates/rb-gemfile/tests/project.rs @@ -0,0 +1,140 @@ +use rb_gemfile::Evaluator; + +fn manifest() -> rb_gemfile::Manifest { + let root = tempfile::tempdir().unwrap(); + std::fs::write( + root.path().join("Gemfile"), + "source 'https://rubygems.org'\nruby '>= 3.2'\ngem 'rake', '>= 13', require: false\n", + ) + .unwrap(); + Evaluator::new(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())) + .evaluate(root.path().join("Gemfile")) + .unwrap() + .manifest +} + +#[test] +fn merges_root_settings_and_additional_dependencies() { + let merged = manifest() + .merge_project(include_str!( + "fixtures/project/merges_root_settings_and_additional_dependencies-1.toml" + )) + .unwrap(); + assert!(merged.starts_with("# Generated by Ruby Butler. Do not edit.\n")); + let value: toml::Value = toml::from_str(&merged).unwrap(); + assert_eq!(value["project"]["name"].as_str(), Some("sample")); + assert_eq!(value["scripts"]["test"].as_str(), Some("rspec")); + assert_eq!(value["bundle"]["without"][0].as_str(), Some("development")); + let parsed = parsed_export(&merged); + assert_eq!( + parsed.dependencies["rake"].require, + Some(rb_gemfile::Require::Enabled(false)) + ); + assert_eq!(parsed.dependencies["rack"].version, ["~> 3"]); +} + +#[test] +fn rejects_explicit_dependency_and_bundle_conflicts() { + for (project, message) in [ + ("[dependencies]\nrake = '< 12'", "rake.version"), + ("[dependencies.rake]\nrequire = true", "rake.require"), + ("[bundle]\nsource = 'https://other.test'", "bundle.source"), + ("[bundle]\nruby = '< 3.0'", "bundle.ruby"), + ("dependencies = 1", "dependencies must be a table"), + ( + "[dependencies.rack]\ngit = 'url'\npath = '.'", + "mutually exclusive", + ), + ("[dependencies.rack]\nunknown = true", "unknown field"), + ] { + let error = manifest().merge_project(project).unwrap_err().to_string(); + assert!(error.contains(message), "{project}: {error}"); + } +} + +#[test] +fn accepts_empty_project_and_preserves_multiple_requirements() { + let manifest = manifest(); + let merged = manifest.merge_project("").unwrap(); + assert_eq!( + toml::from_str::(&merged).unwrap(), + manifest + ); + let merged = manifest + .merge_project("[dependencies.rack]\nversion = ['>= 3', '< 4']\n") + .unwrap(); + let parsed: rb_gemfile::Manifest = toml::from_str(&merged).unwrap(); + assert_eq!(parsed.dependencies["rack"].version, [">= 3", "< 4"]); +} + +#[test] +fn exports_only_active_declarations_and_omits_redundant_fields() { + let root = tempfile::tempdir().unwrap(); + std::fs::write( + root.path().join("Gemfile"), + include_str!( + "fixtures/project/exports_only_active_declarations_and_omits_redundant_fields-1.rb" + ), + ) + .unwrap(); + let evaluation = + Evaluator::new(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())) + .evaluate(root.path().join("Gemfile")) + .unwrap(); + assert!(!evaluation.manifest.dependencies["excluded"].enabled); + for output in [ + evaluation.manifest.to_toml().unwrap(), + evaluation.manifest.merge_project("").unwrap(), + ] { + let value: toml::Value = toml::from_str(&output).unwrap(); + assert!(!output.contains("enabled =")); + assert!(!output.contains("= []")); + assert!(value["bundle"].get("ruby").is_none()); + let parsed = parsed_export(&output); + assert!(!parsed.dependencies.contains_key("excluded")); + assert_eq!(parsed.dependencies["mixed"].groups, ["development"]); + assert_eq!( + parsed.dependencies["mixed"].require, + Some(rb_gemfile::Require::Name("mixed/runtime".into())) + ); + assert!(parsed.dependencies["mixed"].variants.is_empty()); + assert_eq!(parsed.dependencies["active_first"].version, [">= 0"]); + assert_eq!( + parsed.dependencies["retained"].require, + Some(rb_gemfile::Require::Enabled(false)) + ); + assert_eq!( + parsed.dependencies["retained"].variants[0].platforms, + ["jruby"] + ); + let parsed: rb_gemfile::Manifest = toml::from_str(&output).unwrap(); + assert!(parsed.bundle.ruby.is_empty()); + assert!(parsed.bundle.optional_groups.is_empty()); + assert!(parsed.dependencies["mixed"].platforms.is_empty()); + assert!(parsed.dependencies["mixed"].enabled); + } +} + +#[test] +fn omits_disabled_root_dependencies() { + let output = manifest() + .merge_project("[dependencies.disabled]\nenabled = false\n") + .unwrap(); + let parsed = parsed_export(&output); + assert!(!parsed.dependencies.contains_key("disabled")); + assert!(parsed.dependencies.contains_key("rake")); +} + +fn parsed_export(input: &str) -> rb_gemfile::Manifest { + let mut value: toml::Table = toml::from_str(input).unwrap(); + value.retain(|key, _| { + matches!( + key, + "bundle" | "dependencies" | "sources" | "groups" | "gemspecs" + ) + }); + if let Some(bundle) = value.get_mut("bundle").and_then(toml::Value::as_table_mut) { + bundle.remove("without"); + } + toml::Value::Table(value).try_into().unwrap() +} diff --git a/crates/rb-gemfile/tests/ruby/evaluator_test.rb b/crates/rb-gemfile/tests/ruby/evaluator_test.rb new file mode 100644 index 0000000..43ed825 --- /dev/null +++ b/crates/rb-gemfile/tests/ruby/evaluator_test.rb @@ -0,0 +1,189 @@ +require "minitest/autorun" +require "tmpdir" +require "fileutils" +require "open3" +require "rbconfig" +require_relative "../../assets/gemfile" +require_relative "../../assets/sources" +require_relative "../../assets/gemspec" +require_relative "../../assets/compatibility" + +class EvaluatorTest < Minitest::Test + FIXTURES = File.expand_path("../fixtures", __dir__) + ENTRYPOINT = File.expand_path("../../assets/evaluate.rb", __dir__) + + def setup + @evaluator = RubyButler::Gemfile.new + evaluator = @evaluator + RubyButler.define_singleton_method(:evaluator) { evaluator } + end + + def teardown + RubyButler.singleton_class.remove_method(:evaluator) + end + + def test_compatibility_read_file_tracks_inputs + path = File.join(FIXTURES, "format/evaluate-1.rb") + assert_equal File.read(path), Bundler.read_file(path) + assert_equal [path], @evaluator.inputs + refute Gem.loaded_specs.key?("bundler") + end + + def test_plugin_index_does_not_load_plugins + assert_same Bundler::Plugin, Bundler::Plugin.index + assert_empty Bundler::Plugin.index.load_paths("bundler-inject") + refute Gem.loaded_specs.key?("bundler-inject") + end + + def test_groups_sources_and_conditions + @evaluator.eval_gemfile(File.join(FIXTURES, "format/evaluate-1.rb")) + dependencies = @evaluator.manifest.fetch(:dependencies) + assert_equal ["~> 8.0"], dependencies.fetch("rails").fetch(:version) + assert_equal ["development"], dependencies.fetch("debug").fetch(:groups) + assert_equal false, dependencies.fetch("debug").fetch(:require) + assert_equal "https://gems.example.com", dependencies.fetch("internal").fetch(:source) + assert_equal "v1.0", dependencies.fetch("git-gem").fetch(:tag) + assert_equal false, dependencies.fetch("excluded").fetch(:enabled) + end + + def test_source_cooldowns_do_not_change_declarations + @evaluator.eval_gemfile(File.join(FIXTURES, "ruby/source_options/Gemfile")) + refute @evaluator.manifest.fetch(:bundle).key?(:source_cooldowns) + assert_equal "https://example.test", @evaluator.manifest.fetch(:dependencies).fetch("scoped").fetch(:source) + end + + def test_source_cooldowns_reject_invalid_values + [-1, "7", 1.5, true].each do |value| + error = assert_raises(ArgumentError) { @evaluator.source("https://rubygems.org", cooldown: value) } + assert_match "non-negative integer", error.message + end + end + + def test_source_accepts_zero_cooldown_and_rejects_unknown_options + @evaluator.source("https://rubygems.org", cooldown: 0) + assert_equal "https://rubygems.org", @evaluator.manifest.fetch(:bundle).fetch(:source) + error = assert_raises(ArgumentError) { @evaluator.source("https://example.test", mystery: true) } + assert_match "Unsupported source options", error.message + end + + def test_gemspec_accepts_require_without_changing_bundler_activation + @evaluator.eval_gemfile(File.join(FIXTURES, "ruby/gemspec_options/Gemfile")) + assert_equal ["= 1.0.0"], @evaluator.manifest.fetch(:dependencies).fetch("sample").fetch(:version) + refute @evaluator.manifest.fetch(:dependencies).fetch("sample").key?(:require) + end + + def test_pathname_is_available_without_loading_bundler + Dir.mktmpdir do |directory| + gemfile = File.join(directory, "Gemfile") + result = File.join(directory, "manifest.json") + File.write(gemfile, "gem Pathname.new('rake').to_s") + _, stderr, status = Open3.capture3(RbConfig.ruby, ENTRYPOINT, gemfile, result) + assert status.success?, stderr + assert JSON.parse(File.read(result)).fetch("manifest").fetch("dependencies").key?("rake") + end + end + + def test_require_nil_disables_autorequire + @evaluator.gem("rake", require: nil) + @evaluator.gem("json") + assert_equal false, @evaluator.manifest.fetch(:dependencies).fetch("rake").fetch(:require) + refute @evaluator.manifest.fetch(:dependencies).fetch("json").key?(:require) + end + + def test_gemfile_helpers_can_inspect_and_remove_dependencies + @evaluator.eval_gemfile(File.join(FIXTURES, "ruby/compatibility_helpers/Gemfile")) + dependencies = @evaluator.manifest.fetch(:dependencies) + refute dependencies.key?("keep") + assert_equal ["~> 3"], dependencies.fetch("replace").fetch(:version) + assert_equal ["~> 3"], dependencies.fetch("rack").fetch(:version) + assert_equal ["windows"], dependencies.fetch("tzinfo-data").fetch(:platforms) + refute Gem.loaded_specs.key?("bundler") + end + + def test_platforms_and_ruby_constraints_are_preserved + @evaluator.ruby(">= 3.2", "< 5") + @evaluator.platforms(:jruby) { @evaluator.gem("jdbc", require: false) } + assert_equal [">= 3.2", "< 5"], @evaluator.manifest.fetch(:bundle).fetch(:ruby) + dependency = @evaluator.manifest.fetch(:dependencies).fetch("jdbc") + assert_equal ["jruby"], dependency.fetch(:platforms) + assert_equal false, dependency.fetch(:require) + end + + def test_removed_gemspec_dependency_can_be_redeclared + Dir.mktmpdir do |directory| + File.write(File.join(directory, "Gemfile"), "gemspec") + FileUtils.cp(File.join(FIXTURES, "evaluation/loads_project_gemspec_and_ruby_version_file-1.rb"), + File.join(directory, "sample.gemspec")) + @evaluator.eval_gemfile(File.join(directory, "Gemfile")) + @evaluator.dependencies.reject! { |dependency| dependency.name == "rake" } + @evaluator.gem("rake", "~> 14") + assert_equal ["~> 14"], @evaluator.manifest.fetch(:dependencies).fetch("rake").fetch(:version) + assert_equal Gem::Requirement.new("~> 14"), @evaluator.dependencies.find { |dependency| dependency.name == "rake" }.requirement + end + end + + def test_gemspec_metadata_and_development_dependencies + Dir.mktmpdir do |directory| + File.write(File.join(directory, "Gemfile"), "gemspec") + FileUtils.cp(File.join(FIXTURES, "evaluation/loads_project_gemspec_and_ruby_version_file-1.rb"), + File.join(directory, "sample.gemspec")) + @evaluator.eval_gemfile(File.join(directory, "Gemfile")) + package = @evaluator.manifest.fetch(:gemspecs).first + assert_equal "sample", package.fetch(:name) + assert_equal "1.2.3", package.fetch(:version) + assert_equal ["~> 3.0"], package.fetch(:runtime_dependencies).fetch("rack") + assert_equal [">= 13"], package.fetch(:development_dependencies).fetch("rake") + assert_equal ["development"], @evaluator.manifest.fetch(:dependencies).fetch("rake").fetch(:groups) + end + end + + def test_plugins_are_metadata_only + @evaluator.plugin("bundler-inject", "~> 2.0") + assert_equal [{ name: "bundler-inject", version: ["~> 2.0"] }], @evaluator.manifest.fetch(:bundle).fetch(:plugins) + refute Gem.loaded_specs.key?("bundler-inject") + end + + def test_nested_source_scopes_restore_context + @evaluator.eval_gemfile(File.join(FIXTURES, "ruby/nested_sources.rb")) + dependencies = @evaluator.manifest.fetch(:dependencies) + assert_equal "https://example.test", dependencies.fetch("registry").fetch(:source) + refute dependencies.fetch("registry").key?(:branch) + assert_equal "main", dependencies.fetch("outer").fetch(:branch) + refute dependencies.fetch("normal").key?(:git) + end + + def test_invalid_options_and_recursive_includes_fail + error = assert_raises(ArgumentError) { @evaluator.gem("rake", mystery: true) } + assert_match "Unsupported gem options", error.message + error = assert_raises(ArgumentError) { @evaluator.eval_gemfile("Gemfile", "eval_gemfile 'Gemfile'") } + assert_match "Recursive eval_gemfile", error.message + end + + def test_entrypoint_writes_json_separately_from_diagnostics + Dir.mktmpdir do |directory| + gemfile = File.join(directory, "Gemfile") + result = File.join(directory, "manifest.json") + File.write(gemfile, "puts 'hello'; warn 'warning'; gem 'rake'") + stdout, stderr, status = Open3.capture3(RbConfig.ruby, ENTRYPOINT, gemfile, result) + assert status.success?, stderr + assert_equal ["hello"], stdout.lines.map(&:chomp) + assert_equal ["warning"], stderr.lines.map(&:chomp) + manifest = JSON.parse(File.read(result)) + assert_equal [gemfile], manifest.fetch("inputs") + assert_equal [">= 0"], manifest.fetch("manifest").fetch("dependencies").fetch("rake").fetch("version") + end + end + + def test_entrypoint_reports_failures_without_a_manifest + Dir.mktmpdir do |directory| + gemfile = File.join(directory, "Gemfile") + result = File.join(directory, "manifest.json") + File.write(gemfile, "raise 'invalid teacup'") + stdout, stderr, status = Open3.capture3(RbConfig.ruby, ENTRYPOINT, gemfile, result) + refute status.success? + assert_empty stdout + assert_match "RuntimeError: invalid teacup", stderr + refute File.exist?(result) + end + end +end diff --git a/crates/rb-gemfile/tests/snapshot.rs b/crates/rb-gemfile/tests/snapshot.rs new file mode 100644 index 0000000..caf2c64 --- /dev/null +++ b/crates/rb-gemfile/tests/snapshot.rs @@ -0,0 +1,424 @@ +use rb_gemfile::{Evaluator, SnapshotCache, write_project}; +use std::{fs, path::Path}; + +fn evaluator() -> Evaluator { + Evaluator::new(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())) +} + +fn write(root: &Path, file: &str, text: &str) { + let path = root.join(file); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); +} + +#[test] +fn reuses_snapshot_and_invalidates_file_contents_and_directory_membership() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "gem 'rack', File.read('version').strip\nDir['Gemfile.*'].each { |f| eval_gemfile f }", + ); + write(root.path(), "version", "3.1.0"); + let cache = SnapshotCache::new(root.path().join(".rb/gemfile.json")); + let evaluator = evaluator(); + let gemfile = root.path().join("Gemfile"); + assert!(!cache.evaluate(&evaluator, &gemfile).unwrap().reused); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); + write(root.path(), "version", "3.2.0"); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.reused); + assert_eq!( + result.evaluation.manifest.dependencies["rack"].version, + ["3.2.0"] + ); + write(root.path(), "Gemfile.local", "gem 'rake'"); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.reused); + assert!(result.evaluation.manifest.dependencies.contains_key("rake")); + fs::remove_file(root.path().join("Gemfile.local")).unwrap(); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.evaluation.manifest.dependencies.contains_key("rake")); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); +} + +#[test] +fn corruption_is_a_miss_and_failed_evaluation_preserves_existing_snapshot() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "warn 'diagnostic'; puts 'hello'; gem 'rake'", + ); + let path = root.path().join("snapshot.json"); + let cache = SnapshotCache::new(&path); + let evaluator = evaluator(); + let gemfile = root.path().join("Gemfile"); + cache.evaluate(&evaluator, &gemfile).unwrap(); + let reused = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(reused.reused); + assert_eq!( + reused.evaluation.stdout.lines().collect::>(), + ["hello"] + ); + assert_eq!( + reused.evaluation.stderr.lines().collect::>(), + ["diagnostic"] + ); + fs::write(&path, "broken JSON").unwrap(); + assert!(!cache.evaluate(&evaluator, &gemfile).unwrap().reused); + let original = fs::read(&path).unwrap(); + write(root.path(), "Gemfile", "raise 'evaluation failed'"); + assert!(cache.evaluate(&evaluator, &gemfile).is_err()); + assert_eq!(fs::read(&path).unwrap(), original); + write( + root.path(), + "Gemfile", + "warn 'diagnostic'; puts 'hello'; gem 'rake'", + ); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); +} + +#[test] +fn external_includes_require_declared_cache_inputs() { + let root = tempfile::tempdir().unwrap(); + let external = tempfile::tempdir().unwrap(); + write(external.path(), "Gemfile", "gem 'rake'"); + let external_file = external.path().join("Gemfile"); + write( + root.path(), + "Gemfile", + &format!( + "eval_gemfile {}", + serde_json::to_string(&external_file.to_str().unwrap()).unwrap() + ), + ); + let path = root.path().join(".rb/snapshot.json"); + let cache = SnapshotCache::new(&path); + let evaluator = evaluator(); + let gemfile = root.path().join("Gemfile"); + assert!(!cache.evaluate(&evaluator, &gemfile).unwrap().reused); + assert!(!path.exists()); + let cache = cache.input(external.path()); + assert!(!cache.evaluate(&evaluator, &gemfile).unwrap().reused); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); + write(external.path(), "Gemfile", "gem 'rack'"); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.reused); + assert!(result.evaluation.manifest.dependencies.contains_key("rack")); +} + +#[test] +#[cfg(unix)] +fn external_includes_through_symlinked_directories_reuse_snapshot() { + let root = tempfile::tempdir().unwrap(); + let external = tempfile::tempdir().unwrap(); + write(external.path(), "Gemfile", "gem 'rake'"); + let alias = root.path().join("external"); + std::os::unix::fs::symlink(external.path(), &alias).unwrap(); + write(root.path(), "Gemfile", "eval_gemfile 'external/Gemfile'"); + let gemfile = root.path().join("Gemfile"); + let cache = SnapshotCache::new(root.path().join(".rb/snapshot.json")).input(external.path()); + let evaluator = evaluator(); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.reused); + assert!( + result + .evaluation + .inputs + .contains(&dunce::canonicalize(external.path().join("Gemfile")).unwrap()) + ); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); + write(external.path(), "Gemfile", "gem 'rack'"); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.reused); + assert!(result.evaluation.manifest.dependencies.contains_key("rack")); +} + +#[test] +fn generated_project_is_replaced_and_keeps_project_configuration() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "source 'https://rubygems.org'; gem 'rack'", + ); + let evaluation = evaluator().evaluate(root.path().join("Gemfile")).unwrap(); + let project = evaluation + .manifest + .merge_project("[project]\nname = 'test'\n[dependencies]\nrake = '>= 13'") + .unwrap(); + let path = root.path().join(".rb/rbproject.toml"); + write_project(&path, &project).unwrap(); + assert_eq!(fs::read_to_string(&path).unwrap(), project); + assert!(project.starts_with("# Generated by Ruby Butler. Do not edit.\n")); + let parsed: toml::Value = toml::from_str(&project).unwrap(); + assert_eq!(parsed["project"]["name"].as_str(), Some("test")); + assert!(parsed["sources"].as_array().unwrap().iter().any(|source| { + source + .get("dependencies") + .is_some_and(|deps| deps.get("rack").is_some()) + })); + write_project(&path, "replacement\n").unwrap(); + assert_eq!(fs::read_to_string(path).unwrap(), "replacement\n"); +} + +#[cfg(unix)] +#[test] +fn a_cache_hit_does_not_start_ruby() { + use std::os::unix::fs::PermissionsExt; + let root = tempfile::tempdir().unwrap(); + let executable = tempfile::tempdir().unwrap(); + let count = executable.path().join("starts"); + let wrapper = executable.path().join("ruby"); + let ruby = + which::which(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())).unwrap(); + let quote = |path: &Path| format!("'{}'", path.to_str().unwrap().replace('\'', "'\\''")); + fs::write( + &wrapper, + format!( + "#!/bin/sh\nprintf 'start\\n' >> {}\nexec {} \"$@\"\n", + quote(&count), + quote(&ruby) + ), + ) + .unwrap(); + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap(); + write(root.path(), "Gemfile", "gem 'rake'"); + let evaluator = Evaluator::new(&wrapper); + let cache = SnapshotCache::new(root.path().join(".rb/snapshot.json")); + let gemfile = root.path().join("Gemfile"); + assert!(!cache.evaluate(&evaluator, &gemfile).unwrap().reused); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); + assert_eq!(fs::read_to_string(&count).unwrap(), "start\n"); + fs::write( + &wrapper, + format!( + "#!/bin/sh\nprintf 'changed\\n' >> {}\nexec {} \"$@\"\n", + quote(&count), + quote(&ruby) + ), + ) + .unwrap(); + assert!(!cache.evaluate(&evaluator, &gemfile).unwrap().reused); + assert_eq!(fs::read_to_string(count).unwrap(), "start\nchanged\n"); +} + +#[test] +fn effective_environment_changes_invalidate_without_storing_values() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "gem 'rack', ENV.fetch('TEST_RACK_VERSION')", + ); + let path = root.path().join(".rb/snapshot.json"); + let cache = SnapshotCache::new(&path); + let gemfile = root.path().join("Gemfile"); + let first = evaluator() + .env("TEST_RACK_VERSION", "3.1.0") + .env("TEST_SECRET", "private-value"); + cache.evaluate(&first, &gemfile).unwrap(); + assert!(cache.evaluate(&first, &gemfile).unwrap().reused); + assert!(!fs::read_to_string(&path).unwrap().contains("private-value")); + let second = evaluator() + .env("TEST_RACK_VERSION", "3.2.0") + .env("TEST_SECRET", "private-value"); + let result = cache.evaluate(&second, &gemfile).unwrap(); + assert!(!result.reused); + assert_eq!( + result.evaluation.manifest.dependencies["rack"].version, + ["3.2.0"] + ); + assert!(cache.evaluate(&second, &gemfile).unwrap().reused); +} + +#[test] +fn input_changes_during_evaluation_are_not_cached() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "gem 'rack', File.read('version').strip; File.write('version', '3.2.0')", + ); + write(root.path(), "version", "3.1.0"); + let path = root.path().join(".rb/snapshot.json"); + let result = SnapshotCache::new(&path) + .evaluate(&evaluator(), root.path().join("Gemfile")) + .unwrap(); + assert!(!result.reused); + assert_eq!( + result.evaluation.manifest.dependencies["rack"].version, + ["3.1.0"] + ); + assert!(!path.exists()); +} + +#[test] +fn cannot_overwrite_gemfile_or_ruby_inputs_with_a_snapshot() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "gem 'rake'"); + let gemfile = root.path().join("Gemfile"); + let error = SnapshotCache::new(&gemfile) + .evaluate(&evaluator(), &gemfile) + .err() + .unwrap(); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput); + assert_eq!(fs::read_to_string(&gemfile).unwrap(), "gem 'rake'"); + let ruby = + which::which(std::env::var_os("RB_GEMFILE_RUBY").unwrap_or_else(|| "ruby".into())).unwrap(); + let error = SnapshotCache::new(&ruby) + .evaluate(&evaluator(), &gemfile) + .unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput); +} + +#[test] +fn valid_json_with_damaged_manifest_is_rebuilt() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "gem 'rake'"); + let path = root.path().join(".rb/snapshot.json"); + let cache = SnapshotCache::new(&path); + let evaluator = evaluator(); + let gemfile = root.path().join("Gemfile"); + cache.evaluate(&evaluator, &gemfile).unwrap(); + let mut snapshot: serde_json::Value = + serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + snapshot["evaluation"]["manifest"]["dependencies"] + .as_object_mut() + .unwrap() + .remove("rake"); + fs::write(&path, serde_json::to_vec(&snapshot).unwrap()).unwrap(); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.reused); + assert!(result.evaluation.manifest.dependencies.contains_key("rake")); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); +} + +#[cfg(unix)] +#[test] +fn symlinked_inputs_are_fingerprinted_without_directory_cycles() { + use std::os::unix::fs::symlink; + let root = tempfile::tempdir().unwrap(); + let external = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + "gem 'rack', File.read('version').strip", + ); + write(external.path(), "version", "3.1.0"); + symlink(external.path().join("version"), root.path().join("version")).unwrap(); + symlink(root.path(), root.path().join("loop")).unwrap(); + let cache = SnapshotCache::new(root.path().join(".rb/snapshot.json")); + let evaluator = evaluator(); + let gemfile = root.path().join("Gemfile"); + cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); + write(external.path(), "version", "3.2.0"); + let result = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!result.reused); + assert_eq!( + result.evaluation.manifest.dependencies["rack"].version, + ["3.2.0"] + ); +} + +#[test] +fn invalid_file_paths_return_errors() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "gem 'rake'"); + let evaluator = evaluator(); + let cache = SnapshotCache::new(root.path().join("snapshot.json")); + assert_eq!( + cache.evaluate(&evaluator, root.path()).unwrap_err().kind(), + std::io::ErrorKind::InvalidInput + ); + let filesystem_root = root.path().ancestors().last().unwrap(); + assert_eq!( + SnapshotCache::new(filesystem_root) + .evaluate(&evaluator, root.path().join("Gemfile")) + .unwrap_err() + .kind(), + std::io::ErrorKind::InvalidInput + ); +} + +#[test] +fn exporting_the_generated_project_does_not_invalidate_its_snapshot() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "gem 'rake'"); + let project = root.path().join(".rb/rbproject.toml"); + let cache = SnapshotCache::new(root.path().join(".rb/snapshot.json")).output(&project); + let evaluator = evaluator(); + let gemfile = root.path().join("Gemfile"); + let initial = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!initial.reused); + write_project(&project, &initial.evaluation.manifest.to_toml().unwrap()).unwrap(); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); + write_project( + &project, + &initial + .evaluation + .manifest + .merge_project("[project]\nname='updated'") + .unwrap(), + ) + .unwrap(); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); +} + +#[test] +fn concurrent_callers_share_one_atomic_snapshot() { + let root = tempfile::tempdir().unwrap(); + write(root.path(), "Gemfile", "gem 'rake'"); + let cache = SnapshotCache::new(root.path().join(".rb/snapshot.json")); + let evaluator = evaluator(); + let gemfile = root.path().join("Gemfile"); + let mut results = std::thread::scope(|scope| { + let first = scope.spawn(|| cache.evaluate(&evaluator, &gemfile).unwrap()); + let second = scope.spawn(|| cache.evaluate(&evaluator, &gemfile).unwrap()); + [first.join().unwrap(), second.join().unwrap()] + }); + assert_eq!( + results[0].evaluation.manifest, + results[1].evaluation.manifest + ); + results.sort_by_key(|result| result.reused); + assert!(!results[0].reused); + assert!(results[1].reused); + assert!(cache.evaluate(&evaluator, &gemfile).unwrap().reused); +} + +#[test] +fn changing_condition_inputs_updates_exported_dependencies() { + let root = tempfile::tempdir().unwrap(); + write( + root.path(), + "Gemfile", + include_str!( + "fixtures/snapshot/changing_condition_inputs_updates_exported_dependencies-1.rb" + ), + ); + let cache = SnapshotCache::new(root.path().join(".rb/snapshot.json")); + let gemfile = root.path().join("Gemfile"); + for (setting, expected) in [("0", false), ("1", true), ("0", false)] { + let evaluator = evaluator().env("WITH_DEBUG", setting); + let fresh = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(!fresh.reused); + let reused = cache.evaluate(&evaluator, &gemfile).unwrap(); + assert!(reused.reused); + for result in [fresh, reused] { + let output = result.evaluation.manifest.to_toml().unwrap(); + let parsed: toml::Value = toml::from_str(&output).unwrap(); + assert_eq!(parsed["dependencies"].get("debug").is_some(), expected); + assert!(parsed["dependencies"].get("rake").is_some()); + assert!(!output.contains("enabled =")); + if expected { + assert_eq!( + parsed["dependencies"]["debug"]["require"].as_bool(), + Some(false) + ); + } + } + } +} diff --git a/spec/commands/export_gemfile_spec.sh b/spec/commands/export_gemfile_spec.sh new file mode 100644 index 0000000..add875d --- /dev/null +++ b/spec/commands/export_gemfile_spec.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +Describe "Ruby Butler Gemfile export" + Include spec/support/helpers.sh + + setup() { + RUBIES_DIR="${RB_EXPORT_TEST_RUBIES_DIR:-$RUBIES_DIR}" + TEST_EXPORT_DIR="${SHELLSPEC_TMPBASE}/export-gemfile-$$-${RANDOM}" + mkdir -p "$TEST_EXPORT_DIR/tea-room" + cp spec/fixtures/export-gemfile/Gemfile "$TEST_EXPORT_DIR/tea-room/Gemfile" + printf '[project]\nname = "Dinner service"\n' > "$TEST_EXPORT_DIR/tea-room/settings.toml" + } + + cleanup() { + rm -rf "$TEST_EXPORT_DIR" + } + + BeforeEach 'setup' + AfterEach 'cleanup' + + It "exports compact TOML to stdout without creating files" + When run rb -R "$RUBIES_DIR" -r "$LATEST_RUBY" -C "$TEST_EXPORT_DIR/tea-room" export-gemfile + The status should equal 0 + The stderr should equal "" + The output should include 'name = "tea-room"' + The output should include 'rails = "~> 8.0"' + The output should include 'debug = { require = false }' + The output should include 'url = "https://gems.example.org"' + The output should include 'private-api = "~> 2.0"' + The file "$TEST_EXPORT_DIR/tea-room/rbproject.toml" should not be exist + The file "$TEST_EXPORT_DIR/tea-room/Gemfile.lock" should not be exist + End + + It "exports KDL using global project settings" + When run rb -R "$RUBIES_DIR" -r "$LATEST_RUBY" -C "$TEST_EXPORT_DIR/tea-room" -P settings.toml export-gemfile --format kdl + The status should equal 0 + The stderr should equal "" + The output should include 'name "Dinner service"' + The output should include 'gem rails "~> 8.0"' + The output should include 'gem debug require=#false' + The output should include 'source "https://gems.example.org"' + The contents of file "$TEST_EXPORT_DIR/tea-room/settings.toml" should include 'name = "Dinner service"' + End + + It "fails when the selected Gemfile is missing" + When run rb -R "$RUBIES_DIR" -r "$LATEST_RUBY" -C "$TEST_EXPORT_DIR/tea-room" export-gemfile missing.rb + The status should not equal 0 + The output should equal "" + The stderr should include "missing.rb" + End +End diff --git a/spec/fixtures/export-gemfile/Gemfile b/spec/fixtures/export-gemfile/Gemfile new file mode 100644 index 0000000..8e33c8e --- /dev/null +++ b/spec/fixtures/export-gemfile/Gemfile @@ -0,0 +1,8 @@ +source 'https://rubygems.org' +gem 'rails', '~> 8.0' +group :development do + gem 'debug', require: false +end +source 'https://gems.example.org' do + gem 'private-api', '~> 2.0' +end diff --git a/tests/commands/ExportGemfile.Integration.Tests.ps1 b/tests/commands/ExportGemfile.Integration.Tests.ps1 new file mode 100644 index 0000000..52a8d84 --- /dev/null +++ b/tests/commands/ExportGemfile.Integration.Tests.ps1 @@ -0,0 +1,52 @@ +BeforeAll { + $Script:RbPath = $env:RB_TEST_PATH + if (-not $Script:RbPath) { + throw "RB_TEST_PATH environment variable not set. Run Setup.ps1 first." + } + $Script:Fixture = Join-Path $PSScriptRoot '../../spec/fixtures/export-gemfile/Gemfile' +} + +Describe 'Ruby Butler - Gemfile export' { + BeforeEach { + $Script:ProjectDir = Join-Path $TestDrive 'tea-room' + New-Item -ItemType Directory -Path $Script:ProjectDir -Force | Out-Null + Copy-Item $Script:Fixture (Join-Path $Script:ProjectDir 'Gemfile') + $Script:Settings = Join-Path $Script:ProjectDir 'settings.toml' + "[project]`nname = `"Dinner service`"" | Set-Content $Script:Settings + $Script:Errors = Join-Path $TestDrive 'stderr.txt' + } + + It 'exports compact TOML to stdout without creating files' { + $Output = & $Script:RbPath -r 3.4.5 -C $Script:ProjectDir export-gemfile 2> $Script:Errors + $LASTEXITCODE | Should -Be 0 + Get-Content $Script:Errors -Raw | Should -BeNullOrEmpty + $Text = $Output -join "`n" + $Text | Should -Match 'name = "tea-room"' + $Text | Should -Match 'rails = "~> 8.0"' + $Text | Should -Match 'debug = \{ require = false \}' + $Text | Should -Match 'url = "https://gems.example.org"' + $Text | Should -Match 'private-api = "~> 2.0"' + Test-Path (Join-Path $Script:ProjectDir 'rbproject.toml') | Should -BeFalse + Test-Path (Join-Path $Script:ProjectDir 'Gemfile.lock') | Should -BeFalse + } + + It 'exports KDL using global project settings' { + $Original = Get-Content $Script:Settings -Raw + $Output = & $Script:RbPath -r 3.4.5 -C $Script:ProjectDir -P settings.toml export-gemfile --format kdl 2> $Script:Errors + $LASTEXITCODE | Should -Be 0 + Get-Content $Script:Errors -Raw | Should -BeNullOrEmpty + $Text = $Output -join "`n" + $Text | Should -Match 'name "Dinner service"' + $Text | Should -Match 'gem rails "~> 8.0"' + $Text | Should -Match 'gem debug require=#false' + $Text | Should -Match 'source "https://gems.example.org"' + Get-Content $Script:Settings -Raw | Should -BeExactly $Original + } + + It 'fails when the selected Gemfile is missing' { + $Output = & $Script:RbPath -r 3.4.5 -C $Script:ProjectDir export-gemfile missing.rb 2> $Script:Errors + $LASTEXITCODE | Should -Not -Be 0 + $Output | Should -BeNullOrEmpty + Get-Content $Script:Errors -Raw | Should -Match 'missing.rb' + } +}