From 1835c63d0a51023a238b541ff5c1d4a1b673b19b Mon Sep 17 00:00:00 2001 From: "nweiz@google.com" Date: Wed, 4 Feb 2015 20:45:49 +0000 Subject: [PATCH] Use native async/await support in pub. R=rnystrom@google.com Review URL: https://codereview.chromium.org//896623005 git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart@43483 260f80e4-7a28-3924-810f-c04153c831b5 --- create_sdk.gyp | 4 +- sdk/bin/pub | 4 +- sdk/bin/pub.bat | 4 +- sdk/lib/_internal/pub/bin/async_compile.dart | 294 --- .../pub/test/async_compile_test.dart | 28 - sdk/lib/_internal/pub/test/test_pub.dart | 12 +- sdk/lib/_internal/pub_generated/README.md | 18 - .../pub_generated/asset/dart/serialize.dart | 184 -- .../dart/serialize/aggregate_transform.dart | 173 -- .../asset/dart/serialize/exception.dart | 102 - .../dart/serialize/get_input_transform.dart | 34 - .../asset/dart/serialize/transform.dart | 149 -- .../asset/dart/serialize/transformer.dart | 126 -- .../asset/dart/transformer_isolate.dart | 112 -- .../pub_generated/asset/dart/utils.dart | 86 - .../pub_generated/bin/async_compile.dart | 294 --- sdk/lib/_internal/pub_generated/bin/pub.dart | 9 - .../pub_generated/lib/src/ascii_tree.dart | 173 -- .../pub_generated/lib/src/barback.dart | 89 - .../lib/src/barback/admin_server.dart | 70 - .../lib/src/barback/asset_environment.dart | 960 --------- .../lib/src/barback/barback_server.dart | 211 -- .../lib/src/barback/base_server.dart | 129 -- .../lib/src/barback/cycle_exception.dart | 60 - .../lib/src/barback/dart2js_transformer.dart | 431 ----- .../barback/dart_forwarding_transformer.dart | 32 - .../lib/src/barback/dependency_computer.dart | 429 ---- .../excluding_aggregate_transformer.dart | 69 - .../src/barback/excluding_transformer.dart | 67 - .../lib/src/barback/foreign_transformer.dart | 171 -- .../src/barback/load_all_transformers.dart | 276 --- .../lib/src/barback/pub_package_provider.dart | 125 -- .../lib/src/barback/source_directory.dart | 71 - .../lib/src/barback/transformer_cache.dart | 144 -- .../lib/src/barback/transformer_config.dart | 166 -- .../lib/src/barback/transformer_id.dart | 99 - .../lib/src/barback/transformer_isolate.dart | 141 -- .../lib/src/barback/transformer_loader.dart | 249 --- .../lib/src/barback/web_socket_api.dart | 321 --- .../pub_generated/lib/src/cached_package.dart | 88 - .../pub_generated/lib/src/command.dart | 96 - .../lib/src/command/barback.dart | 204 -- .../pub_generated/lib/src/command/build.dart | 275 --- .../pub_generated/lib/src/command/cache.dart | 24 - .../lib/src/command/cache_add.dart | 96 - .../lib/src/command/cache_list.dart | 39 - .../lib/src/command/cache_repair.dart | 143 -- .../pub_generated/lib/src/command/deps.dart | 204 -- .../lib/src/command/downgrade.dart | 68 - .../pub_generated/lib/src/command/get.dart | 38 - .../pub_generated/lib/src/command/global.dart | 25 - .../lib/src/command/global_activate.dart | 117 -- .../lib/src/command/global_deactivate.dart | 36 - .../lib/src/command/global_list.dart | 22 - .../lib/src/command/global_run.dart | 92 - .../pub_generated/lib/src/command/lish.dart | 200 -- .../lib/src/command/list_package_dirs.dart | 63 - .../pub_generated/lib/src/command/run.dart | 107 - .../pub_generated/lib/src/command/serve.dart | 264 --- .../lib/src/command/upgrade.dart | 69 - .../lib/src/command/uploader.dart | 88 - .../lib/src/command/version.dart | 20 - .../pub_generated/lib/src/command_runner.dart | 339 ---- .../_internal/pub_generated/lib/src/dart.dart | 323 ---- .../pub_generated/lib/src/entrypoint.dart | 951 --------- .../pub_generated/lib/src/error_group.dart | 299 --- .../pub_generated/lib/src/exceptions.dart | 125 -- .../pub_generated/lib/src/executable.dart | 320 --- .../pub_generated/lib/src/exit_codes.dart | 60 - .../_internal/pub_generated/lib/src/git.dart | 116 -- .../lib/src/global_packages.dart | 1109 ----------- .../_internal/pub_generated/lib/src/http.dart | 270 --- .../_internal/pub_generated/lib/src/io.dart | 1028 ---------- .../pub_generated/lib/src/lock_file.dart | 147 -- .../_internal/pub_generated/lib/src/log.dart | 551 ------ .../pub_generated/lib/src/oauth2.dart | 222 --- .../pub_generated/lib/src/package.dart | 393 ---- .../pub_generated/lib/src/package_graph.dart | 120 -- .../pub_generated/lib/src/preprocess.dart | 144 -- .../pub_generated/lib/src/progress.dart | 100 - .../pub_generated/lib/src/pubspec.dart | 628 ------ .../_internal/pub_generated/lib/src/sdk.dart | 73 - .../lib/src/solver/backtracking_solver.dart | 810 -------- .../lib/src/solver/dependency_queue.dart | 156 -- .../lib/src/solver/solve_report.dart | 248 --- .../lib/src/solver/version_queue.dart | 110 -- .../lib/src/solver/version_solver.dart | 510 ----- .../pub_generated/lib/src/source.dart | 187 -- .../pub_generated/lib/src/source/cached.dart | 75 - .../pub_generated/lib/src/source/git.dart | 400 ---- .../pub_generated/lib/src/source/hosted.dart | 450 ----- .../pub_generated/lib/src/source/path.dart | 162 -- .../pub_generated/lib/src/source/unknown.dart | 48 - .../lib/src/source_registry.dart | 81 - .../pub_generated/lib/src/system_cache.dart | 108 -- .../pub_generated/lib/src/transcript.dart | 73 - .../pub_generated/lib/src/utils.dart | 924 --------- .../pub_generated/lib/src/validator.dart | 99 - .../lib/src/validator/compiled_dartdoc.dart | 43 - .../lib/src/validator/dependency.dart | 273 --- .../src/validator/dependency_override.dart | 27 - .../lib/src/validator/directory.dart | 51 - .../lib/src/validator/executable.dart | 42 - .../lib/src/validator/license.dart | 34 - .../pub_generated/lib/src/validator/name.dart | 133 -- .../lib/src/validator/pubspec_field.dart | 111 -- .../lib/src/validator/sdk_constraint.dart | 45 - .../pub_generated/lib/src/validator/size.dart | 32 - .../lib/src/validator/utf8_readme.dart | 35 - .../pub_generated/test/ascii_tree_test.dart | 244 --- .../test/async_compile_test.dart | 30 - ...includes_all_default_directories_test.dart | 60 - .../test/barback/directory_args_test.dart | 52 - .../barback/fails_if_args_with_all_test.dart | 24 - .../fails_if_dir_arg_does_not_exist_test.dart | 26 - .../fails_if_dir_outside_package_test.dart | 24 - .../fails_if_no_default_dirs_test.dart | 27 - ...ll_with_no_buildable_directories_test.dart | 26 - .../fails_on_disallowed_directories_test.dart | 26 - ...fails_on_overlapping_directories_test.dart | 54 - .../test/barback/subdirectories_test.dart | 60 - .../pub_generated/test/barback/utils.dart | 60 - .../build/allows_arbitrary_modes_test.dart | 50 - .../can_specify_output_directory_test.dart | 32 - .../cleans_entire_build_directory_test.dart | 38 - ...s_browser_js_next_to_entrypoints_test.dart | 100 - ...wser_js_with_dependency_override_test.dart | 60 - ...s_browser_js_with_dev_dependency_test.dart | 60 - .../copies_non_dart_files_to_build_test.dart | 44 - .../build/defaults_to_release_mode_test.dart | 50 - .../test/build/handles_long_paths_test.dart | 68 - ...ncludes_assets_from_dependencies_test.dart | 77 - ...files_from_dependencies_in_debug_test.dart | 70 - ...ncludes_dart_files_in_debug_mode_test.dart | 48 - .../build/outputs_error_to_json_test.dart | 54 - .../build/outputs_results_to_json_test.dart | 75 - .../test/build/preserves_htaccess_test.dart | 34 - .../pub_generated/test/build/utils.dart | 45 - .../adds_latest_matching_version_test.dart | 35 - .../cache/add/adds_latest_version_test.dart | 27 - .../all_adds_all_matching_versions_test.dart | 37 - .../all_with_some_versions_present_test.dart | 49 - .../test/cache/add/already_cached_test.dart | 31 - .../test/cache/add/bad_version_test.dart | 25 - .../cache/add/missing_package_arg_test.dart | 25 - .../cache/add/no_matching_version_test.dart | 22 - .../cache/add/package_not_found_test.dart | 20 - .../cache/add/unexpected_arguments_test.dart | 25 - .../pub_generated/test/cache/list_test.dart | 97 - .../test/cache/repair/empty_cache_test.dart | 17 - .../handles_corrupted_binstub_test.dart | 35 - ...andles_corrupted_global_lockfile_test.dart | 24 - .../cache/repair/handles_failure_test.dart | 56 - .../repair/handles_orphaned_binstub_test.dart | 36 - .../repair/recompiles_snapshots_test.dart | 45 - .../repair/reinstalls_git_packages_test.dart | 63 - .../reinstalls_hosted_packages_test.dart | 54 - .../cache/repair/updates_binstubs_test.dart | 61 - .../allows_import_in_dart_code_test.dart | 42 - ...iles_entrypoints_in_root_package_test.dart | 86 - .../compiles_generated_dart_file_test.dart | 33 - ...file_from_dependency_outside_web_test.dart | 42 - ...s_generated_file_from_dependency_test.dart | 44 - ...compiles_imported_generated_file_test.dart | 36 - ...nverts_isolate_entrypoint_in_web_test.dart | 34 - .../does_not_compile_if_disabled_test.dart | 24 - ...le_until_its_output_is_requested_test.dart | 31 - ...nvalid_command_line_options_type_test.dart | 31 - ...support_invalid_environment_type_test.dart | 31 - .../does_not_support_invalid_option_test.dart | 28 - ..._invalid_type_for_boolean_option_test.dart | 29 - ...ignores_entrypoint_in_dependency_test.dart | 28 - .../ignores_entrypoints_in_lib_test.dart | 36 - ...gnores_non_entrypoint_dart_files_test.dart | 44 - .../includes_source_maps_in_debug_test.dart | 40 - .../minifies_in_release_mode_test.dart | 24 - ...ify_configuration_overrides_mode_test.dart | 28 - .../omits_source_map_in_release_test.dart | 28 - ..._can_be_consumed_by_successive_phases.dart | 49 - .../outputs_deferred_libraries_test.dart | 71 - ...sses_along_environment_constants_test.dart | 35 - .../reports_dart_parse_errors_test.dart | 56 - ...nclude_core_libs_in_subdirectory_test.dart | 51 - .../source_maps_include_core_libs_test.dart | 72 - ...upports_configuration_with_build_test.dart | 95 - .../dart2js/supports_valid_options_test.dart | 42 - .../unminified_in_nonrelease_mode_test.dart | 24 - .../conservative_dependencies_test.dart | 522 ----- .../test/dependency_computer/cycle_test.dart | 266 --- .../dev_transformers_test.dart | 88 - .../test/dependency_computer/error_test.dart | 45 - .../import_dependencies_test.dart | 249 --- .../no_dependencies_test.dart | 204 -- .../transformers_needed_by_library_test.dart | 131 -- .../test/dependency_computer/utils.dart | 129 -- .../test/dependency_override_test.dart | 115 -- .../pub_generated/test/deps_test.dart | 140 -- .../pub_generated/test/descriptor.dart | 183 -- .../pub_generated/test/descriptor/git.dart | 76 - .../pub_generated/test/descriptor/tar.dart | 52 - .../test/dev_dependency_test.dart | 90 - .../does_not_show_other_versions_test.dart | 34 - .../doesnt_change_git_dependencies_test.dart | 37 - .../dry_run_does_not_apply_changes_test.dart | 48 - .../test/downgrade/unlock_dependers_test.dart | 48 - .../downgrade/unlock_if_necessary_test.dart | 47 - .../pub_generated/test/error_group_test.dart | 520 ----- .../test/get/broken_symlink_test.dart | 51 - .../cache_transformed_dependency_test.dart | 477 ----- .../dry_run_does_not_apply_changes_test.dart | 31 - .../get/git/check_out_and_upgrade_test.dart | 62 - .../test/get/git/check_out_branch_test.dart | 39 - .../test/get/git/check_out_revision_test.dart | 39 - .../test/get/git/check_out_test.dart | 38 - .../get/git/check_out_transitive_test.dart | 49 - .../test/get/git/check_out_twice_test.dart | 42 - ...nfetched_revision_of_cached_repo_test.dart | 71 - .../check_out_with_trailing_slash_test.dart | 44 - .../dependency_name_match_pubspec_test.dart | 32 - .../get/git/different_repo_name_test.dart | 36 - .../doesnt_fetch_if_nothing_changes_test.dart | 47 - .../test/get/git/lock_version_test.dart | 48 - .../locked_revision_without_repo_test.dart | 52 - .../get/git/require_pubspec_name_test.dart | 32 - .../test/get/git/require_pubspec_test.dart | 27 - .../git/stay_locked_if_compatible_test.dart | 50 - .../get/git/unlock_if_incompatible_test.dart | 48 - .../hosted/avoid_network_requests_test.dart | 61 - .../test/get/hosted/cached_pubspec_test.dart | 44 - ...t_upgrade_on_removed_constraints_test.dart | 51 - ...o_network_requests_when_possible_test.dart | 49 - .../test/get/hosted/get_test.dart | 42 - .../test/get/hosted/get_transitive_test.dart | 37 - ...age_with_busted_dev_dependencies_test.dart | 41 - .../get/hosted/resolve_constraints_test.dart | 44 - .../stay_locked_if_compatible_test.dart | 40 - .../stay_locked_if_new_is_satisfied_test.dart | 64 - .../test/get/hosted/stay_locked_test.dart | 45 - .../hosted/unlock_if_incompatible_test.dart | 37 - .../unlock_if_new_is_unsatisfied_test.dart | 73 - .../unlock_if_version_doesnt_exist_test.dart | 37 - .../test/get/path/absolute_path_test.dart | 36 - .../test/get/path/absolute_symlink_test.dart | 39 - .../test/get/path/empty_pubspec_test.dart | 28 - .../test/get/path/no_pubspec_test.dart | 27 - .../test/get/path/nonexistent_dir_test.dart | 27 - .../test/get/path/path_is_file_test.dart | 28 - .../test/get/path/relative_path_test.dart | 76 - .../test/get/path/relative_symlink_test.dart | 48 - .../path/shared_dependency_symlink_test.dart | 50 - .../test/get/path/shared_dependency_test.dart | 119 -- .../test/get/relative_symlink_test.dart | 52 - .../test/get/switch_source_test.dart | 40 - .../activate_git_after_hosted_test.dart | 48 - .../activate_hosted_after_git_test.dart | 46 - .../activate_hosted_after_path_test.dart | 46 - .../activate_path_after_hosted_test.dart | 40 - .../global/activate/bad_version_test.dart | 18 - .../global/activate/cached_package_test.dart | 35 - .../test/global/activate/constraint_test.dart | 30 - .../activate/constraint_with_path_test.dart | 18 - .../activate/different_version_test.dart | 30 - ...doesnt_snapshot_path_executables_test.dart | 37 - .../activate/empty_constraint_test.dart | 21 - .../global/activate/git_package_test.dart | 31 - .../activate/ignores_active_version_test.dart | 28 - .../installs_dependencies_for_git_test.dart | 30 - .../installs_dependencies_for_path_test.dart | 47 - .../activate/installs_dependencies_test.dart | 27 - .../activate/missing_git_repo_test.dart | 19 - .../activate/missing_package_arg_test.dart | 18 - .../activate/outdated_binstub_test.dart | 55 - .../global/activate/path_package_test.dart | 25 - .../reactivating_git_upgrades_test.dart | 40 - .../activate/removes_old_lockfile_test.dart | 39 - .../snapshots_git_executables_test.dart | 52 - .../snapshots_hosted_executables_test.dart | 50 - ...orts_version_solver_backtracking_test.dart | 38 - .../activate/uncached_package_test.dart | 36 - .../activate/unexpected_arguments_test.dart | 18 - .../global/activate/unknown_package_test.dart | 20 - .../binstub_runs_executable_test.dart | 60 - ...b_runs_global_run_if_no_snapshot_test.dart | 36 - ...instub_runs_precompiled_snapshot_test.dart | 35 - .../creates_executables_in_pubspec_test.dart | 44 - .../does_not_warn_if_no_executables_test.dart | 28 - .../does_not_warn_if_on_path_test.dart | 38 - ...licit_and_no_executables_options_test.dart | 29 - .../binstubs/explicit_executables_test.dart | 48 - .../global/binstubs/missing_script_test.dart | 31 - .../global/binstubs/name_collision_test.dart | 55 - .../name_collision_with_overwrite_test.dart | 55 - .../binstubs/no_executables_flag_test.dart | 31 - ...outdated_binstub_runs_pub_global_test.dart | 49 - .../binstubs/outdated_snapshot_test.dart | 62 - .../global/binstubs/path_package_test.dart | 35 - ...activate_removes_old_executables_test.dart | 47 - .../removes_even_if_not_in_pubspec_test.dart | 38 - .../removes_when_deactivated_test.dart | 39 - .../unknown_explicit_executable_test.dart | 40 - .../test/global/binstubs/utils.dart | 43 - .../binstubs/warns_if_not_on_path_test.dart | 27 - ...eactivate_and_reactivate_package_test.dart | 31 - .../global/deactivate/git_package_test.dart | 25 - .../deactivate/hosted_package_test.dart | 18 - .../deactivate/missing_package_arg_test.dart | 20 - .../global/deactivate/path_package_test.dart | 27 - .../removes_precompiled_snapshots_test.dart | 21 - .../deactivate/unexpected_arguments_test.dart | 20 - .../deactivate/unknown_package_test.dart | 18 - .../pub_generated/test/global/list_test.dart | 74 - .../run/errors_if_outside_bin_test.dart | 34 - .../run/implicit_executable_name_test.dart | 25 - .../run/missing_executable_arg_test.dart | 22 - .../global/run/missing_path_package_test.dart | 30 - .../test/global/run/mode_test.dart | 62 - .../global/run/nonexistent_script_test.dart | 21 - ...recompiles_if_sdk_is_out_of_date_test.dart | 54 - ...eflects_changes_to_local_package_test.dart | 25 - .../test/global/run/runs_git_script_test.dart | 25 - .../global/run/runs_path_script_test.dart | 23 - .../test/global/run/runs_script_test.dart | 25 - .../global/run/runs_transformer_test.dart | 49 - .../test/global/run/unknown_package_test.dart | 20 - .../global/run/uses_old_lockfile_test.dart | 50 - ...il_gracefully_on_missing_package_test.dart | 29 - .../fail_gracefully_on_url_resolve_test.dart | 31 - .../test/hosted/offline_test.dart | 76 - .../remove_removed_dependency_test.dart | 44 - ...ve_removed_transitive_dependency_test.dart | 57 - .../test/hosted/version_negotiation_test.dart | 69 - .../implicit_barback_dependency_test.dart | 173 -- .../test/implicit_dependency_test.dart | 140 -- .../_internal/pub_generated/test/io_test.dart | 371 ---- .../archives_and_uploads_a_package_test.dart | 44 - ...d_storage_upload_doesnt_redirect_test.dart | 33 - ...storage_upload_provides_an_error_test.dart | 41 - .../does_not_publish_if_private_test.dart | 23 - ...blish_if_private_with_server_arg_test.dart | 26 - ..._cannot_be_combined_with_dry_run_test.dart | 30 - ...orce_does_not_publish_if_private_test.dart | 23 - ..._not_publish_if_there_are_errors_test.dart | 30 - ..._tests_are_no_warnings_or_errors_test.dart | 40 - ..._publishes_if_there_are_warnings_test.dart | 49 - ...ation_provides_a_malformed_error_test.dart | 39 - ...ion_provides_a_malformed_success_test.dart | 39 - ...ckage_creation_provides_an_error_test.dart | 39 - ...e_creation_provides_invalid_json_test.dart | 33 - ...tion_has_a_warning_and_continues_test.dart | 44 - ...on_has_a_warning_and_is_canceled_test.dart | 29 - .../package_validation_has_an_error_test.dart | 30 - .../lish/preview_errors_if_private_test.dart | 23 - ...package_validation_has_a_warning_test.dart | 32 - ...ckage_validation_has_no_warnings_test.dart | 28 - ...er_arg_does_not_override_private_test.dart | 23 - ...ver_arg_overrides_publish_to_url_test.dart | 21 - ...rm_fields_has_a_non_string_value_test.dart | 36 - .../upload_form_fields_is_not_a_map_test.dart | 34 - .../upload_form_is_missing_fields_test.dart | 33 - .../lish/upload_form_is_missing_url_test.dart | 37 - .../upload_form_provides_an_error_test.dart | 36 - ...pload_form_provides_invalid_json_test.dart | 31 - .../upload_form_url_is_not_a_string_test.dart | 38 - .../test/lish/uses_publish_to_url_test.dart | 21 - .../pub_generated/test/lish/utils.dart | 49 - .../ignores_updated_pubspec_test.dart | 43 - .../includes_dev_dependencies_test.dart | 41 - .../lists_dependency_directories_test.dart | 50 - .../lockfile_error_test.dart | 25 - .../missing_pubspec_test.dart | 23 - .../list_package_dirs/no_lockfile_test.dart | 18 - .../list_package_dirs/pubspec_error_test.dart | 23 - .../pub_generated/test/lock_file_test.dart | 229 --- .../test/no_package_symlinks_test.dart | 125 -- .../pub_generated/test/oauth2/utils.dart | 58 - ..._credentials_authenticates_again_test.dart | 42 - ...redentials_does_not_authenticate_test.dart | 32 - ...efresh_token_authenticates_again_test.dart | 59 - ..._credentials_refreshes_and_saves_test.dart | 62 - ...efresh_token_authenticates_again_test.dart | 49 - ...henticates_and_saves_credentials_test.dart | 39 - ..._credentials_authenticates_again_test.dart | 42 - .../test/package_list_files_test.dart | 258 --- .../pub_generated/test/preprocess_test.dart | 306 --- .../test/pub_get_and_upgrade_test.dart | 155 -- .../pub_generated/test/pub_test.dart | 57 - .../pub_generated/test/pub_uploader_test.dart | 195 -- .../pub_generated/test/pubspec_test.dart | 558 ------ .../pub_generated/test/real_version_test.dart | 41 - .../test/run/allows_dart_extension_test.dart | 30 - .../run/app_can_read_from_stdin_test.dart | 38 - .../run/displays_transformer_logs_test.dart | 85 - ...oes_not_run_on_transformer_error_test.dart | 54 - ..._load_an_unnecessary_transformer_test.dart | 54 - ...errors_if_no_executable_is_given_test.dart | 25 - ...rs_if_only_transitive_dependency_test.dart | 37 - .../errors_if_path_in_dependency_test.dart | 33 - ...res_explicit_dart2js_transformer_test.dart | 21 - ...parent_directories_of_entrypoint_test.dart | 41 - .../pub_generated/test/run/mode_test.dart | 92 - .../test/run/nonexistent_dependency_test.dart | 19 - ...nonexistent_script_in_dependency_test.dart | 29 - .../test/run/nonexistent_script_test.dart | 20 - .../test/run/passes_along_arguments_test.dart | 28 - .../run/runs_a_generated_script_test.dart | 51 - ...s_app_in_directory_in_entrypoint_test.dart | 31 - .../test/run/runs_app_in_entrypoint_test.dart | 30 - .../runs_named_app_in_dependency_test.dart | 29 - ...runs_named_app_in_dev_dependency_test.dart | 32 - .../runs_the_script_in_checked_mode_test.dart | 28 - .../runs_transformer_in_entrypoint_test.dart | 37 - .../test/serve/404_page_test.dart | 45 - .../serve/allows_arbitrary_modes_test.dart | 49 - .../serve/defaults_to_debug_mode_test.dart | 49 - ...sed_dart_file_has_a_syntax_error_test.dart | 36 - ...first_if_a_dependency_is_removed_test.dart | 31 - ..._first_if_git_url_did_not_change_test.dart | 27 - ...first_if_locked_matches_override_test.dart | 36 - ..._first_if_locked_version_matches_test.dart | 40 - .../does_not_serve_dart_in_release_test.dart | 41 - .../does_not_serve_hidden_assets_test.dart | 29 - ...does_not_watch_compiled_js_files_test.dart | 40 - .../gets_first_if_dependency_added_test.dart | 31 - ...t_if_dependency_is_not_installed_test.dart | 34 - ...st_if_dependency_version_changed_test.dart | 42 - ..._first_if_dev_dependency_changed_test.dart | 34 - .../gets_first_if_git_ref_changed_test.dart | 54 - .../gets_first_if_git_url_changed_test.dart | 44 - .../serve/gets_first_if_no_lockfile_test.dart | 26 - ...first_if_path_dependency_changed_test.dart | 44 - .../gets_first_if_source_changed_test.dart | 40 - ...tive_dependency_is_not_installed_test.dart | 40 - .../test/serve/invalid_method_test.dart | 23 - .../test/serve/invalid_urls_test.dart | 40 - .../test/serve/missing_asset_test.dart | 22 - .../serve/missing_dependency_file_test.dart | 28 - .../test/serve/missing_file_test.dart | 45 - .../serve/native_watch_added_file_test.dart | 33 - .../native_watch_modified_file_test.dart | 32 - .../serve/native_watch_removed_file_test.dart | 37 - .../native_watch_replaced_file_test.dart | 57 - .../test/serve/serve_from_app_lib_test.dart | 33 - .../test/serve/serve_from_app_web_test.dart | 36 - .../serve/serve_from_dependency_lib_test.dart | 39 - .../serve/serves_file_with_space_test.dart | 29 - ...erves_index_html_for_directories_test.dart | 30 - ...ves_web_and_test_dirs_by_default_test.dart | 28 - .../supports_cross_origin_header_test.dart | 27 - ...r_defined_declaring_transformers_test.dart | 68 - ...s_user_defined_lazy_transformers_test.dart | 34 - .../test/serve/unknown_dependency_test.dart | 23 - .../uses_appropriate_mime_types_test.dart | 47 - .../pub_generated/test/serve/utils.dart | 491 ----- .../test/serve/watch_added_file_test.dart | 28 - .../test/serve/watch_modified_file_test.dart | 27 - .../test/serve/watch_removed_file_test.dart | 32 - .../serve/web_socket/exit_on_close_test.dart | 37 - .../web_socket/path_to_urls_errors_test.dart | 64 - .../serve/web_socket/path_to_urls_test.dart | 130 -- .../path_to_urls_with_line_test.dart | 32 - .../serve_directory_already_served_test.dart | 28 - ...ry_and_immediately_request_asset_test.dart | 41 - ...tory_and_immediately_serve_again_test.dart | 43 - ...irectory_and_immediately_unserve_test.dart | 54 - .../serve_directory_arg_errors_test.dart | 54 - .../serve_directory_overlapping_test.dart | 39 - .../web_socket/serve_directory_test.dart | 46 - .../unserve_directory_arg_errors_test.dart | 54 - .../unserve_directory_not_served_test.dart | 27 - .../web_socket/unserve_directory_test.dart | 41 - .../url_to_asset_id_errors_test.dart | 34 - .../web_socket/url_to_asset_id_test.dart | 111 -- .../url_to_asset_id_with_line_test.dart | 32 - .../pub_generated/test/serve_packages.dart | 192 -- ...for_immediate_and_transitive_dep_test.dart | 64 - .../snapshot/creates_a_snapshot_test.dart | 60 - ...snt_load_irrelevant_transformers_test.dart | 63 - ...t_when_a_dependency_is_unchanged_test.dart | 43 - ...napshot_an_entrypoint_dependency_test.dart | 39 - .../doesnt_snapshot_path_dependency_test.dart | 37 - ...snapshot_transitive_dependencies_test.dart | 37 - ...ints_errors_for_broken_snapshots_test.dart | 66 - ...mpiles_if_the_sdk_is_out_of_date_test.dart | 53 - .../snapshots_transformed_code_test.dart | 69 - ...ates_snapshot_for_git_dependency_test.dart | 55 - ...upgrades_snapshot_for_dependency_test.dart | 59 - .../test/snapshot/upgrades_snapshot_test.dart | 52 - .../pub_generated/test/test_pub.dart | 1015 ---------- .../pub_generated/test/transcript_test.dart | 60 - ...a_transformer_rejects_its_config_test.dart | 56 - ..._found_exceptions_are_detectable_test.dart | 65 - .../test/transformer/cache_test.dart | 341 ---- .../transformer/can_log_messages_test.dart | 117 -- .../can_use_consume_primary_test.dart | 51 - .../transformer/can_use_has_input_test.dart | 53 - .../can_use_read_input_as_string_test.dart | 49 - .../transformer/can_use_read_input_test.dart | 50 - ...figuration_defaults_to_empty_map_test.dart | 54 - ...s_configuration_to_a_transformer_test.dart | 60 - ...tiates_configurable_transformers_test.dart | 76 - ...ormer_before_another_transformer_test.dart | 30 - ...m_on_an_input_in_another_package_test.dart | 39 - .../exclusion/exclude_asset_glob_test.dart | 40 - .../exclusion/exclude_asset_list_test.dart | 40 - .../exclusion/exclude_asset_prefix_test.dart | 42 - .../exclusion/exclude_asset_string_test.dart | 40 - .../exclusion/include_asset_glob_test.dart | 40 - .../exclusion/include_asset_list_test.dart | 40 - .../exclusion/include_asset_prefix_test.dart | 42 - .../exclusion/include_asset_string_test.dart | 40 - .../includes_before_excludes_test.dart | 41 - .../works_on_aggregate_transformer_test.dart | 67 - .../exclusion/works_on_dart2js_test.dart | 51 - .../works_on_lazy_transformer_test.dart | 49 - .../works_on_transformer_group_test.dart | 60 - ..._file_that_defines_no_transforms_test.dart | 34 - ...to_load_a_non_existent_transform_test.dart | 26 - ...ubspec_with_reserved_transformer_test.dart | 37 - ..._transform_from_a_non_dependency_test.dart | 28 - ..._a_transform_with_a_syntax_error_test.dart | 37 - ...a_transform_with_an_import_error_test.dart | 39 - ...ransformer_when_config_is_passed_test.dart | 40 - ..._declaring_aggregate_transformer_test.dart | 69 - ...ond_transformer_dependency_graph_test.dart | 78 - ...ads_a_lazy_aggregate_transformer_test.dart | 65 - ...r_defined_in_an_exported_library_test.dart | 33 - .../loads_an_aggregate_transformer_test.dart | 56 - ...igurations_from_the_same_isolate_test.dart | 90 - ...transformers_reject_their_config_test.dart | 72 - ...fers_transformer_to_library_name_test.dart | 53 - ...rints_a_transform_error_in_apply_test.dart | 45 - ...ints_a_transform_interface_error_test.dart | 44 - ...sform_on_the_application_package_test.dart | 29 - ...sform_on_the_application_package_test.dart | 38 - ...ansformer_on_a_local_transformer_test.dart | 42 - .../runs_a_transformer_group_test.dart | 48 - ...ns_a_transformer_on_a_dependency_test.dart | 39 - ...ird_party_transformer_on_another_test.dart | 53 - ...ormer_that_doesnt_return_futures_test.dart | 50 - .../test/unknown_source_test.dart | 81 - .../dry_run_does_not_apply_changes_test.dart | 48 - .../git/do_not_upgrade_if_unneeded_test.dart | 64 - .../test/upgrade/git/upgrade_locked_test.dart | 52 - .../upgrade/git/upgrade_one_locked_test.dart | 52 - .../upgrade_to_incompatible_pubspec_test.dart | 42 - .../upgrade_to_nonexistent_pubspec_test.dart | 42 - .../upgrade/hosted/unlock_dependers_test.dart | 48 - .../hosted/unlock_if_necessary_test.dart | 47 - .../upgrade_removed_constraints_test.dart | 49 - .../upgrade/report/describes_change_test.dart | 69 - ...wer_versions_for_locked_packages_test.dart | 46 - .../report/highlights_overrides_test.dart | 28 - .../leading_character_shows_change_test.dart | 95 - .../shows_newer_available_versions_test.dart | 52 - ...s_number_of_changed_dependencies_test.dart | 40 - .../pub_generated/test/utils_test.dart | 105 - .../test/validator/compiled_dartdoc_test.dart | 116 -- .../validator/dependency_override_test.dart | 28 - .../test/validator/dependency_test.dart | 411 ---- .../test/validator/directory_test.dart | 52 - .../test/validator/executable_test.dart | 54 - .../test/validator/license_test.dart | 52 - .../test/validator/name_test.dart | 122 -- .../test/validator/pubspec_field_test.dart | 172 -- .../test/validator/sdk_constraint_test.dart | 48 - .../test/validator/size_test.dart | 32 - .../test/validator/utf8_readme_test.dart | 43 - .../pub_generated/test/validator/utils.dart | 25 - .../test/version_solver_test.dart | 1720 ----------------- tests/lib/analyzer/analyze_library.status | 8 - tools/run_pub.py | 5 +- tools/status_clean.dart | 3 +- tools/testing/dart/test_configurations.dart | 2 +- utils/pub/pub.gyp | 4 +- 574 files changed, 14 insertions(+), 49751 deletions(-) delete mode 100644 sdk/lib/_internal/pub/bin/async_compile.dart delete mode 100644 sdk/lib/_internal/pub/test/async_compile_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/README.md delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/serialize.dart delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/serialize/aggregate_transform.dart delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/serialize/exception.dart delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/serialize/get_input_transform.dart delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/serialize/transform.dart delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/serialize/transformer.dart delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/transformer_isolate.dart delete mode 100644 sdk/lib/_internal/pub_generated/asset/dart/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/bin/async_compile.dart delete mode 100644 sdk/lib/_internal/pub_generated/bin/pub.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/ascii_tree.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/admin_server.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/asset_environment.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/barback_server.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/base_server.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/cycle_exception.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/dart2js_transformer.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/dart_forwarding_transformer.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/dependency_computer.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/excluding_aggregate_transformer.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/excluding_transformer.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/foreign_transformer.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/load_all_transformers.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/pub_package_provider.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/source_directory.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/transformer_cache.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/transformer_config.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/transformer_id.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/transformer_isolate.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/transformer_loader.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/barback/web_socket_api.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/cached_package.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/barback.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/build.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/cache.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/cache_add.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/cache_list.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/cache_repair.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/deps.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/downgrade.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/get.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/global.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/global_activate.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/global_deactivate.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/global_list.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/global_run.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/lish.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/list_package_dirs.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/run.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/serve.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/upgrade.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/uploader.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command/version.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/command_runner.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/dart.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/entrypoint.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/error_group.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/exceptions.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/executable.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/exit_codes.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/git.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/global_packages.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/http.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/io.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/lock_file.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/log.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/oauth2.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/package.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/package_graph.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/preprocess.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/progress.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/pubspec.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/sdk.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/solver/backtracking_solver.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/solver/dependency_queue.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/solver/solve_report.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/solver/version_queue.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/solver/version_solver.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/source.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/source/cached.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/source/git.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/source/hosted.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/source/path.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/source/unknown.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/source_registry.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/system_cache.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/transcript.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/compiled_dartdoc.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/dependency.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/dependency_override.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/directory.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/executable.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/license.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/name.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/pubspec_field.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/sdk_constraint.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/size.dart delete mode 100644 sdk/lib/_internal/pub_generated/lib/src/validator/utf8_readme.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/ascii_tree_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/async_compile_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/all_includes_all_default_directories_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/directory_args_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/fails_if_args_with_all_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_arg_does_not_exist_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_outside_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/fails_if_no_default_dirs_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/fails_on_all_with_no_buildable_directories_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/fails_on_disallowed_directories_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/fails_on_overlapping_directories_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/subdirectories_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/barback/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/allows_arbitrary_modes_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/can_specify_output_directory_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/cleans_entire_build_directory_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/copies_browser_js_next_to_entrypoints_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dependency_override_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dev_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/copies_non_dart_files_to_build_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/defaults_to_release_mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/handles_long_paths_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/includes_assets_from_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/includes_dart_files_from_dependencies_in_debug_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/includes_dart_files_in_debug_mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/outputs_error_to_json_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/outputs_results_to_json_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/preserves_htaccess_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/build/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_matching_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/all_adds_all_matching_versions_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/all_with_some_versions_present_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/already_cached_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/bad_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/missing_package_arg_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/no_matching_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/package_not_found_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/add/unexpected_arguments_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/list_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/empty_cache_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_binstub_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_global_lockfile_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/handles_failure_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/handles_orphaned_binstub_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/recompiles_snapshots_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_git_packages_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_hosted_packages_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/cache/repair/updates_binstubs_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/allows_import_in_dart_code_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/compiles_entrypoints_in_root_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_dart_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_outside_web_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/compiles_imported_generated_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/converts_isolate_entrypoint_in_web_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_if_disabled_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_until_its_output_is_requested_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_command_line_options_type_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_environment_type_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_option_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/doesnt_support_invalid_type_for_boolean_option_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoint_in_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoints_in_lib_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/ignores_non_entrypoint_dart_files_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_in_debug_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/minifies_in_release_mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/minify_configuration_overrides_mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_in_release_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/output_can_be_consumed_by_successive_phases.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/outputs_deferred_libraries_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/passes_along_environment_constants_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/reports_dart_parse_errors_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_in_subdirectory_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/supports_configuration_with_build_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/supports_valid_options_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dart2js/unminified_in_nonrelease_mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/conservative_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/cycle_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/dev_transformers_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/import_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/no_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/transformers_needed_by_library_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_computer/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dependency_override_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/deps_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/descriptor.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/descriptor/git.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/descriptor/tar.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/dev_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/downgrade/does_not_show_other_versions_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/downgrade/doesnt_change_git_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/downgrade/dry_run_does_not_apply_changes_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/downgrade/unlock_dependers_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/downgrade/unlock_if_necessary_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/error_group_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/broken_symlink_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/cache_transformed_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/dry_run_does_not_apply_changes_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_and_upgrade_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_branch_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_revision_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_transitive_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_twice_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_unfetched_revision_of_cached_repo_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/check_out_with_trailing_slash_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/dependency_name_match_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/different_repo_name_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/doesnt_fetch_if_nothing_changes_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/lock_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/locked_revision_without_repo_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_name_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/stay_locked_if_compatible_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/git/unlock_if_incompatible_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/avoid_network_requests_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/cached_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/do_not_upgrade_on_removed_constraints_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/does_no_network_requests_when_possible_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/get_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/get_transitive_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/gets_a_package_with_busted_dev_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/resolve_constraints_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_compatible_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_new_is_satisfied_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_incompatible_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_new_is_unsatisfied_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_version_doesnt_exist_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/absolute_path_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/absolute_symlink_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/empty_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/no_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/nonexistent_dir_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/path_is_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/relative_path_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/relative_symlink_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_symlink_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/relative_symlink_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/get/switch_source_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/activate_git_after_hosted_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_git_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_path_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/activate_path_after_hosted_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/bad_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/cached_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/constraint_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/constraint_with_path_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/different_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/doesnt_snapshot_path_executables_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/empty_constraint_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/git_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/ignores_active_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_git_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_path_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/missing_git_repo_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/missing_package_arg_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/outdated_binstub_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/path_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/reactivating_git_upgrades_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/removes_old_lockfile_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/snapshots_git_executables_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/snapshots_hosted_executables_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/supports_version_solver_backtracking_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/uncached_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/unexpected_arguments_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/activate/unknown_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_executable_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_global_run_if_no_snapshot_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_precompiled_snapshot_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/creates_executables_in_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_no_executables_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_on_path_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_and_no_executables_options_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_executables_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/missing_script_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_with_overwrite_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/no_executables_flag_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_binstub_runs_pub_global_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_snapshot_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/path_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/reactivate_removes_old_executables_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/removes_even_if_not_in_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/removes_when_deactivated_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/unknown_explicit_executable_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/binstubs/warns_if_not_on_path_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/deactivate_and_reactivate_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/git_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/hosted_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/missing_package_arg_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/path_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/removes_precompiled_snapshots_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/unexpected_arguments_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/deactivate/unknown_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/list_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/errors_if_outside_bin_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/implicit_executable_name_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/missing_executable_arg_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/missing_path_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/nonexistent_script_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/recompiles_if_sdk_is_out_of_date_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/reflects_changes_to_local_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/runs_git_script_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/runs_path_script_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/runs_script_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/runs_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/unknown_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/global/run/uses_old_lockfile_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_missing_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_url_resolve_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/hosted/offline_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/hosted/remove_removed_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/hosted/remove_removed_transitive_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/hosted/version_negotiation_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/implicit_barback_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/implicit_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/io_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/archives_and_uploads_a_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_doesnt_redirect_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_provides_an_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_with_server_arg_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/force_cannot_be_combined_with_dry_run_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_private_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_there_are_errors_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_tests_are_no_warnings_or_errors_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_there_are_warnings_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_success_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_an_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_invalid_json_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_continues_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_is_canceled_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/package_validation_has_an_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/preview_errors_if_private_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_a_warning_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_no_warnings_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/server_arg_does_not_override_private_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/server_arg_overrides_publish_to_url_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_has_a_non_string_value_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_is_not_a_map_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_fields_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_url_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_an_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_invalid_json_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/upload_form_url_is_not_a_string_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/uses_publish_to_url_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lish/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/list_package_dirs/ignores_updated_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/list_package_dirs/includes_dev_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/list_package_dirs/lists_dependency_directories_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/list_package_dirs/lockfile_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/list_package_dirs/missing_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/list_package_dirs/no_lockfile_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/list_package_dirs/pubspec_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/lock_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/no_package_symlinks_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/with_a_malformed_credentials_authenticates_again_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/with_a_pre_existing_credentials_does_not_authenticate_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/with_a_server_rejected_refresh_token_authenticates_again_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_refreshes_and_saves_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_without_a_refresh_token_authenticates_again_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/with_no_credentials_authenticates_and_saves_credentials_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/oauth2/with_server_rejected_credentials_authenticates_again_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/package_list_files_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/preprocess_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/pub_get_and_upgrade_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/pub_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/pub_uploader_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/real_version_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/allows_dart_extension_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/app_can_read_from_stdin_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/displays_transformer_logs_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/does_not_run_on_transformer_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/doesnt_load_an_unnecessary_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/errors_if_no_executable_is_given_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/errors_if_only_transitive_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/errors_if_path_in_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/ignores_explicit_dart2js_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/includes_parent_directories_of_entrypoint_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/nonexistent_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/nonexistent_script_in_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/nonexistent_script_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/passes_along_arguments_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/runs_a_generated_script_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/runs_app_in_directory_in_entrypoint_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/runs_app_in_entrypoint_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dev_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/runs_the_script_in_checked_mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/run/runs_transformer_in_entrypoint_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/404_page_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/allows_arbitrary_modes_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/defaults_to_debug_mode_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_crash_if_an_unused_dart_file_has_a_syntax_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_a_dependency_is_removed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_git_url_did_not_change_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_matches_override_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_version_matches_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_serve_dart_in_release_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_serve_hidden_assets_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/does_not_watch_compiled_js_files_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_added_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_is_not_installed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_version_changed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dev_dependency_changed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_ref_changed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_url_changed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_no_lockfile_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_path_dependency_changed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_source_changed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/gets_first_if_transitive_dependency_is_not_installed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/invalid_method_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/invalid_urls_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/missing_asset_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/missing_dependency_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/missing_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/native_watch_added_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/native_watch_modified_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/native_watch_removed_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/native_watch_replaced_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/serve_from_app_lib_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/serve_from_app_web_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/serve_from_dependency_lib_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/serves_file_with_space_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/serves_index_html_for_directories_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/serves_web_and_test_dirs_by_default_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/supports_cross_origin_header_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_declaring_transformers_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_lazy_transformers_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/unknown_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/uses_appropriate_mime_types_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/watch_added_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/watch_modified_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/watch_removed_file_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/exit_on_close_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_errors_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_with_line_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_already_served_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_request_asset_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_serve_again_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_unserve_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_arg_errors_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_overlapping_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_arg_errors_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_not_served_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_errors_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_with_line_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/serve_packages.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_for_immediate_and_transitive_dep_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/doesnt_load_irrelevant_transformers_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/doesnt_resnapshot_when_a_dependency_is_unchanged_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_an_entrypoint_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_path_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_transitive_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/prints_errors_for_broken_snapshots_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/recompiles_if_the_sdk_is_out_of_date_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/snapshots_transformed_code_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/updates_snapshot_for_git_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_for_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/test_pub.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transcript_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/a_transformer_rejects_its_config_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/asset_not_found_exceptions_are_detectable_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/cache_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/can_log_messages_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/can_use_consume_primary_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/can_use_has_input_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_as_string_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/configuration/configuration_defaults_to_empty_map_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/configuration/passes_configuration_to_a_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/configuration/with_configuration_only_instantiates_configurable_transformers_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/dart2js_transformer_before_another_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/does_not_run_a_transform_on_an_input_in_another_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_glob_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_list_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_prefix_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_string_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_glob_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_list_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_prefix_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_string_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/includes_before_excludes_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_aggregate_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_dart2js_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_lazy_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_transformer_group_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_file_that_defines_no_transforms_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_non_existent_transform_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_pubspec_with_reserved_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_from_a_non_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_a_syntax_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_an_import_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_an_unconfigurable_transformer_when_config_is_passed_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/loads_a_declaring_aggregate_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/loads_a_diamond_transformer_dependency_graph_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/loads_a_lazy_aggregate_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/loads_a_transformer_defined_in_an_exported_library_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/loads_an_aggregate_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/loads_different_configurations_from_the_same_isolate_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/multiple_transformers_reject_their_config_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/prefers_transformer_to_library_name_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_error_in_apply_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_interface_error_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/runs_a_local_transform_on_the_application_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transform_on_the_application_package_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transformer_on_a_local_transformer_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_group_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_on_a_dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/runs_one_third_party_transformer_on_another_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/transformer/supports_a_transformer_that_doesnt_return_futures_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/unknown_source_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/dry_run_does_not_apply_changes_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/git/do_not_upgrade_if_unneeded_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_locked_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_one_locked_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_incompatible_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_nonexistent_pubspec_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_dependers_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_if_necessary_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/hosted/upgrade_removed_constraints_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/report/describes_change_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/report/does_not_show_newer_versions_for_locked_packages_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/report/highlights_overrides_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/report/leading_character_shows_change_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/report/shows_newer_available_versions_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/upgrade/report/shows_number_of_changed_dependencies_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/utils_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/compiled_dartdoc_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/dependency_override_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/dependency_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/directory_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/executable_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/license_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/name_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/pubspec_field_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/sdk_constraint_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/size_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/utf8_readme_test.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/validator/utils.dart delete mode 100644 sdk/lib/_internal/pub_generated/test/version_solver_test.dart diff --git a/create_sdk.gyp b/create_sdk.gyp index 17b3ce24c85..721066a0813 100644 --- a/create_sdk.gyp +++ b/create_sdk.gyp @@ -24,9 +24,9 @@ # the pub directory instead of in tests/pub. Xcode can only handle # a certain amount of files in one list (also depending on the # length of the path from where you run). This regexp excludes - # pub/test and pub_generated/test + # pub/test '> - -(Note: this file is also parsed by a tool to update the above commit, so be -careful not to reformat it.) -"""; - -/// This runs the async/await compiler on all of the pub source code. -/// -/// It reads from the repo and writes the compiled output into the given build -/// directory (using the same file names and relative layout). Does not -/// compile files that haven't changed since the last time they were compiled. -// TODO(rnystrom): Remove this when #104 is fixed. -void main(List arguments) { - var parser = new ArgParser(allowTrailingOptions: true); - - parser.addFlag("verbose", callback: (value) => verbose = value); - - var force = false; - parser.addFlag("force", callback: (value) => force = value); - - var buildDir; - parser.addOption("snapshot-build-dir", callback: (value) => buildDir = value); - - try { - var rest = parser.parse(arguments).rest; - if (rest.isEmpty) { - throw new FormatException('Missing generated directory.'); - } else if (rest.length > 1) { - throw new FormatException( - 'Unexpected arguments: ${rest.skip(1).join(" ")}.'); - } - - generatedDir = rest.first; - } on FormatException catch(ex) { - stderr.writeln(ex); - stderr.writeln(); - stderr.writeln( - "Usage: dart async_compile.dart [--verbose] [--force] " - "[--snapshot-build-dir ] "); - exit(64); - } - - // See what version (i.e. Git commit) of the async-await compiler we - // currently have. If this is different from the version that was used to - // compile the sources, recompile everything. - var currentCommit = _getCurrentCommit(); - - var readmePath = p.join(generatedDir, "README.md"); - var lastCommit; - try { - var readme = new File(readmePath).readAsStringSync(); - var match = _commitPattern.firstMatch(readme); - if (match == null) { - stderr.writeln("Could not find compiler commit hash in README.md."); - exit(1); - } - - lastCommit = match[0]; - } on IOException catch (error, stackTrace) { - if (verbose) { - stderr.writeln("Failed to load $readmePath: $error\n" - "${new Trace.from(stackTrace)}"); - } - } - - var numFiles = 0; - var numCompiled = 0; - - // Compile any modified or missing files. - var sources = new Set(); - for (var entry in new Directory(sourceDir).listSync(recursive: true)) { - if (p.extension(entry.path) != ".dart") continue; - - numFiles++; - var relative = p.relative(entry.path, from: sourceDir); - sources.add(relative); - - var sourceFile = entry as File; - var destPath = p.join(generatedDir, relative); - var destFile = new File(destPath); - if (force || - currentCommit != lastCommit || - !destFile.existsSync() || - entry.lastModifiedSync().isAfter(destFile.lastModifiedSync())) { - _compile(sourceFile.path, sourceFile.readAsStringSync(), destPath); - numCompiled++; - if (verbose) print("Compiled $relative"); - } - } - - // Delete any previously compiled files whose source no longer exists. - for (var entry in new Directory(generatedDir).listSync(recursive: true)) { - if (p.extension(entry.path) != ".dart") continue; - - var relative = p.relative(entry.path, from: generatedDir); - - if (!sources.contains(relative)) { - _deleteFile(entry.path); - if (verbose) print("Deleted $relative"); - } - } - - // Update the README. - if (currentCommit != lastCommit) { - _writeFile(readmePath, _README.replaceAll("<>", currentCommit)); - if (verbose) print("Updated README.md"); - } - - if (numCompiled > 0 && buildDir != null) _generateSnapshot(buildDir); - - if (verbose) print("Compiled $numCompiled out of $numFiles files"); - - if (hadFailure) exit(1); -} - -String _getCurrentCommit() { - var command = "git"; - var args = ["rev-parse", "HEAD"]; - - // Spawning a process on Windows will not look for the executable in the - // system path so spawn git through a shell to find it. - if (Platform.operatingSystem == "windows") { - command = "cmd"; - args = ["/c", "git"]..addAll(args); - } - - var result = Process.runSync(command, args, workingDirectory: - p.join(sourceDir, "../../../../third_party/pkg/async_await")); - if (result.exitCode != 0) { - stderr.writeln("Could not get Git revision of async_await compiler."); - exit(1); - } - - return result.stdout.trim(); -} - -void _compile(String sourcePath, String source, String destPath) { - var destDir = new Directory(p.dirname(destPath)); - destDir.createSync(recursive: true); - - source = _translateAsyncAwait(sourcePath, source); - if (source != null) source = _fixDart2jsImports(sourcePath, source, destPath); - - if (source == null) { - // If the async compile fails, delete the file so that we don't try to - // run the stale previous output and so that we try to recompile it later. - _deleteFile(destPath); - } else { - _writeFile(destPath, source); - } -} - -/// Runs the async/await compiler on [source]. -/// -/// Returns the translated Dart code or `null` if the compiler failed. -String _translateAsyncAwait(String sourcePath, String source) { - if (p.isWithin(p.join(sourceDir, "asset"), sourcePath)) { - // Don't run the async compiler on the special "asset" source files. These - // have preprocessor comments that get discarded by the compiler. - return source; - } - - try { - source = async_await.compile(source); - - // Reformat the result since the compiler ditches all whitespace. - // TODO(rnystrom): Remove when this is fixed: - // https://github.com/dart-lang/async_await/issues/12 - var result = new CodeFormatter().format(CodeKind.COMPILATION_UNIT, source); - return result.source; - } catch (ex) { - stderr.writeln("Async compile failed on $sourcePath:\n$ex"); - hadFailure = true; - return null; - } -} - -/// Fix relative imports to dart2js libraries. -/// -/// Pub imports dart2js using relative imports that reach outside of pub's -/// source tree. Since the build directory is in a different location, we need -/// to fix those to be valid relative imports from the build directory. -String _fixDart2jsImports(String sourcePath, String source, String destPath) { - var compilerDir = p.url.join(sourceUrl, "../compiler"); - var relative = p.url.relative(compilerDir, - from: p.url.dirname(p.toUri(destPath).toString())); - return source.replaceAll(_compilerPattern, "import '$relative"); -} - -/// Regenerate the pub snapshot from the async/await-compiled output. We do -/// this here since the tests need it and it's faster than doing a full SDK -/// build. -void _generateSnapshot(String buildDir) { - buildDir = p.normalize(buildDir); - new Directory(buildDir).createSync(recursive: true); - - var entrypoint = p.join(generatedDir, 'bin/pub.dart'); - var packageRoot = p.join(buildDir, 'packages'); - var snapshot = p.join(buildDir, 'dart-sdk/bin/snapshots/pub.dart.snapshot'); - - var result = Process.runSync(Platform.executable, [ - "--package-root=$packageRoot", - "--snapshot=$snapshot", - entrypoint - ]); - - if (result.exitCode != 0) { - stderr.writeln("Failed to generate snapshot:"); - if (result.stderr.trim().isNotEmpty) stderr.writeln(result.stderr); - if (result.stdout.trim().isNotEmpty) stderr.writeln(result.stdout); - exit(result.exitCode); - } - - if (verbose) print("Created pub snapshot"); -} - -/// Deletes the file at [path], ignoring any IO errors that occur. -/// -/// This swallows errors to accommodate multiple compilers running concurrently. -/// Since they will produce the same output anyway, a failure of one is fine. -void _deleteFile(String path) { - try { - new File(path).deleteSync(); - } on IOException catch (ex) { - // Do nothing. - } -} - -/// Writes [contents] to [path], ignoring any IO errors that occur. -/// -/// This swallows errors to accommodate multiple compilers running concurrently. -/// Since they will produce the same output anyway, a failure of one is fine. -void _writeFile(String path, String contents) { - try { - new File(path).writeAsStringSync(contents); - } on IOException catch (ex) { - // Do nothing. - } -} diff --git a/sdk/lib/_internal/pub/test/async_compile_test.dart b/sdk/lib/_internal/pub/test/async_compile_test.dart deleted file mode 100644 index a3216d7c32b..00000000000 --- a/sdk/lib/_internal/pub/test/async_compile_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/descriptor.dart' as d; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_process.dart'; - -import 'test_pub.dart'; -import '../lib/src/io.dart'; - -void main() { - integration("the generated pub source is up to date", () { - var compilerArgs = Platform.executableArguments.toList()..addAll([ - p.join(pubRoot, 'bin', 'async_compile.dart'), - '--force', '--verbose', - p.join(sandboxDir, "pub_generated") - ]); - - new ScheduledProcess.start(Platform.executable, compilerArgs).shouldExit(0); - - new d.DirectoryDescriptor.fromFilesystem("pub_generated", - p.join(pubRoot, "..", "pub_generated")).validate(); - }); -} diff --git a/sdk/lib/_internal/pub/test/test_pub.dart b/sdk/lib/_internal/pub/test/test_pub.dart index 4b6afb3408f..cb555a085dc 100644 --- a/sdk/lib/_internal/pub/test/test_pub.dart +++ b/sdk/lib/_internal/pub/test/test_pub.dart @@ -809,16 +809,8 @@ Map packageMap(String name, String version, [Map dependencies]) { } /// Resolves [target] relative to the path to pub's `test/asset` directory. -String testAssetPath(String target) { - var libPath = libraryPath('test_pub'); - - // We are running from the generated directory, but non-dart assets are only - // in the canonical directory. - // TODO(rnystrom): Remove this when #104 is fixed. - libPath = libPath.replaceAll('pub_generated', 'pub'); - - return p.join(p.dirname(libPath), 'asset', target); -} +String testAssetPath(String target) => + p.join(p.dirname(libraryPath('test_pub')), 'asset', target); /// Returns a Map in the format used by the pub.dartlang.org API to represent a /// package version. diff --git a/sdk/lib/_internal/pub_generated/README.md b/sdk/lib/_internal/pub_generated/README.md deleted file mode 100644 index 903a085c0ea..00000000000 --- a/sdk/lib/_internal/pub_generated/README.md +++ /dev/null @@ -1,18 +0,0 @@ -Pub is currently dogfooding the new Dart async/await syntax. Since the Dart VM -doesn't natively support it yet, we are using the [async-await][] compiler -package. - -[async-await]: https://github.com/dart-lang/async_await - -We run that to compile pub-using-await from sdk/lib/_internal/pub down to -vanilla Dart code which is what you see here. To interoperate more easily with -the rest of the repositry, we check in that generated code. - -When bug #104 is fixed, we can remove this entirely. - -The code here was compiled using the async-await compiler at commit: - - 8b401a9f2e5e81dca5f70dbe7564112a0823dee6 - -(Note: this file is also parsed by a tool to update the above commit, so be -careful not to reformat it.) diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize.dart deleted file mode 100644 index f37ab70a179..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/serialize.dart +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.asset.serialize; - -import 'dart:async'; -import 'dart:isolate'; - -import 'package:barback/barback.dart'; - -//# if source_maps >=0.9.0 <0.10.0 -//> import 'package:source_maps/span.dart'; -//# end - -//# if source_span -import 'package:source_span/source_span.dart'; -//# end - -import 'serialize/exception.dart'; -import 'utils.dart'; - -export 'serialize/aggregate_transform.dart'; -export 'serialize/exception.dart'; -export 'serialize/transform.dart'; -export 'serialize/transformer.dart'; - -/// Converts [id] into a serializable map. -Map serializeId(AssetId id) => {'package': id.package, 'path': id.path}; - -/// Converts a serializable map into an [AssetId]. -AssetId deserializeId(Map id) => new AssetId(id['package'], id['path']); - -/// Converts [span] into a serializable map. -/// -/// [span] may be a [SourceSpan] or a [Span]. -Map serializeSpan(span) { - // TODO(nweiz): convert FileSpans to FileSpans. - // Handily, this code works for both source_map and source_span spans. - return { - 'sourceUrl': span.sourceUrl.toString(), - 'start': serializeLocation(span.start), - 'end': serializeLocation(span.end), - 'text': span.text, - }; -} - -/// Converts a serializable map into a [SourceSpan]. -SourceSpan deserializeSpan(Map span) { - return new SourceSpan( - deserializeLocation(span['start']), - deserializeLocation(span['end']), - span['text']); -} - -/// Converts [location] into a serializable map. -/// -/// [location] may be a [SourceLocation] or a [SourceLocation]. -Map serializeLocation(location) { -//# if source_maps >=0.9.0 <0.10.0 -//> if (location is Location) { -//> return { -//> 'sourceUrl': location.sourceUrl, -//> 'offset': location.offset, -//> 'line': location.line, -//> 'column': location.column -//> }; -//> } -//# end - -//# if source_span - // TODO(nweiz): convert FileLocations to FileLocations. - if (location is SourceLocation) { - return { - 'sourceUrl': location.sourceUrl.toString(), - 'offset': location.offset, - 'line': location.line, - 'column': location.column - }; - } -//# end - - throw new ArgumentError("Unknown type ${location.runtimeType} for location."); -} - -/// Converts a serializable map into a [Location]. -SourceLocation deserializeLocation(Map location) { - return new SourceLocation(location['offset'], - sourceUrl: location['sourceUrl'], - line: location['line'], - column: location['column']); -} - -/// Converts [stream] into a serializable map. -/// -/// [serializeEvent] is used to serialize each event from the stream. -Map serializeStream(Stream stream, serializeEvent(event)) { - var receivePort = new ReceivePort(); - var map = {'replyTo': receivePort.sendPort}; - - receivePort.first.then((message) { - var sendPort = message['replyTo']; - stream.listen((event) { - sendPort.send({ - 'type': 'event', - 'value': serializeEvent(event) - }); - }, onError: (error, stackTrace) { - sendPort.send({ - 'type': 'error', - 'error': serializeException(error, stackTrace) - }); - }, onDone: () => sendPort.send({'type': 'done'})); - }); - - return map; -} - -/// Converts a serializable map into a [Stream]. -/// -/// [deserializeEvent] is used to deserialize each event from the stream. -Stream deserializeStream(Map stream, deserializeEvent(event)) { - return callbackStream(() { - var receivePort = new ReceivePort(); - stream['replyTo'].send({'replyTo': receivePort.sendPort}); - - var controller = new StreamController(sync: true); - receivePort.listen((event) { - switch (event['type']) { - case 'event': - controller.add(deserializeEvent(event['value'])); - break; - case 'error': - var exception = deserializeException(event['error']); - controller.addError(exception, exception.stackTrace); - break; - case 'done': - controller.close(); - receivePort.close(); - break; - } - }); - - return controller.stream; - }); -} - -/// Wraps [message] and sends it across [port], then waits for a response which -/// should be sent using [respond]. -/// -/// The returned Future will complete to the value or error returned by -/// [respond]. -Future call(SendPort port, message) { - var receivePort = new ReceivePort(); - port.send({ - 'message': message, - 'replyTo': receivePort.sendPort - }); - - return receivePort.first.then((response) { - if (response['type'] == 'success') return response['value']; - assert(response['type'] == 'error'); - var exception = deserializeException(response['error']); - return new Future.error(exception, exception.stackTrace); - }); -} - -/// Responds to a message sent by [call]. -/// -/// [wrappedMessage] is the raw message sent by [call]. This unwraps it and -/// passes the contents of the message to [callback], then sends the return -/// value of [callback] back to [call]. If [callback] returns a Future or -/// throws an error, that will also be sent. -void respond(wrappedMessage, callback(message)) { - var replyTo = wrappedMessage['replyTo']; - new Future.sync(() => callback(wrappedMessage['message'])) - .then((result) => replyTo.send({'type': 'success', 'value': result})) - .catchError((error, stackTrace) { - replyTo.send({ - 'type': 'error', - 'error': serializeException(error, stackTrace) - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/aggregate_transform.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/aggregate_transform.dart deleted file mode 100644 index 5b7acc816d8..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/aggregate_transform.dart +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.asset.serialize.aggregate_transform; - -import 'dart:async'; -import 'dart:isolate'; - -import 'package:barback/barback.dart'; -// TODO(nweiz): don't import from "src" once issue 14966 is fixed. -import 'package:barback/src/internal_asset.dart'; - -import '../serialize.dart'; -import 'get_input_transform.dart'; - -/// Serialize the methods shared between [AggregateTransform] and -/// [DeclaringAggregateTransform]. -/// -/// [additionalFields] contains additional serialized fields to add to the -/// serialized transform. [methodHandlers] is a set of additional methods. Each -/// value should take a JSON message and return the response (which may be a -/// Future). -Map _serializeBaseAggregateTransform(transform, Map additionalFields, - Map methodHandlers) { - var receivePort = new ReceivePort(); - receivePort.listen((wrappedMessage) { - respond(wrappedMessage, (message) { - var handler = methodHandlers[message['type']]; - if (handler != null) return handler(message); - - if (message['type'] == 'consumePrimary') { - transform.consumePrimary(deserializeId(message['assetId'])); - return null; - } - - assert(message['type'] == 'log'); - var method = { - 'Info': transform.logger.info, - 'Fine': transform.logger.fine, - 'Warning': transform.logger.warning, - 'Error': transform.logger.error - }[message['level']]; - assert(method != null); - - var assetId = message['assetId'] == null ? null : - deserializeId(message['assetId']); - var span = message['span'] == null ? null : - deserializeSpan(message['span']); - method(message['message'], asset: assetId, span: span); - }); - }); - - return { - 'port': receivePort.sendPort, - 'key': transform.key, - 'package': transform.package - }..addAll(additionalFields); -} - -/// Converts [transform] into a serializable map. -Map serializeAggregateTransform(AggregateTransform transform) { - return _serializeBaseAggregateTransform(transform, { - 'primaryInputs': serializeStream(transform.primaryInputs, serializeAsset) - }, { - 'getInput': (message) => transform.getInput(deserializeId(message['id'])) - .then((asset) => serializeAsset(asset)), - 'addOutput': (message) => - transform.addOutput(deserializeAsset(message['output'])) - }); -} - -/// Converts [transform] into a serializable map. -Map serializeDeclaringAggregateTransform( - DeclaringAggregateTransform transform) { - return _serializeBaseAggregateTransform(transform, { - 'primaryIds': serializeStream(transform.primaryIds, serializeId) - }, { - 'declareOutput': (message) => - transform.declareOutput(deserializeId(message['output'])) - }); -} - -/// The base class for wrappers for [AggregateTransform]s that are in the host -/// isolate. -class _ForeignBaseAggregateTransform { - /// The port with which we communicate with the host isolate. - /// - /// This port and all messages sent across it are specific to this transform. - final SendPort _port; - - final String key; - - final String package; - - TransformLogger get logger => _logger; - TransformLogger _logger; - - _ForeignBaseAggregateTransform(Map transform) - : _port = transform['port'], - key = transform['key'], - package = transform['package'] { - _logger = new TransformLogger((assetId, level, message, span) { - call(_port, { - 'type': 'log', - 'level': level.name, - 'message': message, - 'assetId': assetId == null ? null : serializeId(assetId), - 'span': span == null ? null : serializeSpan(span) - }); - }); - } - - void consumePrimary(AssetId id) { - call(_port, {'type': 'consumePrimary', 'assetId': serializeId(id)}); - } -} - -// We can get away with only removing the class declarations in incompatible -// barback versions because merely referencing undefined types in type -// annotations isn't a static error. Only implementing an undefined interface is -// a static error. -//# if barback >=0.14.1 - -/// A wrapper for an [AggregateTransform] that's in the host isolate. -/// -/// This retrieves inputs from and sends outputs and logs to the host isolate. -class ForeignAggregateTransform extends _ForeignBaseAggregateTransform - with GetInputTransform implements AggregateTransform { - final Stream primaryInputs; - - /// Creates a transform from a serialized map sent from the host isolate. - ForeignAggregateTransform(Map transform) - : primaryInputs = deserializeStream( - transform['primaryInputs'], deserializeAsset), - super(transform); - - Future getInput(AssetId id) { - return call(_port, { - 'type': 'getInput', - 'id': serializeId(id) - }).then(deserializeAsset); - } - - void addOutput(Asset output) { - call(_port, { - 'type': 'addOutput', - 'output': serializeAsset(output) - }); - } -} - -/// A wrapper for a [DeclaringAggregateTransform] that's in the host isolate. -class ForeignDeclaringAggregateTransform - extends _ForeignBaseAggregateTransform - implements DeclaringAggregateTransform { - final Stream primaryIds; - - /// Creates a transform from a serializable map sent from the host isolate. - ForeignDeclaringAggregateTransform(Map transform) - : primaryIds = deserializeStream( - transform['primaryIds'], deserializeId), - super(transform); - - void declareOutput(AssetId id) { - call(_port, { - 'type': 'declareOutput', - 'output': serializeId(id) - }); - } -} - -//# end diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/exception.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/exception.dart deleted file mode 100644 index 26040a9d8b9..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/exception.dart +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.asset.serialize.exception; - -import 'package:barback/barback.dart'; -import 'package:stack_trace/stack_trace.dart'; - -import '../utils.dart'; - -/// An exception that was originally raised in another isolate. -/// -/// Exception objects can't cross isolate boundaries in general, so this class -/// wraps as much information as can be consistently serialized. -class CrossIsolateException implements Exception { - /// The name of the type of exception thrown. - /// - /// This is the return value of [error.runtimeType.toString()]. Keep in mind - /// that objects in different libraries may have the same type name. - final String type; - - /// The exception's message, or its [toString] if it didn't expose a `message` - /// property. - final String message; - - /// The exception's stack chain, or `null` if no stack chain was available. - final Chain stackTrace; - - /// Loads a [CrossIsolateException] from a serialized representation. - /// - /// [error] should be the result of [CrossIsolateException.serialize]. - CrossIsolateException.deserialize(Map error) - : type = error['type'], - message = error['message'], - stackTrace = error['stack'] == null ? null : - new Chain.parse(error['stack']); - - /// Serializes [error] to an object that can safely be passed across isolate - /// boundaries. - static Map serialize(error, [StackTrace stack]) { - if (stack == null && error is Error) stack = error.stackTrace; - return { - 'type': error.runtimeType.toString(), - 'message': getErrorMessage(error), - 'stack': stack == null ? null : new Chain.forTrace(stack).toString() - }; - } - - String toString() => "$message\n$stackTrace"; -} - -/// An [AssetNotFoundException] that was originally raised in another isolate. -class _CrossIsolateAssetNotFoundException extends CrossIsolateException - implements AssetNotFoundException { - final AssetId id; - - String get message => "Could not find asset $id."; - - /// Loads a [_CrossIsolateAssetNotFoundException] from a serialized - /// representation. - /// - /// [error] should be the result of - /// [_CrossIsolateAssetNotFoundException.serialize]. - _CrossIsolateAssetNotFoundException.deserialize(Map error) - : id = new AssetId(error['package'], error['path']), - super.deserialize(error); - - /// Serializes [error] to an object that can safely be passed across isolate - /// boundaries. - static Map serialize(AssetNotFoundException error, [StackTrace stack]) { - var map = CrossIsolateException.serialize(error); - map['package'] = error.id.package; - map['path'] = error.id.path; - return map; - } -} - -/// Serializes [error] to an object that can safely be passed across isolate -/// boundaries. -/// -/// This handles [AssetNotFoundException]s specially, ensuring that their -/// metadata is preserved. -Map serializeException(error, [StackTrace stack]) { - if (error is AssetNotFoundException) { - return _CrossIsolateAssetNotFoundException.serialize(error, stack); - } else { - return CrossIsolateException.serialize(error, stack); - } -} - -/// Loads an exception from a serialized representation. -/// -/// This handles [AssetNotFoundException]s specially, ensuring that their -/// metadata is preserved. -CrossIsolateException deserializeException(Map error) { - if (error['type'] == 'AssetNotFoundException') { - return new _CrossIsolateAssetNotFoundException.deserialize(error); - } else { - return new CrossIsolateException.deserialize(error); - } -} diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/get_input_transform.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/get_input_transform.dart deleted file mode 100644 index 9ab6540b3f9..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/get_input_transform.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.asset.serialize.get_input_transform; - -import 'dart:async'; -import 'dart:convert'; - -import 'package:barback/barback.dart'; - -import '../utils.dart'; - -/// A mixin for transforms that support [getInput] and the associated suite of -/// methods. -abstract class GetInputTransform { - Future getInput(AssetId id); - - Future readInputAsString(AssetId id, {Encoding encoding}) { - if (encoding == null) encoding = UTF8; - return getInput(id).then((input) => - input.readAsString(encoding: encoding)); - } - - Stream> readInput(AssetId id) => - futureStream(getInput(id).then((input) => input.read())); - - Future hasInput(AssetId id) { - return getInput(id).then((_) => true).catchError((error) { - if (error is AssetNotFoundException && error.id == id) return false; - throw error; - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transform.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/transform.dart deleted file mode 100644 index 911f6f624e0..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transform.dart +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.asset.serialize.transform; - -import 'dart:async'; -import 'dart:isolate'; - -import 'package:barback/barback.dart'; -// TODO(nweiz): don't import from "src" once issue 14966 is fixed. -import 'package:barback/src/internal_asset.dart'; - -import '../serialize.dart'; -import 'get_input_transform.dart'; - -/// Serialize the methods shared between [Transform] and [DeclaringTransform]. -/// -/// [additionalFields] contains additional serialized fields to add to the -/// serialized transform. [methodHandlers] is a set of additional methods. Each -/// value should take a JSON message and return the response (which may be a -/// Future). -Map _serializeBaseTransform(transform, Map additionalFields, - Map methodHandlers) { - var receivePort = new ReceivePort(); - receivePort.listen((wrappedMessage) { - respond(wrappedMessage, (message) { - var handler = methodHandlers[message['type']]; - if (handler != null) return handler(message); - - if (message['type'] == 'consumePrimary') { - transform.consumePrimary(); - return null; - } - - assert(message['type'] == 'log'); - var method = { - 'Info': transform.logger.info, - 'Fine': transform.logger.fine, - 'Warning': transform.logger.warning, - 'Error': transform.logger.error - }[message['level']]; - assert(method != null); - - var assetId = message['assetId'] == null ? null : - deserializeId(message['assetId']); - var span = message['span'] == null ? null : - deserializeSpan(message['span']); - method(message['message'], asset: assetId, span: span); - }); - }); - - return {'port': receivePort.sendPort}..addAll(additionalFields); -} - -/// Converts [transform] into a serializable map. -Map serializeTransform(Transform transform) { - return _serializeBaseTransform(transform, { - 'primaryInput': serializeAsset(transform.primaryInput) - }, { - 'getInput': (message) => transform.getInput(deserializeId(message['id'])) - .then((asset) => serializeAsset(asset)), - 'addOutput': (message) => - transform.addOutput(deserializeAsset(message['output'])) - }); -} - -/// Converts [transform] into a serializable map. -Map serializeDeclaringTransform(DeclaringTransform transform) { - return _serializeBaseTransform(transform, { - 'primaryId': serializeId(transform.primaryId) - }, { - 'declareOutput': (message) => - transform.declareOutput(deserializeId(message['output'])) - }); -} - -/// The base class for wrappers for [Transform]s that are in the host isolate. -class _ForeignBaseTransform { - /// The port with which we communicate with the host isolate. - /// - /// This port and all messages sent across it are specific to this transform. - final SendPort _port; - - TransformLogger get logger => _logger; - TransformLogger _logger; - - _ForeignBaseTransform(Map transform) - : _port = transform['port'] { - _logger = new TransformLogger((assetId, level, message, span) { - call(_port, { - 'type': 'log', - 'level': level.name, - 'message': message, - 'assetId': assetId == null ? null : serializeId(assetId), - 'span': span == null ? null : serializeSpan(span) - }); - }); - } - - void consumePrimary() { - call(_port, {'type': 'consumePrimary'}); - } -} - -/// A wrapper for a [Transform] that's in the host isolate. -/// -/// This retrieves inputs from and sends outputs and logs to the host isolate. -class ForeignTransform extends _ForeignBaseTransform - with GetInputTransform implements Transform { - final Asset primaryInput; - - /// Creates a transform from a serialized map sent from the host isolate. - ForeignTransform(Map transform) - : primaryInput = deserializeAsset(transform['primaryInput']), - super(transform); - - Future getInput(AssetId id) { - return call(_port, { - 'type': 'getInput', - 'id': serializeId(id) - }).then(deserializeAsset); - } - - void addOutput(Asset output) { - call(_port, { - 'type': 'addOutput', - 'output': serializeAsset(output) - }); - } -} - -/// A wrapper for a [DeclaringTransform] that's in the host isolate. -class ForeignDeclaringTransform extends _ForeignBaseTransform - implements DeclaringTransform { - final AssetId primaryId; - - /// Creates a transform from a serializable map sent from the host isolate. - ForeignDeclaringTransform(Map transform) - : primaryId = deserializeId(transform['primaryId']), - super(transform); - - void declareOutput(AssetId id) { - call(_port, { - 'type': 'declareOutput', - 'output': serializeId(id) - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transformer.dart b/sdk/lib/_internal/pub_generated/asset/dart/serialize/transformer.dart deleted file mode 100644 index 16d02deb579..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/serialize/transformer.dart +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.asset.serialize.transformer; - -import 'dart:async'; -import 'dart:isolate'; - -import 'package:barback/barback.dart'; - -import '../serialize.dart'; -import 'transform.dart'; - -/// Converts [transformer] into a serializable map. -Map _serializeTransformer(Transformer transformer) { - var port = new ReceivePort(); - port.listen((wrappedMessage) { - respond(wrappedMessage, (message) { - if (message['type'] == 'isPrimary') { - return transformer.isPrimary(deserializeId(message['id'])); - } else if (message['type'] == 'declareOutputs') { - return new Future.sync(() { - return (transformer as DeclaringTransformer).declareOutputs( - new ForeignDeclaringTransform(message['transform'])); - }).then((_) => null); - } else { - assert(message['type'] == 'apply'); - - // Make sure we return null so that if the transformer's [apply] returns - // a non-serializable value it doesn't cause problems. - return new Future.sync(() { - return transformer.apply(new ForeignTransform(message['transform'])); - }).then((_) => null); - } - }); - }); - - var type; - if (transformer is LazyTransformer) { - type = 'LazyTransformer'; - } else if (transformer is DeclaringTransformer) { - type = 'DeclaringTransformer'; - } else { - type = 'Transformer'; - } - - return { - 'type': type, - 'toString': transformer.toString(), - 'port': port.sendPort - }; -} - -/// Converts [transformer] into a serializable map. -Map _serializeAggregateTransformer(AggregateTransformer transformer) { - var port = new ReceivePort(); - port.listen((wrappedMessage) { - respond(wrappedMessage, (message) { - if (message['type'] == 'classifyPrimary') { - return transformer.classifyPrimary(deserializeId(message['id'])); - } else if (message['type'] == 'declareOutputs') { - return new Future.sync(() { - return (transformer as DeclaringAggregateTransformer).declareOutputs( - new ForeignDeclaringAggregateTransform(message['transform'])); - }).then((_) => null); - } else { - assert(message['type'] == 'apply'); - - // Make sure we return null so that if the transformer's [apply] returns - // a non-serializable value it doesn't cause problems. - return new Future.sync(() { - return transformer.apply( - new ForeignAggregateTransform(message['transform'])); - }).then((_) => null); - } - }); - }); - - var type; - if (transformer is LazyAggregateTransformer) { - type = 'LazyAggregateTransformer'; - } else if (transformer is DeclaringAggregateTransformer) { - type = 'DeclaringAggregateTransformer'; - } else { - type = 'AggregateTransformer'; - } - - return { - 'type': type, - 'toString': transformer.toString(), - 'port': port.sendPort - }; -} - -// Converts [group] into a serializable map. -Map _serializeTransformerGroup(TransformerGroup group) { - if (group.phases == null) { - throw "TransformerGroup $group phases cannot be null."; - } - - return { - 'type': 'TransformerGroup', - 'toString': group.toString(), - 'phases': group.phases.map((phase) { - return phase.map(serializeTransformerLike).toList(); - }).toList() - }; -} - -/// Converts [transformerLike] into a serializable map. -/// -/// [transformerLike] can be a [Transformer], an [AggregateTransformer], or a -/// [TransformerGroup]. -Map serializeTransformerLike(transformerLike) { - if (transformerLike is Transformer) { - return _serializeTransformer(transformerLike); - } else if (transformerLike is TransformerGroup) { - return _serializeTransformerGroup(transformerLike); - } else { - // This has to be last, since "transformerLike is AggregateTransformer" will - // throw on older versions of barback. - assert(transformerLike is AggregateTransformer); - return _serializeAggregateTransformer(transformerLike); - } -} diff --git a/sdk/lib/_internal/pub_generated/asset/dart/transformer_isolate.dart b/sdk/lib/_internal/pub_generated/asset/dart/transformer_isolate.dart deleted file mode 100644 index 50bb97baac8..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/transformer_isolate.dart +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.asset.transformer_isolate; - -import 'dart:convert'; -import 'dart:isolate'; -import 'dart:mirrors'; - -import 'package:barback/barback.dart'; - -import 'serialize.dart'; - -/// The mirror system. -/// -/// Cached to avoid re-instantiating each time a transformer is initialized. -final _mirrors = currentMirrorSystem(); - -/// Sets up the initial communication with the host isolate. -void loadTransformers(SendPort replyTo) { - var port = new ReceivePort(); - replyTo.send(port.sendPort); - port.listen((wrappedMessage) { - // TODO(nweiz): When issue 19228 is fixed, spin up a separate isolate for - // libraries loaded beyond the first so they can run in parallel. - respond(wrappedMessage, (message) { - var configuration = JSON.decode(message['configuration']); - var mode = new BarbackMode(message['mode']); - return _initialize(message['library'], configuration, mode). - map(serializeTransformerLike).toList(); - }); - }); -} - -/// Loads all the transformers and groups defined in [uri]. -/// -/// Loads the library, finds any [Transformer] or [TransformerGroup] subclasses -/// in it, instantiates them with [configuration] and [mode], and returns them. -List _initialize(String uri, Map configuration, BarbackMode mode) { - var transformerClass = reflectClass(Transformer); - var aggregateClass = _aggregateTransformerClass; - var groupClass = reflectClass(TransformerGroup); - - var seen = new Set(); - var transformers = []; - - loadFromLibrary(library) { - if (seen.contains(library)) return; - seen.add(library); - - // Load transformers from libraries exported by [library]. - for (var dependency in library.libraryDependencies) { - if (!dependency.isExport) continue; - loadFromLibrary(dependency.targetLibrary); - } - - // TODO(nweiz): if no valid transformers are found, throw an error message - // describing candidates and why they were rejected. - transformers.addAll(library.declarations.values.map((declaration) { - if (declaration is! ClassMirror) return null; - var classMirror = declaration; - if (classMirror.isPrivate) return null; - if (classMirror.isAbstract) return null; - if (!classMirror.isSubtypeOf(transformerClass) && - !classMirror.isSubtypeOf(groupClass) && - (aggregateClass == null || - !classMirror.isSubtypeOf(aggregateClass))) { - return null; - } - - var constructor = _getConstructor(classMirror, 'asPlugin'); - if (constructor == null) return null; - if (constructor.parameters.isEmpty) { - if (configuration.isNotEmpty) return null; - return classMirror.newInstance(const Symbol('asPlugin'), []).reflectee; - } - if (constructor.parameters.length != 1) return null; - - return classMirror.newInstance(const Symbol('asPlugin'), - [new BarbackSettings(configuration, mode)]).reflectee; - }).where((classMirror) => classMirror != null)); - } - - var library = _mirrors.libraries[Uri.parse(uri)]; - - // This should only happen if something's wrong with the logic in pub itself. - // If it were user error, the entire isolate would fail to load. - if (library == null) throw "Couldn't find library at $uri."; - - loadFromLibrary(library); - return transformers; -} - -// TODO(nweiz): clean this up when issue 13248 is fixed. -MethodMirror _getConstructor(ClassMirror classMirror, String constructor) { - var name = new Symbol("${MirrorSystem.getName(classMirror.simpleName)}" - ".$constructor"); - var candidate = classMirror.declarations[name]; - if (candidate is MethodMirror && candidate.isConstructor) return candidate; - return null; -} - -// Older barbacks don't support [AggregateTransformer], and calling -// [reflectClass] on an undefined class will throw an error, so we just define a -// null getter for them. -//# if barback >=0.14.1 -ClassMirror get _aggregateTransformerClass => - reflectClass(AggregateTransformer); -//# else -//> ClassMirror get _aggregateTransformerClass => null; -//# end diff --git a/sdk/lib/_internal/pub_generated/asset/dart/utils.dart b/sdk/lib/_internal/pub_generated/asset/dart/utils.dart deleted file mode 100644 index 72150edf0b1..00000000000 --- a/sdk/lib/_internal/pub_generated/asset/dart/utils.dart +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Functions go in this file as opposed to lib/src/utils.dart if they need to -/// be accessible to the transformer-loading isolate. -library pub.asset.utils; - -import 'dart:async'; - -/// A regular expression to match the exception prefix that some exceptions' -/// [Object.toString] values contain. -final _exceptionPrefix = new RegExp(r'^([A-Z][a-zA-Z]*)?(Exception|Error): '); - -/// Get a string description of an exception. -/// -/// Many exceptions include the exception class name at the beginning of their -/// [toString], so we remove that if it exists. -String getErrorMessage(error) => - error.toString().replaceFirst(_exceptionPrefix, ''); - -/// Returns a buffered stream that will emit the same values as the stream -/// returned by [future] once [future] completes. -/// -/// If [future] completes to an error, the return value will emit that error and -/// then close. -/// -/// If [broadcast] is true, a broadcast stream is returned. This assumes that -/// the stream returned by [future] will be a broadcast stream as well. -/// [broadcast] defaults to false. -Stream futureStream(Future future, {bool broadcast: false}) { - var subscription; - var controller; - - future = future.catchError((e, stackTrace) { - // Since [controller] is synchronous, it's likely that emitting an error - // will cause it to be cancelled before we call close. - if (controller != null) controller.addError(e, stackTrace); - if (controller != null) controller.close(); - controller = null; - }); - - onListen() { - future.then((stream) { - if (controller == null) return; - subscription = stream.listen( - controller.add, - onError: controller.addError, - onDone: controller.close); - }); - } - - onCancel() { - if (subscription != null) subscription.cancel(); - subscription = null; - controller = null; - } - - if (broadcast) { - controller = new StreamController.broadcast( - sync: true, onListen: onListen, onCancel: onCancel); - } else { - controller = new StreamController( - sync: true, onListen: onListen, onCancel: onCancel); - } - return controller.stream; -} - -/// Returns a [Stream] that will emit the same values as the stream returned by -/// [callback]. -/// -/// [callback] will only be called when the returned [Stream] gets a subscriber. -Stream callbackStream(Stream callback()) { - var subscription; - var controller; - controller = new StreamController(onListen: () { - subscription = callback().listen(controller.add, - onError: controller.addError, - onDone: controller.close); - }, - onCancel: () => subscription.cancel(), - onPause: () => subscription.pause(), - onResume: () => subscription.resume(), - sync: true); - return controller.stream; -} diff --git a/sdk/lib/_internal/pub_generated/bin/async_compile.dart b/sdk/lib/_internal/pub_generated/bin/async_compile.dart deleted file mode 100644 index 2e96717d460..00000000000 --- a/sdk/lib/_internal/pub_generated/bin/async_compile.dart +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:args/args.dart'; -import 'package:analyzer/src/services/formatter_impl.dart'; -import 'package:async_await/async_await.dart' as async_await; -import 'package:stack_trace/stack_trace.dart'; -import 'package:path/path.dart' as p; - -/// The path to pub's root directory (sdk/lib/_internal/pub) in the Dart repo. -/// -/// This assumes this script is itself being run from within the repo. -final sourceDir = p.dirname(p.dirname(p.fromUri(Platform.script))); - -/// The [sourceDir] as a URL, for use in import strings. -final sourceUrl = p.toUri(sourceDir).toString(); - -/// The directory that compiler output should be written to. -String generatedDir; - -/// `true` if any file failed to compile. -bool hadFailure = false; - -bool verbose = false; - -/// Prefix for imports in pub that import dart2js libraries. -final _compilerPattern = new RegExp(r"import '(\.\./)+compiler"); - -/// Matches the Git commit hash of the compiler stored in the README.md file. -/// -/// This is used both to find the current commit and replace it with the new -/// one. -final _commitPattern = new RegExp(r"[a-f0-9]{40}"); - -/// The template for the README that's added to the generated source. -/// -/// This is used to store the current commit of the async_await compiler. -const _README = """ -Pub is currently dogfooding the new Dart async/await syntax. Since the Dart VM -doesn't natively support it yet, we are using the [async-await][] compiler -package. - -[async-await]: https://github.com/dart-lang/async_await - -We run that to compile pub-using-await from sdk/lib/_internal/pub down to -vanilla Dart code which is what you see here. To interoperate more easily with -the rest of the repositry, we check in that generated code. - -When bug #104 is fixed, we can remove this entirely. - -The code here was compiled using the async-await compiler at commit: - - <> - -(Note: this file is also parsed by a tool to update the above commit, so be -careful not to reformat it.) -"""; - -/// This runs the async/await compiler on all of the pub source code. -/// -/// It reads from the repo and writes the compiled output into the given build -/// directory (using the same file names and relative layout). Does not -/// compile files that haven't changed since the last time they were compiled. -// TODO(rnystrom): Remove this when #104 is fixed. -void main(List arguments) { - var parser = new ArgParser(allowTrailingOptions: true); - - parser.addFlag("verbose", callback: (value) => verbose = value); - - var force = false; - parser.addFlag("force", callback: (value) => force = value); - - var buildDir; - parser.addOption("snapshot-build-dir", callback: (value) => buildDir = value); - - try { - var rest = parser.parse(arguments).rest; - if (rest.isEmpty) { - throw new FormatException('Missing generated directory.'); - } else if (rest.length > 1) { - throw new FormatException( - 'Unexpected arguments: ${rest.skip(1).join(" ")}.'); - } - - generatedDir = rest.first; - } on FormatException catch (ex) { - stderr.writeln(ex); - stderr.writeln(); - stderr.writeln( - "Usage: dart async_compile.dart [--verbose] [--force] " - "[--snapshot-build-dir ] "); - exit(64); - } - - // See what version (i.e. Git commit) of the async-await compiler we - // currently have. If this is different from the version that was used to - // compile the sources, recompile everything. - var currentCommit = _getCurrentCommit(); - - var readmePath = p.join(generatedDir, "README.md"); - var lastCommit; - try { - var readme = new File(readmePath).readAsStringSync(); - var match = _commitPattern.firstMatch(readme); - if (match == null) { - stderr.writeln("Could not find compiler commit hash in README.md."); - exit(1); - } - - lastCommit = match[0]; - } on IOException catch (error, stackTrace) { - if (verbose) { - stderr.writeln( - "Failed to load $readmePath: $error\n" "${new Trace.from(stackTrace)}"); - } - } - - var numFiles = 0; - var numCompiled = 0; - - // Compile any modified or missing files. - var sources = new Set(); - for (var entry in new Directory(sourceDir).listSync(recursive: true)) { - if (p.extension(entry.path) != ".dart") continue; - - numFiles++; - var relative = p.relative(entry.path, from: sourceDir); - sources.add(relative); - - var sourceFile = entry as File; - var destPath = p.join(generatedDir, relative); - var destFile = new File(destPath); - if (force || - currentCommit != lastCommit || - !destFile.existsSync() || - entry.lastModifiedSync().isAfter(destFile.lastModifiedSync())) { - _compile(sourceFile.path, sourceFile.readAsStringSync(), destPath); - numCompiled++; - if (verbose) print("Compiled $relative"); - } - } - - // Delete any previously compiled files whose source no longer exists. - for (var entry in new Directory(generatedDir).listSync(recursive: true)) { - if (p.extension(entry.path) != ".dart") continue; - - var relative = p.relative(entry.path, from: generatedDir); - - if (!sources.contains(relative)) { - _deleteFile(entry.path); - if (verbose) print("Deleted $relative"); - } - } - - // Update the README. - if (currentCommit != lastCommit) { - _writeFile(readmePath, _README.replaceAll("<>", currentCommit)); - if (verbose) print("Updated README.md"); - } - - if (numCompiled > 0 && buildDir != null) _generateSnapshot(buildDir); - - if (verbose) print("Compiled $numCompiled out of $numFiles files"); - - if (hadFailure) exit(1); -} - -String _getCurrentCommit() { - var command = "git"; - var args = ["rev-parse", "HEAD"]; - - // Spawning a process on Windows will not look for the executable in the - // system path so spawn git through a shell to find it. - if (Platform.operatingSystem == "windows") { - command = "cmd"; - args = ["/c", "git"]..addAll(args); - } - - var result = Process.runSync( - command, - args, - workingDirectory: p.join(sourceDir, "../../../../third_party/pkg/async_await")); - if (result.exitCode != 0) { - stderr.writeln("Could not get Git revision of async_await compiler."); - exit(1); - } - - return result.stdout.trim(); -} - -void _compile(String sourcePath, String source, String destPath) { - var destDir = new Directory(p.dirname(destPath)); - destDir.createSync(recursive: true); - - source = _translateAsyncAwait(sourcePath, source); - if (source != null) source = _fixDart2jsImports(sourcePath, source, destPath); - - if (source == null) { - // If the async compile fails, delete the file so that we don't try to - // run the stale previous output and so that we try to recompile it later. - _deleteFile(destPath); - } else { - _writeFile(destPath, source); - } -} - -/// Runs the async/await compiler on [source]. -/// -/// Returns the translated Dart code or `null` if the compiler failed. -String _translateAsyncAwait(String sourcePath, String source) { - if (p.isWithin(p.join(sourceDir, "asset"), sourcePath)) { - // Don't run the async compiler on the special "asset" source files. These - // have preprocessor comments that get discarded by the compiler. - return source; - } - - try { - source = async_await.compile(source); - - // Reformat the result since the compiler ditches all whitespace. - // TODO(rnystrom): Remove when this is fixed: - // https://github.com/dart-lang/async_await/issues/12 - var result = new CodeFormatter().format(CodeKind.COMPILATION_UNIT, source); - return result.source; - } catch (ex) { - stderr.writeln("Async compile failed on $sourcePath:\n$ex"); - hadFailure = true; - return null; - } -} - -/// Fix relative imports to dart2js libraries. -/// -/// Pub imports dart2js using relative imports that reach outside of pub's -/// source tree. Since the build directory is in a different location, we need -/// to fix those to be valid relative imports from the build directory. -String _fixDart2jsImports(String sourcePath, String source, String destPath) { - var compilerDir = p.url.join(sourceUrl, "../compiler"); - var relative = - p.url.relative(compilerDir, from: p.url.dirname(p.toUri(destPath).toString())); - return source.replaceAll(_compilerPattern, "import '$relative"); -} - -/// Regenerate the pub snapshot from the async/await-compiled output. We do -/// this here since the tests need it and it's faster than doing a full SDK -/// build. -void _generateSnapshot(String buildDir) { - buildDir = p.normalize(buildDir); - new Directory(buildDir).createSync(recursive: true); - - var entrypoint = p.join(generatedDir, 'bin/pub.dart'); - var packageRoot = p.join(buildDir, 'packages'); - var snapshot = p.join(buildDir, 'dart-sdk/bin/snapshots/pub.dart.snapshot'); - - var result = Process.runSync( - Platform.executable, - ["--package-root=$packageRoot", "--snapshot=$snapshot", entrypoint]); - - if (result.exitCode != 0) { - stderr.writeln("Failed to generate snapshot:"); - if (result.stderr.trim().isNotEmpty) stderr.writeln(result.stderr); - if (result.stdout.trim().isNotEmpty) stderr.writeln(result.stdout); - exit(result.exitCode); - } - - if (verbose) print("Created pub snapshot"); -} - -/// Deletes the file at [path], ignoring any IO errors that occur. -/// -/// This swallows errors to accommodate multiple compilers running concurrently. -/// Since they will produce the same output anyway, a failure of one is fine. -void _deleteFile(String path) { - try { - new File(path).deleteSync(); - } on IOException catch (ex) { - // Do nothing. - } -} - -/// Writes [contents] to [path], ignoring any IO errors that occur. -/// -/// This swallows errors to accommodate multiple compilers running concurrently. -/// Since they will produce the same output anyway, a failure of one is fine. -void _writeFile(String path, String contents) { - try { - new File(path).writeAsStringSync(contents); - } on IOException catch (ex) { - // Do nothing. - } -} diff --git a/sdk/lib/_internal/pub_generated/bin/pub.dart b/sdk/lib/_internal/pub_generated/bin/pub.dart deleted file mode 100644 index e781f94785e..00000000000 --- a/sdk/lib/_internal/pub_generated/bin/pub.dart +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../lib/src/command_runner.dart'; - -void main(List arguments) { - new PubCommandRunner().run(arguments); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/ascii_tree.dart b/sdk/lib/_internal/pub_generated/lib/src/ascii_tree.dart deleted file mode 100644 index ca8d5103c2b..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/ascii_tree.dart +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// A simple library for rendering tree-like structures in ASCII. -library pub.ascii_tree; - -import 'package:path/path.dart' as path; - -import 'log.dart' as log; -import 'utils.dart'; - -/// Draws a tree for the given list of files. Given files like: -/// -/// TODO -/// example/console_example.dart -/// example/main.dart -/// example/web copy/web_example.dart -/// test/absolute_test.dart -/// test/basename_test.dart -/// test/dirname_test.dart -/// test/extension_test.dart -/// test/is_absolute_test.dart -/// test/is_relative_test.dart -/// test/join_test.dart -/// test/normalize_test.dart -/// test/relative_test.dart -/// test/split_test.dart -/// .gitignore -/// README.md -/// lib/path.dart -/// pubspec.yaml -/// test/all_test.dart -/// test/path_posix_test.dart -/// test/path_windows_test.dart -/// -/// this renders: -/// -/// |-- .gitignore -/// |-- README.md -/// |-- TODO -/// |-- example -/// | |-- console_example.dart -/// | |-- main.dart -/// | '-- web copy -/// | '-- web_example.dart -/// |-- lib -/// | '-- path.dart -/// |-- pubspec.yaml -/// '-- test -/// |-- absolute_test.dart -/// |-- all_test.dart -/// |-- basename_test.dart -/// | (7 more...) -/// |-- path_windows_test.dart -/// |-- relative_test.dart -/// '-- split_test.dart -/// -/// If [baseDir] is passed, it will be used as the root of the tree. -/// -/// If [showAllChildren] is `false`, then directories with more than ten items -/// will have their contents truncated. Defaults to `false`. -String fromFiles(List files, {String baseDir, bool showAllChildren}) { - // Parse out the files into a tree of nested maps. - var root = {}; - for (var file in files) { - if (baseDir != null) file = path.relative(file, from: baseDir); - var parts = path.split(file); - var directory = root; - for (var part in path.split(file)) { - directory = directory.putIfAbsent(part, () => {}); - } - } - - // Walk the map recursively and render to a string. - return fromMap(root, showAllChildren: showAllChildren); -} - -/// Draws a tree from a nested map. Given a map like: -/// -/// { -/// "analyzer": { -/// "args": { -/// "collection": "" -/// }, -/// "logging": {} -/// }, -/// "barback": {} -/// } -/// -/// this renders: -/// -/// analyzer -/// |-- args -/// | '-- collection -/// '---logging -/// barback -/// -/// Items with no children should have an empty map as the value. -/// -/// If [showAllChildren] is `false`, then directories with more than ten items -/// will have their contents truncated. Defaults to `false`. -String fromMap(Map map, {bool showAllChildren}) { - var buffer = new StringBuffer(); - _draw(buffer, "", null, map, showAllChildren: showAllChildren); - return buffer.toString(); -} - -void _drawLine(StringBuffer buffer, String prefix, bool isLastChild, - String name) { - // Print lines. - buffer.write(prefix); - if (name != null) { - if (isLastChild) { - buffer.write(log.gray("'-- ")); - } else { - buffer.write(log.gray("|-- ")); - } - } - - // Print name. - buffer.writeln(name); -} - -String _getPrefix(bool isRoot, bool isLast) { - if (isRoot) return ""; - if (isLast) return " "; - return log.gray("| "); -} - -void _draw(StringBuffer buffer, String prefix, String name, Map children, - {bool showAllChildren, bool isLast: false}) { - if (showAllChildren == null) showAllChildren = false; - - // Don't draw a line for the root node. - if (name != null) _drawLine(buffer, prefix, isLast, name); - - // Recurse to the children. - var childNames = ordered(children.keys); - - drawChild(bool isLastChild, String child) { - var childPrefix = _getPrefix(name == null, isLast); - _draw( - buffer, - '$prefix$childPrefix', - child, - children[child], - showAllChildren: showAllChildren, - isLast: isLastChild); - } - - if (name == null || showAllChildren || childNames.length <= 10) { - // Not too many, so show all the children. - for (var i = 0; i < childNames.length; i++) { - drawChild(i == childNames.length - 1, childNames[i]); - } - } else { - // Show the first few. - drawChild(false, childNames[0]); - drawChild(false, childNames[1]); - drawChild(false, childNames[2]); - - // Elide the middle ones. - buffer.write(prefix); - buffer.write(_getPrefix(name == null, isLast)); - buffer.writeln(log.gray('| (${childNames.length - 6} more...)')); - - // Show the last few. - drawChild(false, childNames[childNames.length - 3]); - drawChild(false, childNames[childNames.length - 2]); - drawChild(true, childNames[childNames.length - 1]); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback.dart b/sdk/lib/_internal/pub_generated/lib/src/barback.dart deleted file mode 100644 index ea7e650557d..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback.dart +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; -import 'package:pub_semver/pub_semver.dart'; - -/// The currently supported versions of packages that this version of pub works -/// with. -/// -/// Pub implicitly constrains these packages to these versions as long as -/// barback is a dependency. -/// -/// Users' transformers are loaded in an isolate that uses the entrypoint -/// package's dependency versions. However, that isolate also loads code -/// provided by pub (`asset/dart/transformer_isolate.dart` and associated -/// files). This code uses these packages as well, so these constraints exist to -/// ensure that its usage of the packages remains valid. -/// -/// Most constraints here are like normal version constraints in that their -/// upper bound is the next major version of the package (or minor version for -/// pre-1.0.0 packages). If a new major version of the package is released, -/// these *must* be incremented to synchronize with that. -/// -/// The constraint on barback is different. Its upper bound is the next *patch* -/// version of barback—that is, the next version with new features. This is -/// because most barback features need additional serialization code to be fully -/// supported in pub, even if they're otherwise backwards-compatible. -/// -/// Whenever a new minor or patch version of barback is published, this *must* -/// be incremented to synchronize with that. See the barback [compatibility -/// documentation][compat] for details on the relationship between this -/// constraint and barback's version. -/// -/// [compat]: https://gist.github.com/nex3/10942218 -final pubConstraints = { - "barback": new VersionConstraint.parse(">=0.13.0 <0.15.3"), - "source_span": new VersionConstraint.parse(">=1.0.0 <2.0.0"), - "stack_trace": new VersionConstraint.parse(">=0.9.1 <2.0.0") -}; - -/// Converts [id] to a "package:" URI. -/// -/// This will throw an [ArgumentError] if [id] doesn't represent a library in -/// `lib/`. -Uri idToPackageUri(AssetId id) { - if (!id.path.startsWith('lib/')) { - throw new ArgumentError("Asset id $id doesn't identify a library."); - } - - return new Uri( - scheme: 'package', - path: p.url.join(id.package, id.path.replaceFirst('lib/', ''))); -} - -/// Converts [uri] into an [AssetId] if its path is within "packages". -/// -/// If the URL contains a special directory, but lacks a following package name, -/// throws a [FormatException]. -/// -/// If the URI doesn't contain one of those special directories, returns null. -AssetId packagesUrlToId(Uri url) { - var parts = p.url.split(url.path); - - // Strip the leading "/" from the URL. - if (parts.isNotEmpty && parts.first == "/") parts = parts.skip(1).toList(); - - if (parts.isEmpty) return null; - - // Check for "packages" in the URL. - // TODO(rnystrom): If we rewrite "package:" imports to relative imports that - // point to a canonical "packages" directory, we can limit "packages" to the - // root of the URL as well. See: #16649. - var index = parts.indexOf("packages"); - if (index == -1) return null; - - // There should be a package name after "packages". - if (parts.length <= index + 1) { - throw new FormatException( - 'Invalid URL path "${url.path}". Expected package name ' 'after "packages".'); - } - - var package = parts[index + 1]; - var assetPath = p.url.join("lib", p.url.joinAll(parts.skip(index + 2))); - return new AssetId(package, assetPath); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/admin_server.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/admin_server.dart deleted file mode 100644 index 36bb621e579..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/admin_server.dart +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.admin_server; - -import 'dart:async'; -import 'dart:io'; - -import 'package:http_parser/http_parser.dart'; -import 'package:shelf/shelf.dart' as shelf; -import 'package:shelf_web_socket/shelf_web_socket.dart'; - -import '../io.dart'; -import '../log.dart' as log; -import 'asset_environment.dart'; -import 'base_server.dart'; -import 'web_socket_api.dart'; - -/// The web admin interface to pub serve. -// TODO(rnystrom): Currently this just provides access to the Web Socket API. -// See #16954. -class AdminServer extends BaseServer { - /// All currently open [WebSocket] connections. - final _webSockets = new Set(); - - shelf.Handler _handler; - - /// Creates a new server and binds it to [port] of [host]. - static Future bind(AssetEnvironment environment, String host, - int port) { - return bindServer(host, port).then((server) { - log.fine('Bound admin server to $host:$port.'); - return new AdminServer._(environment, server); - }); - } - - AdminServer._(AssetEnvironment environment, HttpServer server) - : super(environment, server) { - _handler = new shelf.Cascade().add( - webSocketHandler(_handleWebSocket)).add(_handleHttp).handler; - } - - /// Closes the server and all Web Socket connections. - Future close() { - var futures = [super.close()]; - futures.addAll(_webSockets.map((socket) => socket.close())); - return Future.wait(futures); - } - - handleRequest(shelf.Request request) => _handler(request); - - /// Handles an HTTP request. - _handleHttp(shelf.Request request) { - // TODO(rnystrom): Actually respond to requests once there is an admin - // interface. See #16954. - logRequest(request, "501 Not Implemented"); - return new shelf.Response( - 501, - body: "Currently this server only accepts Web Socket connections."); - } - - /// Creates a web socket for [request] which should be an upgrade request. - void _handleWebSocket(CompatibleWebSocket socket) { - _webSockets.add(socket); - var api = new WebSocketApi(socket, environment); - api.listen().whenComplete( - () => _webSockets.remove(api)).catchError(addError); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/asset_environment.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/asset_environment.dart deleted file mode 100644 index 8316d4e4e03..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/asset_environment.dart +++ /dev/null @@ -1,960 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.asset_environment; - -import 'dart:async'; -import 'dart:io'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as path; -import 'package:watcher/watcher.dart'; - -import '../cached_package.dart'; -import '../entrypoint.dart'; -import '../exceptions.dart'; -import '../io.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../package_graph.dart'; -import '../sdk.dart' as sdk; -import '../source/cached.dart'; -import '../utils.dart'; -import 'admin_server.dart'; -import 'barback_server.dart'; -import 'dart_forwarding_transformer.dart'; -import 'dart2js_transformer.dart'; -import 'load_all_transformers.dart'; -import 'pub_package_provider.dart'; -import 'source_directory.dart'; - -/// The entire "visible" state of the assets of a package and all of its -/// dependencies, taking into account the user's configuration when running pub. -/// -/// Where [PackageGraph] just describes the entrypoint's dependencies as -/// specified by pubspecs, this includes "transient" information like the mode -/// that the user is running pub in, or which directories they want to -/// transform. -class AssetEnvironment { - /// Creates a new build environment for working with the assets used by - /// [entrypoint] and its dependencies. - /// - /// HTTP servers that serve directories from this environment will be bound - /// to [hostname] and have ports based on [basePort]. If omitted, they - /// default to "localhost" and "0" (use ephemeral ports), respectively. - /// - /// Loads all used transformers using [mode] (including dart2js if - /// [useDart2JS] is true). - /// - /// This will only add the root package's "lib" directory to the environment. - /// Other directories can be added to the environment using [serveDirectory]. - /// - /// If [watcherType] is not [WatcherType.NONE] (the default), watches source - /// assets for modification. - /// - /// If [packages] is passed, only those packages' assets are loaded and - /// served. - /// - /// If [entrypoints] is passed, only transformers necessary to run those - /// entrypoints are loaded. Each entrypoint is expected to refer to a Dart - /// library. - /// - /// Returns a [Future] that completes to the environment once the inputs, - /// transformers, and server are loaded and ready. - static Future create(Entrypoint entrypoint, - BarbackMode mode, {WatcherType watcherType, String hostname, int basePort, - Iterable packages, Iterable entrypoints, bool useDart2JS: - true}) { - if (watcherType == null) watcherType = WatcherType.NONE; - if (hostname == null) hostname = "localhost"; - if (basePort == null) basePort = 0; - - return log.progress("Loading asset environment", () { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value(entrypoint.loadPackageGraph()).then((x0) { - try { - var graph = x0; - graph = _adjustPackageGraph(graph, mode, packages); - var barback = new Barback(new PubPackageProvider(graph)); - barback.log.listen(_log); - var environment = - new AssetEnvironment._(graph, barback, mode, watcherType, hostname, basePort); - new Future.value( - environment._load(entrypoints: entrypoints, useDart2JS: useDart2JS)).then((x1) { - try { - x1; - completer0.complete(environment); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }, fine: true); - } - - /// Return a version of [graph] that's restricted to [packages] (if passed) - /// and loads cached packages (if [mode] is [BarbackMode.DEBUG]). - static PackageGraph _adjustPackageGraph(PackageGraph graph, BarbackMode mode, - Iterable packages) { - if (mode != BarbackMode.DEBUG && packages == null) return graph; - packages = (packages == null ? graph.packages.keys : packages).toSet(); - - return new PackageGraph( - graph.entrypoint, - graph.lockFile, - new Map.fromIterable(packages, value: (packageName) { - var package = graph.packages[packageName]; - if (mode != BarbackMode.DEBUG) return package; - var cache = path.join('.pub/deps/debug', packageName); - if (!dirExists(cache)) return package; - return new CachedPackage(package, cache); - })); - } - - /// The server for the Web Socket API and admin interface. - AdminServer _adminServer; - - /// The public directories in the root package that are included in the asset - /// environment, keyed by their root directory. - final _directories = new Map(); - - /// The [Barback] instance used to process assets in this environment. - final Barback barback; - - /// The root package being built. - Package get rootPackage => graph.entrypoint.root; - - /// The graph of packages whose assets and transformers are loaded in this - /// environment. - /// - /// This isn't necessarily identical to the graph that's passed in to the - /// environment. It may expose fewer packages if some packages' assets don't - /// need to be loaded, and it may expose some [CachedPackage]s. - final PackageGraph graph; - - /// The mode to run the transformers in. - final BarbackMode mode; - - /// The [Transformer]s that should be appended by default to the root - /// package's transformer cascade. Will be empty if there are none. - final _builtInTransformers = []; - - /// How source files should be watched. - final WatcherType _watcherType; - - /// The hostname that servers are bound to. - final String _hostname; - - /// The starting number for ports that servers will be bound to. - /// - /// Servers will be bound to ports starting at this number and then - /// incrementing from there. However, if this is zero, then ephemeral port - /// numbers will be selected for each server. - final int _basePort; - - /// The modified source assets that have not been sent to barback yet. - /// - /// The build environment can be paused (by calling [pauseUpdates]) and - /// resumed ([resumeUpdates]). While paused, all source asset updates that - /// come from watching or adding new directories are not sent to barback. - /// When resumed, all pending source updates are sent to barback. - /// - /// This lets pub serve and pub build create an environment and bind several - /// servers before barback starts building and producing results - /// asynchronously. - /// - /// If this is `null`, then the environment is "live" and all updates will - /// go to barback immediately. - Set _modifiedSources; - - AssetEnvironment._(this.graph, this.barback, this.mode, this._watcherType, - this._hostname, this._basePort); - - /// Gets the built-in [Transformer]s that should be added to [package]. - /// - /// Returns `null` if there are none. - Iterable getBuiltInTransformers(Package package) { - // Built-in transformers only apply to the root package. - if (package.name != rootPackage.name) return null; - - // The built-in transformers are for dart2js and forwarding assets around - // dart2js. - if (_builtInTransformers.isEmpty) return null; - - return _builtInTransformers; - } - - /// Starts up the admin server on an appropriate port and returns it. - /// - /// This may only be called once on the build environment. - Future startAdminServer([int port]) { - // Can only start once. - assert(_adminServer == null); - - // The admin server is bound to one before the base port by default, unless - // it's ephemeral in which case the admin port is too. - if (port == null) port = _basePort == 0 ? 0 : _basePort - 1; - - return AdminServer.bind(this, _hostname, port).then((server) => _adminServer = - server); - } - - /// Binds a new port to serve assets from within [rootDirectory] in the - /// entrypoint package. - /// - /// Adds and watches the sources within that directory. Returns a [Future] - /// that completes to the bound server. - /// - /// If [rootDirectory] is already being served, returns that existing server. - Future serveDirectory(String rootDirectory) { - // See if there is already a server bound to the directory. - var directory = _directories[rootDirectory]; - if (directory != null) { - return directory.server.then((server) { - log.fine('Already serving $rootDirectory on ${server.url}.'); - return server; - }); - } - - // See if the new directory overlaps any existing servers. - var overlapping = _directories.keys.where( - (directory) => - path.isWithin(directory, rootDirectory) || - path.isWithin(rootDirectory, directory)).toList(); - - if (overlapping.isNotEmpty) { - return new Future.error( - new OverlappingSourceDirectoryException(overlapping)); - } - - var port = _basePort; - - // If not using an ephemeral port, find the lowest-numbered available one. - if (port != 0) { - var boundPorts = - _directories.values.map((directory) => directory.port).toSet(); - while (boundPorts.contains(port)) { - port++; - } - } - - var sourceDirectory = - new SourceDirectory(this, rootDirectory, _hostname, port); - _directories[rootDirectory] = sourceDirectory; - - return _provideDirectorySources( - rootPackage, - rootDirectory).then((subscription) { - sourceDirectory.watchSubscription = subscription; - return sourceDirectory.serve(); - }); - } - - /// Binds a new port to serve assets from within the "bin" directory of - /// [package]. - /// - /// Adds the sources within that directory and then binds a server to it. - /// Unlike [serveDirectory], this works with packages that are not the - /// entrypoint. - /// - /// Returns a [Future] that completes to the bound server. - Future servePackageBinDirectory(String package) { - return _provideDirectorySources( - graph.packages[package], - "bin").then( - (_) => - BarbackServer.bind(this, _hostname, 0, package: package, rootDirectory: "bin")); - } - - /// Precompiles all of [packageName]'s executables to snapshots in - /// [directory]. - /// - /// If [executableIds] is passed, only those executables are precompiled. - /// - /// Returns a map from executable name to path for the snapshots that were - /// successfully precompiled. - Future> precompileExecutables(String packageName, - String directory, {Iterable executableIds}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - log.fine("Executables for ${packageName}: ${executableIds}"); - join1() { - var package = graph.packages[packageName]; - new Future.value(servePackageBinDirectory(packageName)).then((x0) { - try { - var server = x0; - join2() { - completer0.complete(); - } - finally0(cont0) { - server.close(); - cont0(); - } - catch0(e1, s1) { - finally0(() => completer0.completeError(e1, s1)); - } - try { - var precompiled = {}; - new Future.value(waitAndPrintErrors(executableIds.map(((id) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var basename = path.url.basename(id.path); - var snapshotPath = - path.join(directory, "${basename}.snapshot"); - new Future.value( - runProcess( - Platform.executable, - [ - '--snapshot=${snapshotPath}', - server.url.resolve(basename).toString()])).then((x0) { - try { - var result = x0; - join0() { - completer0.complete(); - } - if (result.success) { - log.message( - "Precompiled ${_formatExecutable(id)}."); - precompiled[path.withoutExtension(basename)] = - snapshotPath; - join0(); - } else { - throw new ApplicationException( - log.yellow("Failed to precompile ${_formatExecutable(id)}:\n") + - result.stderr.join('\n')); - join0(); - } - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x1) { - try { - x1; - final v0 = precompiled; - finally0(() { - completer0.complete(v0); - }); - } catch (e2, s2) { - catch0(e2, s2); - } - }, onError: catch0); - } catch (e3, s3) { - catch0(e3, s3); - } - } catch (e4, s4) { - completer0.completeError(e4, s4); - } - }, onError: completer0.completeError); - } - if (executableIds.isEmpty) { - completer0.complete([]); - } else { - join1(); - } - } - if (executableIds == null) { - executableIds = graph.packages[packageName].executableIds; - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Returns the executable name for [id]. - /// - /// [id] is assumed to be an executable in a bin directory. The return value - /// is intended for log output and may contain formatting. - String _formatExecutable(AssetId id) => - log.bold("${id.package}:${path.basenameWithoutExtension(id.path)}"); - - /// Stops the server bound to [rootDirectory]. - /// - /// Also removes any source files within that directory from barback. Returns - /// the URL of the unbound server, of `null` if [rootDirectory] was not - /// bound to a server. - Future unserveDirectory(String rootDirectory) { - log.fine("Unserving $rootDirectory."); - var directory = _directories.remove(rootDirectory); - if (directory == null) return new Future.value(); - - return directory.server.then((server) { - var url = server.url; - return directory.close().then((_) { - _removeDirectorySources(rootDirectory); - return url; - }); - }); - } - - /// Gets the source directory that contains [assetPath] within the entrypoint - /// package. - /// - /// If [assetPath] is not contained within a source directory, this throws - /// an exception. - String getSourceDirectoryContaining(String assetPath) => - _directories.values.firstWhere( - (dir) => path.isWithin(dir.directory, assetPath)).directory; - - /// Return all URLs serving [assetPath] in this environment. - Future> getUrlsForAssetPath(String assetPath) { - // Check the three (mutually-exclusive) places the path could be pointing. - return _lookUpPathInServerRoot(assetPath).then((urls) { - if (urls.isNotEmpty) return urls; - return _lookUpPathInPackagesDirectory(assetPath); - }).then((urls) { - if (urls.isNotEmpty) return urls; - return _lookUpPathInDependency(assetPath); - }); - } - - /// Look up [assetPath] in the root directories of servers running in the - /// entrypoint package. - Future> _lookUpPathInServerRoot(String assetPath) { - // Find all of the servers whose root directories contain the asset and - // generate appropriate URLs for each. - return Future.wait( - _directories.values.where( - (dir) => path.isWithin(dir.directory, assetPath)).map((dir) { - var relativePath = path.relative(assetPath, from: dir.directory); - return dir.server.then( - (server) => server.url.resolveUri(path.toUri(relativePath))); - })); - } - - /// Look up [assetPath] in the "packages" directory in the entrypoint package. - Future> _lookUpPathInPackagesDirectory(String assetPath) { - var components = path.split(path.relative(assetPath)); - if (components.first != "packages") return new Future.value([]); - if (!graph.packages.containsKey(components[1])) return new Future.value([]); - return Future.wait(_directories.values.map((dir) { - return dir.server.then( - (server) => server.url.resolveUri(path.toUri(assetPath))); - })); - } - - /// Look up [assetPath] in the "lib" or "asset" directory of a dependency - /// package. - Future> _lookUpPathInDependency(String assetPath) { - for (var packageName in graph.packages.keys) { - var package = graph.packages[packageName]; - var libDir = package.path('lib'); - var assetDir = package.path('asset'); - - var uri; - if (path.isWithin(libDir, assetPath)) { - uri = path.toUri( - path.join('packages', package.name, path.relative(assetPath, from: libDir))); - } else if (path.isWithin(assetDir, assetPath)) { - uri = path.toUri( - path.join('assets', package.name, path.relative(assetPath, from: assetDir))); - } else { - continue; - } - - return Future.wait(_directories.values.map((dir) { - return dir.server.then((server) => server.url.resolveUri(uri)); - })); - } - - return new Future.value([]); - } - - /// Given a URL to an asset served by this environment, returns the ID of the - /// asset that would be accessed by that URL. - /// - /// If no server can serve [url], completes to `null`. - Future getAssetIdForUrl(Uri url) { - return Future.wait( - _directories.values.map((dir) => dir.server)).then((servers) { - var server = servers.firstWhere((server) { - if (server.port != url.port) return false; - return isLoopback(server.address.host) == isLoopback(url.host) || - server.address.host == url.host; - }, orElse: () => null); - if (server == null) return null; - return server.urlToId(url); - }); - } - - /// Determines if [sourcePath] is contained within any of the directories in - /// the root package that are visible to this build environment. - bool containsPath(String sourcePath) { - var directories = ["lib"]; - directories.addAll(_directories.keys); - return directories.any((dir) => path.isWithin(dir, sourcePath)); - } - - /// Pauses sending source asset updates to barback. - void pauseUpdates() { - // Cannot pause while already paused. - assert(_modifiedSources == null); - - _modifiedSources = new Set(); - } - - /// Sends any pending source updates to barback and begins the asynchronous - /// build process. - void resumeUpdates() { - // Cannot resume while not paused. - assert(_modifiedSources != null); - - barback.updateSources(_modifiedSources); - _modifiedSources = null; - } - - /// Loads the assets and transformers for this environment. - /// - /// This transforms and serves all library and asset files in all packages in - /// the environment's package graph. It loads any transformer plugins defined - /// in packages in [graph] and re-runs them as necessary when any input files - /// change. - /// - /// If [useDart2JS] is `true`, then the [Dart2JSTransformer] is implicitly - /// added to end of the root package's transformer phases. - /// - /// If [entrypoints] is passed, only transformers necessary to run those - /// entrypoints will be loaded. - /// - /// Returns a [Future] that completes once all inputs and transformers are - /// loaded. - Future _load({Iterable entrypoints, bool useDart2JS}) { - return log.progress("Initializing barback", () { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var containsDart2JS = - graph.entrypoint.root.pubspec.transformers.any(((transformers) { - return transformers.any( - (config) => config.id.package == '\$dart2js'); - })); - join0() { - new Future.value(BarbackServer.bind(this, _hostname, 0)).then((x0) { - try { - var transformerServer = x0; - var errorStream = barback.errors.map(((error) { - if (error is! AssetLoadException) throw error; - log.error(log.red(error.message)); - log.fine(error.stackTrace.terse); - })); - new Future.value(_withStreamErrors((() { - return log.progress("Loading source assets", _provideSources); - }), [errorStream, barback.results])).then((x1) { - try { - x1; - log.fine("Provided sources."); - errorStream = barback.errors.map(((error) { - if (error is! TransformerException) throw error; - var message = error.error.toString(); - if (error.stackTrace != null) { - message += "\n" + error.stackTrace.terse.toString(); - } - _log( - new LogEntry( - error.transform, - error.transform.primaryId, - LogLevel.ERROR, - message, - null)); - })); - new Future.value(_withStreamErrors((() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - completer0.complete( - log.progress("Loading transformers", (() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value( - loadAllTransformers( - this, - transformerServer, - entrypoints: entrypoints)).then((x0) { - try { - x0; - transformerServer.close(); - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }), fine: true)); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }), - [errorStream, barback.results, transformerServer.results])).then((x2) { - try { - x2; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }, onError: completer0.completeError); - } - if (!containsDart2JS && useDart2JS) { - _builtInTransformers.addAll( - [new Dart2JSTransformer(this, mode), new DartForwardingTransformer(mode)]); - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }, fine: true); - } - - /// Provides the public source assets in the environment to barback. - /// - /// If [watcherType] is not [WatcherType.NONE], enables watching on them. - Future _provideSources() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value(Future.wait(graph.packages.values.map(((package) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - new Future.value( - _provideDirectorySources(package, "lib")).then((x0) { - try { - x0; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (graph.isPackageStatic(package.name)) { - completer0.complete(null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x0) { - try { - x0; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Provides all of the source assets within [dir] in [package] to barback. - /// - /// If [watcherType] is not [WatcherType.NONE], enables watching on them. - /// Returns the subscription to the watcher, or `null` if none was created. - Future> - _provideDirectorySources(Package package, String dir) { - log.fine("Providing sources for ${package.name}|$dir."); - // TODO(rnystrom): Handle overlapping directories. If two served - // directories overlap like so: - // - // $ pub serve example example/subdir - // - // Then the sources of the subdirectory will be updated and watched twice. - // See: #17454 - if (_watcherType == WatcherType.NONE) { - _updateDirectorySources(package, dir); - return new Future.value(); - } - - // Watch the directory before listing is so we don't miss files that - // are added between the initial list and registering the watcher. - return _watchDirectorySources(package, dir).then((_) { - _updateDirectorySources(package, dir); - }); - } - - /// Updates barback with all of the files in [dir] inside [package]. - void _updateDirectorySources(Package package, String dir) { - var ids = _listDirectorySources(package, dir); - if (_modifiedSources == null) { - barback.updateSources(ids); - } else { - _modifiedSources.addAll(ids); - } - } - - /// Removes all of the files in [dir] in the root package from barback. - void _removeDirectorySources(String dir) { - var ids = _listDirectorySources(rootPackage, dir); - if (_modifiedSources == null) { - barback.removeSources(ids); - } else { - _modifiedSources.removeAll(ids); - } - } - - /// Lists all of the source assets in [dir] inside [package]. - /// - /// For large packages, listing the contents is a performance bottleneck, so - /// this is optimized for our needs in here instead of using the more general - /// but slower [listDir]. - Iterable _listDirectorySources(Package package, String dir) { - // This is used in some performance-sensitive paths and can list many, many - // files. As such, it leans more havily towards optimization as opposed to - // readability than most code in pub. In particular, it avoids using the - // path package, since re-parsing a path is very expensive relative to - // string operations. - return package.listFiles(beneath: dir).map((file) { - // From profiling, path.relative here is just as fast as a raw substring - // and is correct in the case where package.dir has a trailing slash. - var relative = package.relative(file); - - if (Platform.operatingSystem == 'windows') { - relative = relative.replaceAll("\\", "/"); - } - - var uri = new Uri(pathSegments: relative.split("/")); - return new AssetId(package.name, uri.toString()); - }); - } - - /// Adds a file watcher for [dir] within [package], if the directory exists - /// and the package needs watching. - Future> _watchDirectorySources(Package package, - String dir) { - // If this package comes from a cached source, its contents won't change so - // we don't need to monitor it. `packageId` will be null for the - // application package, since that's not locked. - var packageId = graph.lockFile.packages[package.name]; - if (packageId != null && - graph.entrypoint.cache.sources[packageId.source] is CachedSource) { - return new Future.value(); - } - - var subdirectory = package.path(dir); - if (!dirExists(subdirectory)) return new Future.value(); - - // TODO(nweiz): close this watcher when [barback] is closed. - var watcher = _watcherType.create(subdirectory); - var subscription = watcher.events.listen((event) { - // Don't watch files symlinked into these directories. - // TODO(rnystrom): If pub gets rid of symlinks, remove this. - var parts = path.split(event.path); - if (parts.contains("packages")) return; - - // Skip files that were (most likely) compiled from nearby ".dart" - // files. These are created by the Editor's "Run as JavaScript" - // command and are written directly into the package's directory. - // When pub's dart2js transformer then tries to create the same file - // name, we get a build error. To avoid that, just don't consider - // that file to be a source. - // TODO(rnystrom): Remove these when the Editor no longer generates - // .js files and users have had enough time that they no longer have - // these files laying around. See #15859. - if (event.path.endsWith(".dart.js")) return; - if (event.path.endsWith(".dart.js.map")) return; - if (event.path.endsWith(".dart.precompiled.js")) return; - - var idPath = package.relative(event.path); - var id = new AssetId(package.name, path.toUri(idPath).toString()); - if (event.type == ChangeType.REMOVE) { - if (_modifiedSources != null) { - _modifiedSources.remove(id); - } else { - barback.removeSources([id]); - } - } else if (_modifiedSources != null) { - _modifiedSources.add(id); - } else { - barback.updateSources([id]); - } - }); - - return watcher.ready.then((_) => subscription); - } - - /// Returns the result of [futureCallback] unless any stream in [streams] - /// emits an error before it's done. - /// - /// If a stream does emit an error, that error is thrown instead. - /// [futureCallback] is a callback rather than a plain future to ensure that - /// [streams] are listened to before any code that might cause an error starts - /// running. - Future _withStreamErrors(Future futureCallback(), List streams) { - var completer = new Completer.sync(); - var subscriptions = streams.map( - (stream) => stream.listen((_) {}, onError: completer.completeError)).toList(); - - new Future.sync(futureCallback).then((_) { - if (!completer.isCompleted) completer.complete(); - }).catchError((error, stackTrace) { - if (!completer.isCompleted) completer.completeError(error, stackTrace); - }); - - return completer.future.whenComplete(() { - for (var subscription in subscriptions) { - subscription.cancel(); - } - }); - } -} - -/// Log [entry] using Pub's logging infrastructure. -/// -/// Since both [LogEntry] objects and the message itself often redundantly -/// show the same context like the file where an error occurred, this tries -/// to avoid showing redundant data in the entry. -void _log(LogEntry entry) { - messageMentions(text) => - entry.message.toLowerCase().contains(text.toLowerCase()); - - messageMentionsAsset(id) => - messageMentions(id.toString()) || - messageMentions(path.fromUri(entry.assetId.path)); - - var prefixParts = []; - - // Show the level (unless the message mentions it). - if (!messageMentions(entry.level.name)) { - prefixParts.add("${entry.level} from"); - } - - // Show the transformer. - prefixParts.add(entry.transform.transformer); - - // Mention the primary input of the transform unless the message seems to. - if (!messageMentionsAsset(entry.transform.primaryId)) { - prefixParts.add("on ${entry.transform.primaryId}"); - } - - // If the relevant asset isn't the primary input, mention it unless the - // message already does. - if (entry.assetId != entry.transform.primaryId && - !messageMentionsAsset(entry.assetId)) { - prefixParts.add("with input ${entry.assetId}"); - } - - var prefix = "[${prefixParts.join(' ')}]:"; - var message = entry.message; - if (entry.span != null) { - message = entry.span.message(entry.message); - } - - switch (entry.level) { - case LogLevel.ERROR: - log.error("${log.red(prefix)}\n$message"); - break; - - case LogLevel.WARNING: - log.warning("${log.yellow(prefix)}\n$message"); - break; - - case LogLevel.INFO: - log.message("${log.cyan(prefix)}\n$message"); - break; - - case LogLevel.FINE: - log.fine("${log.gray(prefix)}\n$message"); - break; - } -} - -/// Exception thrown when trying to serve a new directory that overlaps one or -/// more directories already being served. -class OverlappingSourceDirectoryException implements Exception { - /// The relative paths of the directories that overlap the one that could not - /// be served. - final List overlappingDirectories; - - OverlappingSourceDirectoryException(this.overlappingDirectories); -} - -/// An enum describing different modes of constructing a [DirectoryWatcher]. -abstract class WatcherType { - /// A watcher that automatically chooses its type based on the operating - /// system. - static const AUTO = const _AutoWatcherType(); - - /// A watcher that always polls the filesystem for changes. - static const POLLING = const _PollingWatcherType(); - - /// No directory watcher at all. - static const NONE = const _NoneWatcherType(); - - /// Creates a new DirectoryWatcher. - DirectoryWatcher create(String directory); - - String toString(); -} - -class _AutoWatcherType implements WatcherType { - const _AutoWatcherType(); - - DirectoryWatcher create(String directory) => new DirectoryWatcher(directory); - - String toString() => "auto"; -} - -class _PollingWatcherType implements WatcherType { - const _PollingWatcherType(); - - DirectoryWatcher create(String directory) => - new PollingDirectoryWatcher(directory); - - String toString() => "polling"; -} - -class _NoneWatcherType implements WatcherType { - const _NoneWatcherType(); - - DirectoryWatcher create(String directory) => null; - - String toString() => "none"; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/barback_server.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/barback_server.dart deleted file mode 100644 index 24658e22592..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/barback_server.dart +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.server; - -import 'dart:async'; -import 'dart:io'; - -import 'package:barback/barback.dart'; -import 'package:mime/mime.dart'; -import 'package:path/path.dart' as path; -import 'package:shelf/shelf.dart' as shelf; -import 'package:stack_trace/stack_trace.dart'; - -import '../barback.dart'; -import '../io.dart'; -import '../log.dart' as log; -import '../utils.dart'; -import 'base_server.dart'; -import 'asset_environment.dart'; - -/// Callback for determining if an asset with [id] should be served or not. -typedef bool AllowAsset(AssetId id); - -/// A server that serves assets transformed by barback. -class BarbackServer extends BaseServer { - /// The package whose assets are being served. - final String package; - - /// The directory in the root which will serve as the root of this server as - /// a native platform path. - /// - /// This may be `null` in which case no files in the root package can be - /// served and only assets in "lib" directories are available. - final String rootDirectory; - - /// Optional callback to determine if an asset should be served. - /// - /// This can be set to allow outside code to filter out assets. Pub serve - /// uses this after plug-ins are loaded to avoid serving ".dart" files in - /// release mode. - /// - /// If this is `null`, all assets may be served. - AllowAsset allowAsset; - - /// Creates a new server and binds it to [port] of [host]. - /// - /// This server serves assets from [barback], and uses [rootDirectory] - /// (which is relative to the root directory of [package]) as the root - /// directory. If [rootDirectory] is omitted, the bound server can only be - /// used to serve assets from packages' lib directories (i.e. "packages/..." - /// URLs). If [package] is omitted, it defaults to the entrypoint package. - static Future bind(AssetEnvironment environment, String host, - int port, {String package, String rootDirectory}) { - if (package == null) package = environment.rootPackage.name; - return bindServer(host, port).then((server) { - if (rootDirectory == null) { - log.fine('Serving packages on $host:$port.'); - } else { - log.fine('Bound "$rootDirectory" to $host:$port.'); - } - return new BarbackServer._(environment, server, package, rootDirectory); - }); - } - - BarbackServer._(AssetEnvironment environment, HttpServer server, this.package, - this.rootDirectory) - : super(environment, server); - - /// Converts a [url] served by this server into an [AssetId] that can be - /// requested from barback. - AssetId urlToId(Uri url) { - // See if it's a URL to a public directory in a dependency. - var id = packagesUrlToId(url); - if (id != null) return id; - - if (rootDirectory == null) { - throw new FormatException( - "This server cannot serve out of the root directory. Got $url."); - } - - // Otherwise, it's a path in current package's [rootDirectory]. - var parts = path.url.split(url.path); - - // Strip the leading "/" from the URL. - if (parts.isNotEmpty && parts.first == "/") parts = parts.skip(1); - - var relativePath = path.url.join(rootDirectory, path.url.joinAll(parts)); - return new AssetId(package, relativePath); - } - - /// Handles an HTTP request. - handleRequest(shelf.Request request) { - if (request.method != "GET" && request.method != "HEAD") { - return methodNotAllowed(request); - } - - var id; - try { - id = urlToId(request.url); - } on FormatException catch (ex) { - // If we got here, we had a path like "/packages" which is a special - // directory, but not a valid path since it lacks a following package - // name. - return notFound(request, error: ex.message); - } - - // See if the asset should be blocked. - if (allowAsset != null && !allowAsset(id)) { - return notFound( - request, - error: "Asset $id is not available in this configuration.", - asset: id); - } - - return environment.barback.getAssetById(id).then((result) { - return result; - }).then((asset) => _serveAsset(request, asset)).catchError((error, trace) { - if (error is! AssetNotFoundException) throw error; - return environment.barback.getAssetById( - id.addExtension("/index.html")).then((asset) { - if (request.url.path.endsWith('/')) return _serveAsset(request, asset); - - // We only want to serve index.html if the URL explicitly ends in a - // slash. For other URLs, we redirect to one with the slash added to - // implicitly support that too. This follows Apache's behavior. - logRequest(request, "302 Redirect to ${request.url}/"); - return new shelf.Response.found('${request.url}/'); - }).catchError((newError, newTrace) { - // If we find neither the original file or the index, we should report - // the error about the original to the user. - throw newError is AssetNotFoundException ? error : newError; - }); - }).catchError((error, trace) { - if (error is! AssetNotFoundException) { - trace = new Chain.forTrace(trace); - logRequest(request, "$error\n$trace"); - - addError(error, trace); - close(); - return new shelf.Response.internalServerError(); - } - - addResult(new BarbackServerResult._failure(request.url, id, error)); - return notFound(request, asset: id); - }).then((response) { - // Allow requests of any origin to access "pub serve". This is useful for - // running "pub serve" in parallel with another development server. Since - // "pub serve" is only used as a development server and doesn't require - // any sort of credentials anyway, this is secure. - return response.change(headers: const { - "Access-Control-Allow-Origin": "*" - }); - }); - } - - /// Returns the body of [asset] as a response to [request]. - Future _serveAsset(shelf.Request request, Asset asset) { - return validateStream(asset.read()).then((stream) { - addResult(new BarbackServerResult._success(request.url, asset.id)); - var headers = {}; - var mimeType = lookupMimeType(asset.id.path); - if (mimeType != null) headers['Content-Type'] = mimeType; - return new shelf.Response.ok(stream, headers: headers); - }).catchError((error, trace) { - addResult(new BarbackServerResult._failure(request.url, asset.id, error)); - - // If we couldn't read the asset, handle the error gracefully. - if (error is FileSystemException) { - // Assume this means the asset was a file-backed source asset - // and we couldn't read it, so treat it like a missing asset. - return notFound(request, error: error.toString(), asset: asset.id); - } - - trace = new Chain.forTrace(trace); - logRequest(request, "$error\n$trace"); - - // Otherwise, it's some internal error. - return new shelf.Response.internalServerError(body: error.toString()); - }); - } -} - -/// The result of the server handling a URL. -/// -/// Only requests for which an asset was requested from barback will emit a -/// result. Malformed requests will be handled internally. -class BarbackServerResult { - /// The requested url. - final Uri url; - - /// The id that [url] identifies. - final AssetId id; - - /// The error thrown by barback. - /// - /// If the request was served successfully, this will be null. - final error; - - /// Whether the request was served successfully. - bool get isSuccess => error == null; - - /// Whether the request was served unsuccessfully. - bool get isFailure => !isSuccess; - - BarbackServerResult._success(this.url, this.id) - : error = null; - - BarbackServerResult._failure(this.url, this.id, this.error); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/base_server.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/base_server.dart deleted file mode 100644 index e95c5d37f6e..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/base_server.dart +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.base_server; - -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:barback/barback.dart'; -import 'package:shelf/shelf.dart' as shelf; -import 'package:shelf/shelf_io.dart' as shelf_io; - -import '../log.dart' as log; -import '../utils.dart'; -import 'asset_environment.dart'; - -/// Base class for a pub-controlled server. -abstract class BaseServer { - /// The [BuildEnvironment] being served. - final AssetEnvironment environment; - - /// The underlying HTTP server. - final HttpServer _server; - - /// The server's port. - int get port => _server.port; - - /// The servers's address. - InternetAddress get address => _server.address; - - /// The server's base URL. - Uri get url => baseUrlForAddress(_server.address, port); - - /// The results of requests handled by the server. - /// - /// These can be used to provide visual feedback for the server's processing. - /// This stream is also used to emit any programmatic errors that occur in the - /// server. - Stream get results => _resultsController.stream; - final _resultsController = new StreamController.broadcast(); - - BaseServer(this.environment, this._server) { - shelf_io.serveRequests( - _server, - const shelf.Pipeline().addMiddleware( - shelf.createMiddleware(errorHandler: _handleError)).addHandler(handleRequest)); - } - - /// Closes this server. - Future close() { - return Future.wait([_server.close(), _resultsController.close()]); - } - - /// Handles an HTTP request. - handleRequest(shelf.Request request); - - /// Returns a 405 response to [request]. - shelf.Response methodNotAllowed(shelf.Request request) { - logRequest(request, "405 Method Not Allowed"); - return new shelf.Response( - 405, - body: "The ${request.method} method is not allowed for ${request.url}.", - headers: { - 'Allow': 'GET, HEAD' - }); - } - - /// Returns a 404 response to [request]. - /// - /// If [asset] is given, it is the ID of the asset that couldn't be found. - shelf.Response notFound(shelf.Request request, {String error, - AssetId asset}) { - logRequest(request, "Not Found"); - - // TODO(rnystrom): Apply some styling to make it visually clear that this - // error is coming from pub serve itself. - var body = new StringBuffer(); - body.writeln(""" - - - 404 Not Found - - -

404 Not Found

"""); - - if (asset != null) { - body.writeln( - "

Could not find asset " - "${HTML_ESCAPE.convert(asset.path)} in package " - "${HTML_ESCAPE.convert(asset.package)}.

"); - } - - if (error != null) { - body.writeln("

Error: ${HTML_ESCAPE.convert(error)}

"); - } - - body.writeln(""" - """); - - // Force a UTF-8 encoding so that error messages in non-English locales are - // sent correctly. - return new shelf.Response.notFound(body.toString(), headers: { - 'Content-Type': 'text/html; charset=utf-8' - }); - } - - /// Log [message] at [log.Level.FINE] with metadata about [request]. - void logRequest(shelf.Request request, String message) => - log.fine("$this ${request.method} ${request.url}\n$message"); - - /// Adds [result] to the server's [results] stream. - void addResult(T result) { - _resultsController.add(result); - } - - /// Adds [error] as an error to the server's [results] stream. - void addError(error, [stackTrace]) { - _resultsController.addError(error, stackTrace); - } - - /// Handles an error thrown by [handleRequest]. - _handleError(error, StackTrace stackTrace) { - _resultsController.addError(error, stackTrace); - close(); - return new shelf.Response.internalServerError(); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/cycle_exception.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/cycle_exception.dart deleted file mode 100644 index 8fdd04788b4..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/cycle_exception.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.cycle_exception; - -import '../exceptions.dart'; - -/// An exception thrown when a transformer dependency cycle is detected. -/// -/// A cycle exception is usually produced within a deeply-nested series of -/// calls. The API is designed to make it easy for each of these calls to add to -/// the message so that the full reasoning for the cycle is made visible to the -/// user. -/// -/// Each call's individual message is called a "step". A [CycleException] is -/// represented internally as a linked list of steps. -class CycleException implements ApplicationException { - /// The step for this exception. - final String _step; - - /// The next exception in the linked list. - /// - /// [_next]'s steps come after [_step]. - final CycleException _next; - - /// A list of all steps in the cycle. - List get steps { - if (_step == null) return []; - - var exception = this; - var steps = []; - while (exception != null) { - steps.add(exception._step); - exception = exception._next; - } - return steps; - } - - String get message { - var steps = this.steps; - if (steps.isEmpty) return "Transformer cycle detected."; - return "Transformer cycle detected:\n" + - steps.map((step) => " $step").join("\n"); - } - - /// Creates a new [CycleException] with zero or one steps. - CycleException([this._step]) - : _next = null; - - CycleException._(this._step, this._next); - - /// Returns a copy of [this] with [step] added to the beginning of [steps]. - CycleException prependStep(String step) { - if (_step == null) return new CycleException(step); - return new CycleException._(step, this); - } - - String toString() => message; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/dart2js_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/dart2js_transformer.dart deleted file mode 100644 index 3910ef8be56..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/dart2js_transformer.dart +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.dart2js_transformer; - -import 'dart:async'; -import 'dart:convert'; - -import 'package:analyzer/analyzer.dart'; -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as path; -import 'package:pool/pool.dart'; - -import '../../../../../../../pkg/compiler/lib/compiler.dart' as compiler; -import '../../../../../../../pkg/compiler/lib/src/dart2js.dart' show AbortLeg; -import '../../../../../../../pkg/compiler/lib/src/io/source_file.dart'; -import '../barback.dart'; -import '../dart.dart' as dart; -import '../utils.dart'; -import 'asset_environment.dart'; - -/// The set of all valid configuration options for this transformer. -final _validOptions = new Set.from( - [ - 'commandLineOptions', - 'checked', - 'csp', - 'minify', - 'verbose', - 'environment', - 'preserveUris', - 'suppressWarnings', - 'suppressHints', - 'suppressPackageWarnings', - 'terse']); - -/// A [Transformer] that uses dart2js's library API to transform Dart -/// entrypoints in "web" to JavaScript. -class Dart2JSTransformer extends Transformer implements LazyTransformer { - /// We use this to ensure that only one compilation is in progress at a time. - /// - /// Dart2js uses lots of memory, so if we try to actually run compiles in - /// parallel, it takes down the VM. The tracking bug to do something better - /// is here: https://code.google.com/p/dart/issues/detail?id=14730. - static final _pool = new Pool(1); - - final AssetEnvironment _environment; - final BarbackSettings _settings; - - /// Whether source maps should be generated for the compiled JS. - bool get _generateSourceMaps => _settings.mode != BarbackMode.RELEASE; - - Dart2JSTransformer.withSettings(this._environment, this._settings) { - var invalidOptions = - _settings.configuration.keys.toSet().difference(_validOptions); - if (invalidOptions.isEmpty) return; - - throw new FormatException( - "Unrecognized dart2js " "${pluralize('option', invalidOptions.length)} " - "${toSentence(invalidOptions.map((option) => '"$option"'))}."); - } - - Dart2JSTransformer(AssetEnvironment environment, BarbackMode mode) - : this.withSettings(environment, new BarbackSettings({}, mode)); - - /// Only ".dart" entrypoint files within a buildable directory are processed. - bool isPrimary(AssetId id) { - if (id.extension != ".dart") return false; - - // "lib" should only contain libraries. For efficiency's sake, we don't - // look for entrypoints in there. - return !id.path.startsWith("lib/"); - } - - Future apply(Transform transform) { - // TODO(nweiz): If/when barback starts reporting what assets were modified, - // don't re-run the entrypoint detection logic unless the primary input was - // actually modified. See issue 16817. - return _isEntrypoint(transform.primaryInput).then((isEntrypoint) { - if (!isEntrypoint) return null; - - // Wait for any ongoing apply to finish first. - return _pool.withResource(() { - transform.logger.info("Compiling ${transform.primaryInput.id}..."); - var stopwatch = new Stopwatch()..start(); - return _doCompilation(transform).then((_) { - stopwatch.stop(); - transform.logger.info( - "Took ${stopwatch.elapsed} to compile " "${transform.primaryInput.id}."); - }); - }); - }); - } - - void declareOutputs(DeclaringTransform transform) { - var primaryId = transform.primaryId; - transform.declareOutput(primaryId.addExtension(".js")); - if (_generateSourceMaps) { - transform.declareOutput(primaryId.addExtension(".js.map")); - } - } - - /// Returns whether or not [asset] might be an entrypoint. - Future _isEntrypoint(Asset asset) { - return asset.readAsString().then((code) { - try { - var name = asset.id.path; - if (asset.id.package != _environment.rootPackage.name) { - name += " in ${asset.id.package}"; - } - - var parsed = parseCompilationUnit(code, name: name); - return dart.isEntrypoint(parsed); - } on AnalyzerErrorGroup catch (e) { - // If we get a parse error, consider the asset primary so we report - // dart2js's more detailed error message instead. - return true; - } - }); - } - - /// Run the dart2js compiler. - Future _doCompilation(Transform transform) { - var provider = new _BarbackCompilerProvider( - _environment, - transform, - generateSourceMaps: _generateSourceMaps); - - // Create a "path" to the entrypoint script. The entrypoint may not actually - // be on disk, but this gives dart2js a root to resolve relative paths - // against. - var id = transform.primaryInput.id; - - var entrypoint = _environment.graph.packages[id.package].path(id.path); - - // TODO(rnystrom): Should have more sophisticated error-handling here. Need - // to report compile errors to the user in an easily visible way. Need to - // make sure paths in errors are mapped to the original source path so they - // can understand them. - return dart.compile( - entrypoint, - provider, - commandLineOptions: _configCommandLineOptions, - csp: _configBool('csp'), - checked: _configBool('checked'), - minify: _configBool( - 'minify', - defaultsTo: _settings.mode == BarbackMode.RELEASE), - verbose: _configBool('verbose'), - environment: _configEnvironment, - packageRoot: _environment.rootPackage.path("packages"), - analyzeAll: _configBool('analyzeAll'), - preserveUris: _configBool('preserveUris'), - suppressWarnings: _configBool('suppressWarnings'), - suppressHints: _configBool('suppressHints'), - suppressPackageWarnings: _configBool( - 'suppressPackageWarnings', - defaultsTo: true), - terse: _configBool('terse'), - includeSourceMapUrls: _settings.mode != BarbackMode.RELEASE); - } - - /// Parses and returns the "commandLineOptions" configuration option. - List get _configCommandLineOptions { - if (!_settings.configuration.containsKey('commandLineOptions')) return null; - - var options = _settings.configuration['commandLineOptions']; - if (options is List && options.every((option) => option is String)) { - return options; - } - - throw new FormatException( - 'Invalid value for ' - '\$dart2js.commandLineOptions: ${JSON.encode(options)} (expected list ' - 'of strings).'); - } - - /// Parses and returns the "environment" configuration option. - Map get _configEnvironment { - if (!_settings.configuration.containsKey('environment')) return null; - - var environment = _settings.configuration['environment']; - if (environment is Map && - environment.keys.every((key) => key is String) && - environment.values.every((key) => key is String)) { - return environment; - } - - throw new FormatException( - 'Invalid value for \$dart2js.environment: ' - '${JSON.encode(environment)} (expected map from strings to strings).'); - } - - /// Parses and returns a boolean configuration option. - /// - /// [defaultsTo] is the default value of the option. - bool _configBool(String name, {bool defaultsTo: false}) { - if (!_settings.configuration.containsKey(name)) return defaultsTo; - var value = _settings.configuration[name]; - if (value is bool) return value; - throw new FormatException( - 'Invalid value for \$dart2js.$name: ' - '${JSON.encode(value)} (expected true or false).'); - } -} - -/// Defines an interface for dart2js to communicate with barback and pub. -/// -/// Note that most of the implementation of diagnostic handling here was -/// copied from [FormattingDiagnosticHandler] in dart2js. The primary -/// difference is that it uses barback's logging code and, more importantly, it -/// handles missing source files more gracefully. -class _BarbackCompilerProvider implements dart.CompilerProvider { - Uri get libraryRoot => Uri.parse("${path.toUri(_libraryRootPath)}/"); - - final AssetEnvironment _environment; - final Transform _transform; - String _libraryRootPath; - - /// The map of previously loaded files. - /// - /// Used to show where an error occurred in a source file. - final _sourceFiles = new Map(); - - // TODO(rnystrom): Make these configurable. - /// Whether or not warnings should be logged. - var _showWarnings = true; - - /// Whether or not hints should be logged. - var _showHints = true; - - /// Whether or not verbose info messages should be logged. - var _verbose = false; - - /// Whether an exception should be thrown on an error to stop compilation. - var _throwOnError = false; - - /// This gets set after a fatal error is reported to quash any subsequent - /// errors. - var _isAborting = false; - - final bool generateSourceMaps; - - compiler.Diagnostic _lastKind = null; - - static final int _FATAL = - compiler.Diagnostic.CRASH.ordinal | - compiler.Diagnostic.ERROR.ordinal; - static final int _INFO = - compiler.Diagnostic.INFO.ordinal | - compiler.Diagnostic.VERBOSE_INFO.ordinal; - - _BarbackCompilerProvider(this._environment, this._transform, - {this.generateSourceMaps: true}) { - // Dart2js outputs source maps that reference the Dart SDK sources. For - // that to work, those sources need to be inside the build environment. We - // do that by placing them in a special "$sdk" pseudo-package. In order for - // dart2js to generate the right URLs to point to that package, we give it - // a library root that corresponds to where that package can be found - // relative to the public source directory containing that entrypoint. - // - // For example, say the package being compiled is "/dev/myapp", the - // entrypoint is "web/sub/foo/bar.dart", and the source directory is - // "web/sub". This means the SDK sources will be (conceptually) at: - // - // /dev/myapp/web/sub/packages/$sdk/lib/ - // - // This implies that the asset path for a file in the SDK is: - // - // $sdk|lib/lib/... - // - // TODO(rnystrom): Fix this if #17751 is fixed. - var buildDir = - _environment.getSourceDirectoryContaining(_transform.primaryInput.id.path); - _libraryRootPath = - _environment.rootPackage.path(buildDir, "packages", r"$sdk"); - } - - /// A [CompilerInputProvider] for dart2js. - Future provideInput(Uri resourceUri) { - // We only expect to get absolute "file:" URLs from dart2js. - assert(resourceUri.isAbsolute); - assert(resourceUri.scheme == "file"); - - var sourcePath = path.fromUri(resourceUri); - return _readResource(resourceUri).then((source) { - _sourceFiles[resourceUri.toString()] = - new StringSourceFile(path.relative(sourcePath), source); - return source; - }); - } - - /// A [CompilerOutputProvider] for dart2js. - EventSink provideOutput(String name, String extension) { - // TODO(rnystrom): Do this more cleanly. See: #17403. - if (!generateSourceMaps && extension.endsWith(".map")) { - return new NullSink(); - } - - // TODO(nweiz): remove this special case when dart2js stops generating these - // files. - if (extension.endsWith(".precompiled.js")) return new NullSink(); - - var primaryId = _transform.primaryInput.id; - - // Dart2js uses an empty string for the name of the entrypoint library. - // Otherwise, it's the name of a deferred library. - var outPath; - if (name == "") { - outPath = _transform.primaryInput.id.path; - } else { - var dirname = path.url.dirname(_transform.primaryInput.id.path); - outPath = path.url.join(dirname, name); - } - - var id = new AssetId(primaryId.package, "$outPath.$extension"); - - // Make a sink that dart2js can write to. - var sink = new StreamController(); - - // dart2js gives us strings, but stream assets expect byte lists. - var stream = UTF8.encoder.bind(sink.stream); - - // And give it to barback as a stream it can read from. - _transform.addOutput(new Asset.fromStream(id, stream)); - - return sink; - } - - /// A [DiagnosticHandler] for dart2js, loosely based on - /// [FormattingDiagnosticHandler]. - void handleDiagnostic(Uri uri, int begin, int end, String message, - compiler.Diagnostic kind) { - // TODO(ahe): Remove this when source map is handled differently. - if (kind.name == "source map") return; - - if (_isAborting) return; - _isAborting = (kind == compiler.Diagnostic.CRASH); - - var isInfo = (kind.ordinal & _INFO) != 0; - if (isInfo && uri == null && kind != compiler.Diagnostic.INFO) { - if (!_verbose && kind == compiler.Diagnostic.VERBOSE_INFO) return; - _transform.logger.info(message); - return; - } - - // [_lastKind] records the previous non-INFO kind we saw. - // This is used to suppress info about a warning when warnings are - // suppressed, and similar for hints. - if (kind != compiler.Diagnostic.INFO) _lastKind = kind; - - var logFn; - if (kind == compiler.Diagnostic.ERROR) { - logFn = _transform.logger.error; - } else if (kind == compiler.Diagnostic.WARNING) { - if (!_showWarnings) return; - logFn = _transform.logger.warning; - } else if (kind == compiler.Diagnostic.HINT) { - if (!_showHints) return; - logFn = _transform.logger.warning; - } else if (kind == compiler.Diagnostic.CRASH) { - logFn = _transform.logger.error; - } else if (kind == compiler.Diagnostic.INFO) { - if (_lastKind == compiler.Diagnostic.WARNING && !_showWarnings) return; - if (_lastKind == compiler.Diagnostic.HINT && !_showHints) return; - logFn = _transform.logger.info; - } else { - throw new Exception('Unknown kind: $kind (${kind.ordinal})'); - } - - var fatal = (kind.ordinal & _FATAL) != 0; - if (uri == null) { - logFn(message); - } else { - SourceFile file = _sourceFiles[uri.toString()]; - if (file == null) { - // We got a message before loading the file, so just report the message - // itself. - logFn('$uri: $message'); - } else { - logFn(file.getLocationMessage(message, begin, end)); - } - } - - if (fatal && _throwOnError) { - _isAborting = true; - throw new AbortLeg(message); - } - } - - Future _readResource(Uri url) { - return new Future.sync(() { - // Find the corresponding asset in barback. - var id = _sourceUrlToId(url); - if (id != null) return _transform.readInputAsString(id); - - // Don't allow arbitrary file paths that point to things not in packages. - // Doing so won't work in Dartium. - throw new Exception( - "Cannot read $url because it is outside of the build environment."); - }); - } - - AssetId _sourceUrlToId(Uri url) { - // See if it's a package path. - var id = packagesUrlToId(url); - if (id != null) return id; - - // See if it's a path to a "public" asset within the root package. All - // other files in the root package are not visible to transformers, so - // should be loaded directly from disk. - var sourcePath = path.fromUri(url); - if (_environment.containsPath(sourcePath)) { - var relative = - path.toUri(_environment.rootPackage.relative(sourcePath)).toString(); - - return new AssetId(_environment.rootPackage.name, relative); - } - - return null; - } -} - -/// An [EventSink] that discards all data. Provided to dart2js when we don't -/// want an actual output. -class NullSink implements EventSink { - void add(T event) {} - void addError(errorEvent, [StackTrace stackTrace]) {} - void close() {} -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/dart_forwarding_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/dart_forwarding_transformer.dart deleted file mode 100644 index d1129248f48..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/dart_forwarding_transformer.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.dart_forwarding_transformer; - -import 'dart:async'; - -import 'package:barback/barback.dart'; - -import '../utils.dart'; - -/// A single transformer that just forwards any ".dart" file as an output when -/// not in release mode. -/// -/// Since the [Dart2JSTransformer] consumes its inputs, this is used in -/// parallel to make sure the original Dart file is still available for use by -/// Dartium. -class DartForwardingTransformer extends Transformer { - /// The mode that the transformer is running in. - final BarbackMode _mode; - - DartForwardingTransformer(this._mode); - - String get allowedExtensions => ".dart"; - - Future apply(Transform transform) { - return newFuture(() { - transform.addOutput(transform.primaryInput); - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/dependency_computer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/dependency_computer.dart deleted file mode 100644 index f9aff0b3223..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/dependency_computer.dart +++ /dev/null @@ -1,429 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.dependency_computer; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; - -import '../dart.dart'; -import '../io.dart'; -import '../package.dart'; -import '../package_graph.dart'; -import '../utils.dart'; -import 'cycle_exception.dart'; -import 'transformer_config.dart'; -import 'transformer_id.dart'; - -/// A class for determining dependencies between transformers and from Dart -/// libraries onto transformers. -class DependencyComputer { - /// The package graph being analyzed. - final PackageGraph _graph; - - /// The names of packages for which [_PackageDependencyComputer]s are - /// currently loading. - /// - /// This is used to detect transformer cycles. If a package's libraries or - /// transformers are referenced while the transformers that apply to it are - /// being processed, that indicates an unresolvable cycle. - final _loadingPackageComputers = new Set(); - - /// [_PackageDependencyComputer]s that have been loaded. - final _packageComputers = new Map(); - - /// A cache of the results of [transformersNeededByPackage]. - final _transformersNeededByPackages = new Map>(); - - /// The set of all packages that neither use transformers themselves nor - /// import packages that use transformers. - /// - /// This is precomputed before any package computers are loaded. - final _untransformedPackages = new Set(); - - DependencyComputer(this._graph) { - for (var package in ordered(_graph.packages.keys)) { - if (_graph.transitiveDependencies( - package).every((dependency) => dependency.pubspec.transformers.isEmpty)) { - _untransformedPackages.add(package); - } - } - - ordered(_graph.packages.keys).forEach(_loadPackageComputer); - } - - /// Returns a dependency graph for [transformers], or for all transformers if - /// [transformers] is `null`. - /// - /// This graph is represented by a map whose keys are the vertices and whose - /// values are sets representing edges from the given vertex. Each vertex is a - /// [TransformerId]. If there's an edge from `T1` to `T2`, then `T2` must be - /// loaded before `T1` can be loaded. - /// - /// The returned graph is transitively closed. That is, if there's an edge - /// from `T1` to `T2` and an edge from `T2` to `T3`, there's also an edge from - /// `T1` to `T2`. - Map> - transformersNeededByTransformers([Iterable transformers]) { - var result = {}; - - if (transformers == null) { - transformers = ordered(_graph.packages.keys).expand((packageName) { - var package = _graph.packages[packageName]; - return package.pubspec.transformers.expand((phase) { - return phase.expand((config) { - var id = config.id; - if (id.isBuiltInTransformer) return []; - if (id.package != _graph.entrypoint.root.name && - !config.canTransformPublicFiles) { - return []; - } - return [id]; - }); - }); - }); - } - - for (var id in transformers) { - result[id] = _transformersNeededByTransformer(id); - } - return result; - } - - /// Returns the set of all transformers needed to load the library identified - /// by [id]. - Set transformersNeededByLibrary(AssetId id) { - var library = _graph.packages[id.package].path(p.fromUri(id.path)); - _loadPackageComputer(id.package); - return _packageComputers[id.package].transformersNeededByLibrary( - library).where((id) => !id.isBuiltInTransformer).toSet(); - } - - /// Returns the set of all transformers that need to be loaded before [id] is - /// loaded. - Set _transformersNeededByTransformer(TransformerId id) { - if (id.isBuiltInTransformer) return new Set(); - _loadPackageComputer(id.package); - return _packageComputers[id.package]._transformersNeededByTransformer(id); - } - - /// Returns the set of all transformers that need to be loaded before - /// [packageUri] (a "package:" URI) can be safely imported from an external - /// package. - Set _transformersNeededByPackageUri(Uri packageUri) { - var components = p.split(p.fromUri(packageUri.path)); - var packageName = components.first; - if (_untransformedPackages.contains(packageName)) return new Set(); - - var package = _graph.packages[packageName]; - if (package == null) { - // TODO(nweiz): include source range information here. - fail( - 'A transformer imported unknown package "$packageName" (in ' '"$packageUri").'); - } - - var library = package.path('lib', p.joinAll(components.skip(1))); - - _loadPackageComputer(packageName); - return _packageComputers[packageName].transformersNeededByLibrary(library); - } - - /// Returns the set of all transformers that need to be loaded before - /// everything in [rootPackage] can be used. - /// - /// This is conservative in that it returns all transformers that could - /// theoretically affect [rootPackage]. It only looks at which transformers - /// packages use and which packages they depend on; it ignores imports - /// entirely. - /// - /// We fall back on this conservative analysis when a transformer - /// (transitively) imports a transformed library. The result of the - /// transformation may import any dependency or hit any transformer, so we - /// have to assume that it will. - Set _transformersNeededByPackage(String rootPackage) { - if (_untransformedPackages.contains(rootPackage)) return new Set(); - - if (_transformersNeededByPackages.containsKey(rootPackage)) { - return _transformersNeededByPackages[rootPackage]; - } - - var results = new Set(); - var seen = new Set(); - - traversePackage(packageName) { - if (seen.contains(packageName)) return; - seen.add(packageName); - - var package = _graph.packages[packageName]; - for (var phase in package.pubspec.transformers) { - for (var config in phase) { - var id = config.id; - if (id.isBuiltInTransformer) continue; - if (_loadingPackageComputers.contains(id.package)) { - throw new CycleException("$packageName is transformed by $id"); - } - results.add(id); - } - } - - var dependencies = packageName == _graph.entrypoint.root.name ? - package.immediateDependencies : - package.dependencies; - for (var dep in dependencies) { - try { - traversePackage(dep.name); - } on CycleException catch (error) { - throw error.prependStep("$packageName depends on ${dep.name}"); - } - } - } - - traversePackage(rootPackage); - _transformersNeededByPackages[rootPackage] = results; - return results; - } - - - /// Ensure that a [_PackageDependencyComputer] for [packageName] is loaded. - /// - /// If the computer has already been loaded, this does nothing. If the - /// computer is in the process of being loaded, this throws a - /// [CycleException]. - void _loadPackageComputer(String packageName) { - if (_loadingPackageComputers.contains(packageName)) { - throw new CycleException(); - } - if (_packageComputers.containsKey(packageName)) return; - _loadingPackageComputers.add(packageName); - _packageComputers[packageName] = - new _PackageDependencyComputer(this, packageName); - _loadingPackageComputers.remove(packageName); - } -} - -/// A helper class for [computeTransformersNeededByTransformers] that keeps -/// package-specific state and caches over the course of the computation. -class _PackageDependencyComputer { - /// The parent [DependencyComputer]. - final DependencyComputer _dependencyComputer; - - /// The package whose dependencies [this] is computing. - final Package _package; - - /// The set of transformers that currently apply to [this]. - /// - /// This is added to phase-by-phase while [this] is being initialized. This is - /// necessary to model the dependencies of a transformer that's applied to its - /// own package. - final _applicableTransformers = new Set(); - - /// A cache of imports and exports parsed from libraries in this package. - final _directives = new Map>(); - - /// The set of libraries for which there are currently active - /// [transformersNeededByLibrary] calls. - /// - /// This is used to guard against infinite loops caused by libraries in - /// different packages importing one another circularly. - /// [transformersNeededByLibrary] will return an empty set for any active - /// libraries. - final _activeLibraries = new Set(); - - /// A cache of the results of [_transformersNeededByTransformer]. - final _transformersNeededByTransformers = - new Map>(); - - /// A cache of the results of [_getTransitiveExternalDirectives]. - /// - /// This is invalidated whenever [_applicableTransformers] changes. - final _transitiveExternalDirectives = new Map>(); - - _PackageDependencyComputer(DependencyComputer dependencyComputer, - String packageName) - : _dependencyComputer = dependencyComputer, - _package = dependencyComputer._graph.packages[packageName] { - // If [_package] uses its own transformers, there will be fewer transformers - // running on [_package] while its own transformers are loading than there - // will be once all its transformers are finished loading. To handle this, - // we run [_transformersNeededByTransformer] to pre-populate - // [_transformersNeededByLibraries] while [_applicableTransformers] is - // smaller. - for (var phase in _package.pubspec.transformers) { - for (var config in phase) { - var id = config.id; - try { - if (id.package != _package.name) { - // Probe [id]'s transformer dependencies to ensure that it doesn't - // depend on this package. If it does, a CycleError will be thrown. - _dependencyComputer._transformersNeededByTransformer(id); - } else { - // Store the transformers needed specifically with the current set - // of [_applicableTransformers]. When reporting this transformer's - // dependencies, [computeTransformersNeededByTransformers] will use - // this stored set of dependencies rather than the potentially wider - // set that would be recomputed if [transformersNeededByLibrary] - // were called anew. - _transformersNeededByTransformers[id] = - transformersNeededByLibrary(_package.transformerPath(id)); - } - } on CycleException catch (error) { - throw error.prependStep("$packageName is transformed by $id"); - } - } - - // Clear the cached imports and exports because the new transformers may - // start transforming a library whose directives were previously - // statically analyzable. - _transitiveExternalDirectives.clear(); - _applicableTransformers.addAll(phase); - } - } - - /// Returns the set of all transformers that need to be loaded before [id] is - /// loaded. - /// - /// [id] must refer to a transformer in [_package]. - Set _transformersNeededByTransformer(TransformerId id) { - assert(id.package == _package.name); - if (_transformersNeededByTransformers.containsKey(id)) { - return _transformersNeededByTransformers[id]; - } - - _transformersNeededByTransformers[id] = - transformersNeededByLibrary(_package.transformerPath(id)); - return _transformersNeededByTransformers[id]; - } - - /// Returns the set of all transformers that need to be loaded before - /// [library] is imported. - /// - /// If [library] or anything it imports/exports within this package is - /// transformed by [_applicableTransformers], this will return a conservative - /// set of transformers (see also - /// [DependencyComputer._transformersNeededByPackage]). - Set transformersNeededByLibrary(String library) { - library = p.normalize(library); - if (_activeLibraries.contains(library)) return new Set(); - _activeLibraries.add(library); - - try { - var externalDirectives = _getTransitiveExternalDirectives(library); - if (externalDirectives == null) { - var rootName = _dependencyComputer._graph.entrypoint.root.name; - var dependencies = _package.name == rootName ? - _package.immediateDependencies : - _package.dependencies; - - // If anything transitively imported/exported by [library] within this - // package is modified by a transformer, we don't know what it will - // load, so we take the conservative approach and say it depends on - // everything. - return _applicableTransformers.map( - (config) => config.id).toSet().union(unionAll(dependencies.map((dep) { - try { - return _dependencyComputer._transformersNeededByPackage(dep.name); - } on CycleException catch (error) { - throw error.prependStep("${_package.name} depends on ${dep.name}"); - } - }))); - } else { - // If nothing's transformed, then we only depend on the transformers - // used by the external packages' libraries that we import or export. - return unionAll(externalDirectives.map((uri) { - try { - return _dependencyComputer._transformersNeededByPackageUri(uri); - } on CycleException catch (error) { - var packageName = p.url.split(uri.path).first; - throw error.prependStep("${_package.name} depends on $packageName"); - } - })); - } - } finally { - _activeLibraries.remove(library); - } - } - - /// Returns the set of all external package libraries transitively imported or - /// exported by [rootLibrary]. - /// - /// All of the returned URIs will have the "package:" scheme. None of them - /// will be URIs for this package. - /// - /// If [rootLibrary] transitively imports or exports a library that's modified - /// by a transformer, this will return `null`. - Set _getTransitiveExternalDirectives(String rootLibrary) { - rootLibrary = p.normalize(rootLibrary); - if (_transitiveExternalDirectives.containsKey(rootLibrary)) { - return _transitiveExternalDirectives[rootLibrary]; - } - - var results = new Set(); - var seen = new Set(); - - traverseLibrary(library) { - library = p.normalize(library); - if (seen.contains(library)) return true; - seen.add(library); - - var directives = _getDirectives(library); - if (directives == null) return false; - - for (var uri in directives) { - var path; - if (uri.scheme == 'package') { - var components = p.split(p.fromUri(uri.path)); - if (components.first != _package.name) { - results.add(uri); - continue; - } - - path = _package.path('lib', p.joinAll(components.skip(1))); - } else if (uri.scheme == '' || uri.scheme == 'file') { - path = p.join(p.dirname(library), p.fromUri(uri)); - } else { - // Ignore "dart:" URIs and theoretically-possible "http:" URIs. - continue; - } - - if (!traverseLibrary(path)) return false; - } - - return true; - } - - _transitiveExternalDirectives[rootLibrary] = - traverseLibrary(rootLibrary) ? results : null; - return _transitiveExternalDirectives[rootLibrary]; - } - - /// Returns the set of all imports or exports in [library]. - /// - /// If [library] is modified by a transformer, this will return `null`. - Set _getDirectives(String library) { - var libraryUri = p.toUri(p.normalize(library)); - var relative = p.toUri(_package.relative(library)).path; - if (_applicableTransformers.any( - (config) => config.canTransform(relative))) { - _directives[libraryUri] = null; - return null; - } - - // Check the cache *after* checking [_applicableTransformers] because - // [_applicableTransformers] changes over time so the directives may be - // invalidated. - if (_directives.containsKey(libraryUri)) return _directives[libraryUri]; - - // If a nonexistent library is imported, it will probably be generated by a - // transformer. - if (!fileExists(library)) { - _directives[libraryUri] = null; - return null; - } - - _directives[libraryUri] = parseImportsAndExports( - readTextFile(library), - name: library).map((directive) => Uri.parse(directive.uri.stringValue)).toSet(); - return _directives[libraryUri]; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_aggregate_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_aggregate_transformer.dart deleted file mode 100644 index a45f824bf89..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_aggregate_transformer.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.excluding_aggregate_transformer; - -import 'dart:async'; - -import 'package:barback/barback.dart'; - -import 'transformer_config.dart'; - -/// Decorates an inner [AggregateTransformer] and handles including and -/// excluding primary inputs. -class ExcludingAggregateTransformer extends AggregateTransformer { - /// If [config] defines includes or excludes, wraps [inner] in an - /// [ExcludingAggregateTransformer] that handles those. - /// - /// Otherwise, just returns [inner] unmodified. - static AggregateTransformer wrap(AggregateTransformer inner, - TransformerConfig config) { - if (!config.hasExclusions) return inner; - - if (inner is LazyAggregateTransformer) { - return new _LazyExcludingAggregateTransformer( - inner as LazyAggregateTransformer, - config); - } else if (inner is DeclaringAggregateTransformer) { - return new _DeclaringExcludingAggregateTransformer( - inner as DeclaringAggregateTransformer, - config); - } else { - return new ExcludingAggregateTransformer._(inner, config); - } - } - - final AggregateTransformer _inner; - - /// The config containing rules for which assets to include or exclude. - final TransformerConfig _config; - - ExcludingAggregateTransformer._(this._inner, this._config); - - classifyPrimary(AssetId id) { - if (!_config.canTransform(id.path)) return null; - return _inner.classifyPrimary(id); - } - - Future apply(AggregateTransform transform) => _inner.apply(transform); - - String toString() => _inner.toString(); -} - -class _DeclaringExcludingAggregateTransformer extends - ExcludingAggregateTransformer implements DeclaringAggregateTransformer { - _DeclaringExcludingAggregateTransformer(DeclaringAggregateTransformer inner, - TransformerConfig config) - : super._(inner as AggregateTransformer, config); - - Future declareOutputs(DeclaringAggregateTransform transform) => - (_inner as DeclaringAggregateTransformer).declareOutputs(transform); -} - -class _LazyExcludingAggregateTransformer extends - _DeclaringExcludingAggregateTransformer implements LazyAggregateTransformer { - _LazyExcludingAggregateTransformer(DeclaringAggregateTransformer inner, - TransformerConfig config) - : super(inner, config); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_transformer.dart deleted file mode 100644 index 52d90a991d2..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/excluding_transformer.dart +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.excluding_transformer; - -import 'dart:async'; - -import 'package:barback/barback.dart'; - -import 'transformer_config.dart'; - -/// Decorates an inner [Transformer] and handles including and excluding -/// primary inputs. -class ExcludingTransformer extends Transformer { - /// If [config] defines includes or excludes, wraps [inner] in an - /// [ExcludingTransformer] that handles those. - /// - /// Otherwise, just returns [inner] unmodified. - static Transformer wrap(Transformer inner, TransformerConfig config) { - if (!config.hasExclusions) return inner; - - if (inner is LazyTransformer) { - // TODO(nweiz): Remove these unnecessary "as"es when issue 19046 is fixed. - return new _LazyExcludingTransformer(inner as LazyTransformer, config); - } else if (inner is DeclaringTransformer) { - return new _DeclaringExcludingTransformer( - inner as DeclaringTransformer, - config); - } else { - return new ExcludingTransformer._(inner, config); - } - } - - final Transformer _inner; - - /// The config containing rules for which assets to include or exclude. - final TransformerConfig _config; - - ExcludingTransformer._(this._inner, this._config); - - isPrimary(AssetId id) { - if (!_config.canTransform(id.path)) return false; - return _inner.isPrimary(id); - } - - Future apply(Transform transform) => _inner.apply(transform); - - String toString() => _inner.toString(); -} - -class _DeclaringExcludingTransformer extends ExcludingTransformer implements - DeclaringTransformer { - _DeclaringExcludingTransformer(DeclaringTransformer inner, - TransformerConfig config) - : super._(inner as Transformer, config); - - Future declareOutputs(DeclaringTransform transform) => - (_inner as DeclaringTransformer).declareOutputs(transform); -} - -class _LazyExcludingTransformer extends _DeclaringExcludingTransformer - implements LazyTransformer { - _LazyExcludingTransformer(DeclaringTransformer inner, - TransformerConfig config) - : super(inner, config); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/foreign_transformer.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/foreign_transformer.dart deleted file mode 100644 index 6ab11145b9c..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/foreign_transformer.dart +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.foreign_transformer; - -import 'dart:async'; -import 'dart:isolate'; - -import 'package:barback/barback.dart'; - -import '../../../asset/dart/serialize.dart'; -import 'excluding_transformer.dart'; -import 'excluding_aggregate_transformer.dart'; -import 'transformer_config.dart'; - -/// A wrapper for a transformer that's in a different isolate. -class _ForeignTransformer extends Transformer { - /// The port with which we communicate with the child isolate. - /// - /// This port and all messages sent across it are specific to this - /// transformer. - final SendPort _port; - - /// The result of calling [toString] on the transformer in the isolate. - final String _toString; - - _ForeignTransformer(Map map) - : _port = map['port'], - _toString = map['toString']; - - Future isPrimary(AssetId id) { - return call(_port, { - 'type': 'isPrimary', - 'id': serializeId(id) - }); - } - - Future apply(Transform transform) { - return call(_port, { - 'type': 'apply', - 'transform': serializeTransform(transform) - }); - } - - String toString() => _toString; -} - -class _ForeignDeclaringTransformer extends _ForeignTransformer implements - DeclaringTransformer { - _ForeignDeclaringTransformer(Map map) - : super(map); - - Future declareOutputs(DeclaringTransform transform) { - return call(_port, { - 'type': 'declareOutputs', - 'transform': serializeDeclaringTransform(transform) - }); - } -} - -class _ForeignLazyTransformer extends _ForeignDeclaringTransformer implements - LazyTransformer { - _ForeignLazyTransformer(Map map) - : super(map); -} - -/// A wrapper for an aggregate transformer that's in a different isolate. -class _ForeignAggregateTransformer extends AggregateTransformer { - /// The port with which we communicate with the child isolate. - /// - /// This port and all messages sent across it are specific to this - /// transformer. - final SendPort _port; - - /// The result of calling [toString] on the transformer in the isolate. - final String _toString; - - _ForeignAggregateTransformer(Map map) - : _port = map['port'], - _toString = map['toString']; - - Future classifyPrimary(AssetId id) { - return call(_port, { - 'type': 'classifyPrimary', - 'id': serializeId(id) - }); - } - - Future apply(AggregateTransform transform) { - return call(_port, { - 'type': 'apply', - 'transform': serializeAggregateTransform(transform) - }); - } - - String toString() => _toString; -} - -class _ForeignDeclaringAggregateTransformer extends _ForeignAggregateTransformer - implements DeclaringAggregateTransformer { - _ForeignDeclaringAggregateTransformer(Map map) - : super(map); - - Future declareOutputs(DeclaringAggregateTransform transform) { - return call(_port, { - 'type': 'declareOutputs', - 'transform': serializeDeclaringAggregateTransform(transform) - }); - } -} - -class _ForeignLazyAggregateTransformer extends - _ForeignDeclaringAggregateTransformer implements LazyAggregateTransformer { - _ForeignLazyAggregateTransformer(Map map) - : super(map); -} - -/// A wrapper for a transformer group that's in a different isolate. -class _ForeignGroup implements TransformerGroup { - final Iterable phases; - - /// The result of calling [toString] on the transformer group in the isolate. - final String _toString; - - _ForeignGroup(TransformerConfig config, Map map) - : phases = map['phases'].map((phase) { - return phase.map( - (transformer) => deserializeTransformerLike(transformer, config)).toList(); - }).toList(), - _toString = map['toString']; - - String toString() => _toString; -} - -/// Converts a serializable map into a [Transformer], an [AggregateTransformer], -/// or a [TransformerGroup]. -deserializeTransformerLike(Map map, TransformerConfig config) { - var transformer; - switch (map['type']) { - case 'TransformerGroup': - return new _ForeignGroup(config, map); - case 'Transformer': - transformer = new _ForeignTransformer(map); - break; - case 'DeclaringTransformer': - transformer = new _ForeignDeclaringTransformer(map); - break; - case 'LazyTransformer': - transformer = new _ForeignLazyTransformer(map); - break; - case 'AggregateTransformer': - transformer = new _ForeignAggregateTransformer(map); - break; - case 'DeclaringAggregateTransformer': - transformer = new _ForeignDeclaringAggregateTransformer(map); - break; - case 'LazyAggregateTransformer': - transformer = new _ForeignLazyAggregateTransformer(map); - break; - default: - assert(false); - } - - if (transformer is Transformer) { - return ExcludingTransformer.wrap(transformer, config); - } else { - assert(transformer is AggregateTransformer); - return ExcludingAggregateTransformer.wrap(transformer, config); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/load_all_transformers.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/load_all_transformers.dart deleted file mode 100644 index fc593774d86..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/load_all_transformers.dart +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.load_all_transformers; - -import 'dart:async'; - -import 'package:barback/barback.dart'; - -import '../log.dart' as log; -import '../package_graph.dart'; -import '../utils.dart'; -import 'asset_environment.dart'; -import 'barback_server.dart'; -import 'dependency_computer.dart'; -import 'transformer_id.dart'; -import 'transformer_loader.dart'; - -/// Loads all transformers depended on by packages in [environment]. -/// -/// This uses [environment]'s primary server to serve the Dart files from which -/// transformers are loaded, then adds the transformers to -/// `environment.barback`. -/// -/// Any built-in transformers that are provided by the environment will -/// automatically be added to the end of the root package's cascade. -/// -/// If [entrypoints] is passed, only transformers necessary to run those -/// entrypoints will be loaded. -Future loadAllTransformers(AssetEnvironment environment, - BarbackServer transformerServer, {Iterable entrypoints}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var dependencyComputer = new DependencyComputer(environment.graph); - var necessaryTransformers; - join0() { - var transformersNeededByTransformers = - dependencyComputer.transformersNeededByTransformers(necessaryTransformers); - var buffer = new StringBuffer(); - buffer.writeln("Transformer dependencies:"); - transformersNeededByTransformers.forEach(((id, dependencies) { - if (dependencies.isEmpty) { - buffer.writeln("$id: -"); - } else { - buffer.writeln("$id: ${toSentence(dependencies)}"); - } - })); - log.fine(buffer); - var stagedTransformers = - _stageTransformers(transformersNeededByTransformers); - var packagesThatUseTransformers = - _packagesThatUseTransformers(environment.graph); - var loader = new TransformerLoader(environment, transformerServer); - join1(x0) { - var cache = x0; - var first = true; - var it0 = stagedTransformers.iterator; - break0() { - join2() { - new Future.value( - Future.wait(environment.graph.packages.values.map(((package) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value( - loader.transformersForPhases(package.pubspec.transformers)).then((x0) { - try { - var phases = x0; - var transformers = - environment.getBuiltInTransformers(package); - join0() { - join1() { - newFuture((() { - return environment.barback.updateTransformers( - package.name, - phases); - })); - completer0.complete(); - } - if (phases.isEmpty) { - completer0.complete(null); - } else { - join1(); - } - } - if (transformers != null) { - phases.add(transformers); - join0(); - } else { - join0(); - } - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x1) { - try { - x1; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (cache != null) { - cache.save(); - join2(); - } else { - join2(); - } - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var stage = it0.current; - join3(x2) { - var snapshotPath = x2; - first = false; - new Future.value( - loader.load(stage, snapshot: snapshotPath)).then((x3) { - trampoline0 = () { - trampoline0 = null; - try { - x3; - var packagesToUpdate = unionAll(stage.map(((id) { - return packagesThatUseTransformers[id]; - }))); - new Future.value( - Future.wait(packagesToUpdate.map(((packageName) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var package = - environment.graph.packages[packageName]; - new Future.value( - loader.transformersForPhases(package.pubspec.transformers)).then((x0) { - try { - var phases = x0; - environment.barback.updateTransformers( - packageName, - phases); - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x4) { - trampoline0 = () { - trampoline0 = null; - try { - x4; - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: completer0.completeError); - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: completer0.completeError); - } - if (cache == null || !first) { - join3(null); - } else { - join3(cache.snapshotPath(stage)); - } - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - if (environment.rootPackage.dir == null) { - join1(null); - } else { - join1(environment.graph.loadTransformerCache()); - } - } - if (entrypoints != null) { - join4() { - necessaryTransformers = - unionAll(entrypoints.map(dependencyComputer.transformersNeededByLibrary)); - join5() { - join0(); - } - if (necessaryTransformers.isEmpty) { - log.fine( - "No transformers are needed for ${toSentence(entrypoints)}."); - completer0.complete(null); - } else { - join5(); - } - } - if (entrypoints.isEmpty) { - completer0.complete(null); - } else { - join4(); - } - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; -} - -/// Given [transformerDependencies], a directed acyclic graph, returns a list of -/// "stages" (sets of transformers). -/// -/// Each stage must be fully loaded and passed to barback before the next stage -/// can be safely loaded. However, transformers within a stage can be safely -/// loaded in parallel. -List> _stageTransformers(Map> transformerDependencies) { - // A map from transformer ids to the indices of the stages that those - // transformer ids should end up in. Populated by [stageNumberFor]. - var stageNumbers = {}; - var stages = []; - - stageNumberFor(id) { - // Built-in transformers don't have to be loaded in stages, since they're - // run from pub's source. Return -1 so that the "next stage" is 0. - if (id.isBuiltInTransformer) return -1; - - if (stageNumbers.containsKey(id)) return stageNumbers[id]; - var dependencies = transformerDependencies[id]; - stageNumbers[id] = - dependencies.isEmpty ? 0 : maxAll(dependencies.map(stageNumberFor)) + 1; - return stageNumbers[id]; - } - - for (var id in transformerDependencies.keys) { - var stageNumber = stageNumberFor(id); - if (stages.length <= stageNumber) stages.length = stageNumber + 1; - if (stages[stageNumber] == null) stages[stageNumber] = new Set(); - stages[stageNumber].add(id); - } - - return stages; -} - -/// Returns a map from transformer ids to all packages in [graph] that use each -/// transformer. -Map> _packagesThatUseTransformers(PackageGraph graph) - { - var results = {}; - for (var package in graph.packages.values) { - for (var phase in package.pubspec.transformers) { - for (var config in phase) { - results.putIfAbsent(config.id, () => new Set()).add(package.name); - } - } - } - return results; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/pub_package_provider.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/pub_package_provider.dart deleted file mode 100644 index d82da67d87d..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/pub_package_provider.dart +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.pub_package_provider; - -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as path; - -import '../io.dart'; -import '../package_graph.dart'; -import '../preprocess.dart'; -import '../sdk.dart' as sdk; -import '../utils.dart'; - -/// An implementation of barback's [PackageProvider] interface so that barback -/// can find assets within pub packages. -class PubPackageProvider implements StaticPackageProvider { - final PackageGraph _graph; - final List staticPackages; - - Iterable get packages => - _graph.packages.keys.toSet().difference(staticPackages.toSet()); - - PubPackageProvider(PackageGraph graph) - : _graph = graph, - staticPackages = [ - r"$pub", - r"$sdk"]..addAll(graph.packages.keys.where(graph.isPackageStatic)); - - Future getAsset(AssetId id) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - join1() { - var nativePath = path.fromUri(id.path); - var file = _graph.packages[id.package].path(nativePath); - _assertExists(file, id); - completer0.complete(new Asset.fromPath(id, file)); - } - if (id.package == r'$sdk') { - var parts = path.split(path.fromUri(id.path)); - assert(parts.isNotEmpty && parts[0] == 'lib'); - parts = parts.skip(1); - var file = path.join(sdk.rootDirectory, path.joinAll(parts)); - _assertExists(file, id); - completer0.complete(new Asset.fromPath(id, file)); - } else { - join1(); - } - } - if (id.package == r'$pub') { - var components = path.url.split(id.path); - assert(components.isNotEmpty); - assert(components.first == 'lib'); - components[0] = 'dart'; - var file = assetPath(path.joinAll(components)); - _assertExists(file, id); - join2() { - var versions = mapMap(_graph.packages, value: ((_, package) { - return package.version; - })); - var contents = readTextFile(file); - contents = preprocess(contents, versions, path.toUri(file)); - completer0.complete(new Asset.fromString(id, contents)); - } - if (!_graph.packages.containsKey("barback")) { - completer0.complete(new Asset.fromPath(id, file)); - } else { - join2(); - } - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Throw an [AssetNotFoundException] for [id] if [path] doesn't exist. - void _assertExists(String path, AssetId id) { - if (!fileExists(path)) throw new AssetNotFoundException(id); - } - - Stream getAllAssetIds(String packageName) { - if (packageName == r'$pub') { - // "$pub" is a pseudo-package that allows pub's transformer-loading - // infrastructure to share code with pub proper. We provide it only during - // the initial transformer loading process. - var dartPath = assetPath('dart'); - return new Stream.fromIterable( - listDir(dartPath, recursive: true)// Don't include directories. - .where((file) => path.extension(file) == ".dart").map((library) { - var idPath = path.join('lib', path.relative(library, from: dartPath)); - return new AssetId('\$pub', path.toUri(idPath).toString()); - })); - } else if (packageName == r'$sdk') { - // "$sdk" is a pseudo-package that allows the dart2js transformer to find - // the Dart core libraries without hitting the file system directly. This - // ensures they work with source maps. - var libPath = path.join(sdk.rootDirectory, "lib"); - return new Stream.fromIterable( - listDir( - libPath, - recursive: true).where((file) => path.extension(file) == ".dart").map((file) { - var idPath = - path.join("lib", path.relative(file, from: sdk.rootDirectory)); - return new AssetId('\$sdk', path.toUri(idPath).toString()); - })); - } else { - var package = _graph.packages[packageName]; - return new Stream.fromIterable( - package.listFiles(beneath: 'lib').map((file) { - return new AssetId( - packageName, - path.toUri(package.relative(file)).toString()); - })); - } - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/source_directory.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/source_directory.dart deleted file mode 100644 index 9996ab9d1fa..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/source_directory.dart +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.source_directory; - -import 'dart:async'; - -import 'package:watcher/watcher.dart'; - -import 'asset_environment.dart'; -import 'barback_server.dart'; - -/// A directory in the entrypoint package whose contents have been made -/// available to barback and that are bound to a server. -class SourceDirectory { - final AssetEnvironment _environment; - - /// The relative directory path within the package. - final String directory; - - /// The hostname to serve this directory on. - final String hostname; - - /// The port to serve this directory on. - final int port; - - /// The server bound to this directory. - /// - /// This is a future that will complete once [serve] has been called and the - /// server has been successfully spun up. - Future get server => _serverCompleter.future; - final _serverCompleter = new Completer(); - - /// The subscription to the [DirectoryWatcher] used to watch this directory - /// for changes. - /// - /// If the directory is not being watched, this will be `null`. - StreamSubscription watchSubscription; - - SourceDirectory(this._environment, this.directory, this.hostname, this.port); - - /// Binds a server running on [hostname]:[port] to this directory. - Future serve() { - return BarbackServer.bind( - _environment, - hostname, - port, - rootDirectory: directory).then((server) { - _serverCompleter.complete(server); - return server; - }); - } - - /// Removes the source directory from the build environment. - /// - /// Closes the server, removes the assets from barback, and stops watching it. - Future close() { - return server.then((server) { - var futures = [server.close()]; - - // Stop watching the directory. - if (watchSubscription != null) { - var cancel = watchSubscription.cancel(); - if (cancel != null) futures.add(cancel); - } - - return Future.wait(futures); - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_cache.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_cache.dart deleted file mode 100644 index 7e8a61d90c7..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_cache.dart +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.transformer_cache; - -import 'package:path/path.dart' as p; - -import '../io.dart'; -import '../log.dart' as log; -import '../package_graph.dart'; -import '../sdk.dart' as sdk; -import '../utils.dart'; -import 'transformer_id.dart'; - -/// A cache for managing a snapshot of the first "stage" of transformers to -/// load. -/// -/// This uses the [_stageTransformers] notion of a stage. Transformers are -/// divided into stages for loading based on which transformers are needed to -/// load one another. For example, if a transformer T1 produces a file that's -/// imported by another transformer T2, T2 must be put in a stage after T1. -/// -/// We only cache the first stage because it's the only stage whose contents are -/// independent of any configuration. Since most transformers don't import the -/// output of other transformers, many packages will only have one stage. -class TransformerCache { - final PackageGraph _graph; - - /// The set of transformer ids that were previously cached. - /// - /// If there was no previous cache, this will be empty. - Set _oldTransformers; - - /// The set of transformer ids that are newly cached or re-used from the - /// previous cache. - Set _newTransformers; - - /// The directory in which transformers are cached. - /// - /// This may be `null` if there's no physical entrypoint directory. - String _dir; - - /// The directory of the manifest listing which transformers were cached. - String get _manifestPath => p.join(_dir, "manifest.txt"); - - /// Loads the transformer cache for [environment]. - /// - /// This may modify the cache. - TransformerCache.load(PackageGraph graph) - : _graph = graph, - _dir = graph.entrypoint.root.path(".pub/transformers") { - _oldTransformers = _parseManifest(); - } - - /// Clear the cache if it depends on any package in [changedPackages]. - void clearIfOutdated(Set changedPackages) { - var snapshotDependencies = unionAll(_oldTransformers.map((id) { - // If the transformer cache contains transformers we don't know about, - // that's fine; we just won't load them. - if (!_graph.packages.containsKey(id.package)) return new Set(); - - return _graph.transitiveDependencies( - id.package).map((package) => package.name).toSet(); - })); - - // If none of the snapshot's dependencies have changed, then we can reuse - // it. - if (!overlaps(changedPackages, snapshotDependencies)) return; - - // Otherwise, delete it. - deleteEntry(_dir); - _oldTransformers = new Set(); - } - - /// Returns the path for the transformer snapshot for [transformers], or - /// `null` if the transformers shouldn't be cached. - /// - /// There may or may not exist a file at the returned path. If one does exist, - /// it can safely be used to load the stage. Otherwise, a snapshot of the - /// stage should be written there. - String snapshotPath(Set transformers) { - var path = p.join(_dir, "transformers.snapshot"); - if (_newTransformers != null) return path; - - if (transformers.any((id) => _graph.isPackageMutable(id.package))) { - log.fine("Not caching mutable transformers."); - deleteEntry(_dir); - return null; - } - - if (!_oldTransformers.containsAll(transformers)) { - log.fine("Cached transformer snapshot is out-of-date, deleting."); - deleteEntry(path); - } else { - log.fine("Using cached transformer snapshot."); - } - - _newTransformers = transformers; - return path; - } - - /// Saves the manifest to the transformer cache. - void save() { - // If we didn't write any snapshots, there's no need to write a manifest. - if (_newTransformers == null) { - if (_dir != null) deleteEntry(_dir); - return; - } - - // We only need to rewrite the manifest if we created a new snapshot. - if (_oldTransformers.containsAll(_newTransformers)) return; - - ensureDir(_dir); - writeTextFile( - _manifestPath, - "${sdk.version}\n" + - ordered(_newTransformers.map((id) => id.serialize())).join(",")); - } - - /// Parses the cache manifest and returns the set of previously-cached - /// transformers. - /// - /// If the manifest indicates that the SDK version is out-of-date, this - /// deletes the existing cache. Otherwise, - Set _parseManifest() { - if (!fileExists(_manifestPath)) return new Set(); - - var manifest = readTextFile(_manifestPath).split("\n"); - - // The first line of the manifest is the SDK version. We want to clear out - // the snapshots even if they're VM-compatible, since pub's transformer - // isolate scaffolding may have changed. - if (manifest.removeAt(0) != sdk.version.toString()) { - deleteEntry(_dir); - return new Set(); - } - - /// The second line of the manifest is a list of transformer ids used to - /// create the existing snapshot. - return manifest.single.split( - ",").map((id) => new TransformerId.parse(id, null)).toSet(); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_config.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_config.dart deleted file mode 100644 index 11d959457fd..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_config.dart +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.transformer_config; - -import 'package:glob/glob.dart'; -import 'package:path/path.dart' as p; -import 'package:source_span/source_span.dart'; -import 'package:yaml/yaml.dart'; - -import 'transformer_id.dart'; - -/// The configuration for a transformer. -/// -/// This corresponds to the transformers listed in a pubspec, which have both an -/// [id] indicating the location of the transformer and configuration specific -/// to that use of the transformer. -class TransformerConfig { - /// The [id] of the transformer [this] is configuring. - final TransformerId id; - - /// The configuration to pass to the transformer. - /// - /// Any pub-specific configuration (i.e. keys starting with "$") will have - /// been stripped out of this and handled separately. This will be an empty - /// map if no configuration was provided. - final Map configuration; - - /// The source span from which this configuration was parsed. - final SourceSpan span; - - /// The primary input inclusions. - /// - /// Each inclusion is an asset path. If this set is non-empty, then *only* - /// matching assets are allowed as a primary input by this transformer. If - /// `null`, all assets are included. - /// - /// This is processed before [excludes]. If a transformer has both includes - /// and excludes, then the set of included assets is determined and assets - /// are excluded from that resulting set. - final Set includes; - - /// The primary input exclusions. - /// - /// Any asset whose pach is in this is not allowed as a primary input by - /// this transformer. - /// - /// This is processed after [includes]. If a transformer has both includes - /// and excludes, then the set of included assets is determined and assets - /// are excluded from that resulting set. - final Set excludes; - - /// Returns whether this config excludes certain asset ids from being - /// processed. - bool get hasExclusions => includes != null || excludes != null; - - /// Returns whether this transformer might transform a file that's visible to - /// the package's dependers. - bool get canTransformPublicFiles { - if (includes == null) return true; - return includes.any((glob) { - // Check whether the first path component of the glob is "lib", "bin", or - // contains wildcards that may cause it to match "lib" or "bin". - var first = p.posix.split(glob.toString()).first; - if (first.contains('{') || - first.contains('*') || - first.contains('[') || - first.contains('?')) { - return true; - } - - return first == 'lib' || first == 'bin'; - }); - } - - /// Parses [identifier] as a [TransformerId] with [configuration]. - /// - /// [identifierSpan] is the source span for [identifier]. - factory TransformerConfig.parse(String identifier, SourceSpan identifierSpan, - YamlMap configuration) => - new TransformerConfig( - new TransformerId.parse(identifier, identifierSpan), - configuration); - - factory TransformerConfig(TransformerId id, YamlMap configurationNode) { - parseField(key) { - if (!configurationNode.containsKey(key)) return null; - var fieldNode = configurationNode.nodes[key]; - var field = fieldNode.value; - - if (field is String) { - return new Set.from([new Glob(field, context: p.url, recursive: true)]); - } - - if (field is! List) { - throw new SourceSpanFormatException( - '"$key" field must be a string or list.', - fieldNode.span); - } - - return new Set.from(field.nodes.map((node) { - if (node.value is String) { - return new Glob(node.value, context: p.url, recursive: true); - } - - throw new SourceSpanFormatException( - '"$key" field may contain only strings.', - node.span); - })); - } - - var includes = null; - var excludes = null; - - var configuration; - var span; - if (configurationNode == null) { - configuration = {}; - span = id.span; - } else { - // Don't write to the immutable YAML map. - configuration = new Map.from(configurationNode); - span = configurationNode.span; - - // Pull out the exclusions/inclusions. - includes = parseField("\$include"); - configuration.remove("\$include"); - excludes = parseField("\$exclude"); - configuration.remove("\$exclude"); - - // All other keys starting with "$" are unexpected. - for (var key in configuration.keys) { - if (key is! String || !key.startsWith(r'$')) continue; - throw new SourceSpanFormatException( - 'Unknown reserved field.', - configurationNode.nodes[key].span); - } - } - - return new TransformerConfig._(id, configuration, span, includes, excludes); - } - - TransformerConfig._(this.id, this.configuration, this.span, this.includes, - this.excludes); - - String toString() => id.toString(); - - /// Returns whether the include/exclude rules allow the transformer to run on - /// [pathWithinPackage]. - /// - /// [pathWithinPackage] must be a URL-style path relative to the containing - /// package's root directory. - bool canTransform(String pathWithinPackage) { - if (excludes != null) { - // If there are any excludes, it must not match any of them. - for (var exclude in excludes) { - if (exclude.matches(pathWithinPackage)) return false; - } - } - - // If there are any includes, it must match one of them. - return includes == null || - includes.any((include) => include.matches(pathWithinPackage)); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_id.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_id.dart deleted file mode 100644 index 2017d9bb0a8..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_id.dart +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.transformer_id; - -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:source_span/source_span.dart'; - -import '../utils.dart'; - -/// A list of the names of all built-in transformers that pub exposes. -const _BUILT_IN_TRANSFORMERS = const ['\$dart2js']; - -/// An identifier that indicates the library that contains a transformer. -/// -/// It's possible that the library identified by [this] defines multiple -/// transformers. If so, they're all always loaded in the same phase. -class TransformerId { - /// The package containing the library where the transformer is defined. - final String package; - - /// The `/`-separated path to the library that contains this transformer. - /// - /// This is relative to the `lib/` directory in [package], and doesn't end in - /// `.dart`. - /// - /// This can be null; if so, it indicates that the transformer(s) should be - /// loaded from `lib/transformer.dart` if that exists, and `lib/$package.dart` - /// otherwise. - final String path; - - /// The source span from which this id was parsed. - final SourceSpan span; - - /// Whether this ID points to a built-in transformer exposed by pub. - bool get isBuiltInTransformer => package.startsWith('\$'); - - /// Parses a transformer identifier. - /// - /// A transformer identifier is a string of the form "package_name" or - /// "package_name/path/to/library". It does not have a trailing extension. If - /// it just has a package name, it expands to lib/transformer.dart if that - /// exists, or lib/${package}.dart otherwise. Otherwise, it expands to - /// lib/${path}.dart. In either case it's located in the given package. - factory TransformerId.parse(String identifier, SourceSpan span) { - if (identifier.isEmpty) { - throw new FormatException('Invalid library identifier: "".'); - } - - var parts = split1(identifier, "/"); - if (parts.length == 1) { - return new TransformerId(parts.single, null, span); - } - - return new TransformerId(parts.first, parts.last, span); - } - - TransformerId(this.package, this.path, this.span) { - if (!package.startsWith('\$')) return; - if (_BUILT_IN_TRANSFORMERS.contains(package)) return; - throw new SourceSpanFormatException( - 'Unsupported built-in transformer $package.', - span); - } - - bool operator ==(other) => - other is TransformerId && other.package == package && other.path == path; - - int get hashCode => package.hashCode ^ path.hashCode; - - /// Returns a serialized form of [this] that can be passed to - /// [new TransformerId.parse]. - String serialize() => path == null ? package : '$package/$path'; - - String toString() => serialize(); - - /// Returns the asset id for the library identified by this transformer id. - /// - /// If `path` is null, this will determine which library to load. Unlike - /// [getAssetId], this doesn't take generated assets into account; it's used - /// to determine transformers' dependencies, which requires looking at files - /// on disk. - Future getAssetId(Barback barback) { - if (path != null) { - return new Future.value(new AssetId(package, 'lib/$path.dart')); - } - - var transformerAsset = new AssetId(package, 'lib/transformer.dart'); - return barback.getAssetById( - transformerAsset).then( - (_) => - transformerAsset).catchError( - (e) => new AssetId(package, 'lib/$package.dart'), - test: (e) => e is AssetNotFoundException); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_isolate.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_isolate.dart deleted file mode 100644 index 04298d2be1f..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_isolate.dart +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.transformer_isolate; - -import 'dart:async'; -import 'dart:convert'; -import 'dart:isolate'; - -import 'package:barback/barback.dart'; -import 'package:source_span/source_span.dart'; -import 'package:stack_trace/stack_trace.dart'; - -import '../../../asset/dart/serialize.dart'; -import '../barback.dart'; -import '../exceptions.dart'; -import '../dart.dart' as dart; -import '../log.dart' as log; -import '../utils.dart'; -import 'asset_environment.dart'; -import 'barback_server.dart'; -import 'foreign_transformer.dart'; -import 'transformer_config.dart'; -import 'transformer_id.dart'; - -/// A wrapper for an isolate from which transformer plugins can be instantiated. -class TransformerIsolate { - /// The port used to communicate with the wrapped isolate. - final SendPort _port; - - /// A map indicating the barback server URLs for each [TransformerId] that's - /// loaded in the wrapped isolate. - /// - /// A barback server URL is the URL for the library that the given id - /// identifies. For example, the URL for "polymer/src/mirrors_remover" might - /// be "http://localhost:56234/packages/polymer/src/mirrors_remover.dart". - final Map _idsToUrls; - - /// The barback mode for this run of pub. - final BarbackMode _mode; - - /// Spawns an isolate that loads all transformer libraries defined by [ids]. - /// - /// This doesn't actually instantiate any transformers, since a - /// [TransformerId] doesn't define the transformers' configuration. The - /// transformers can be constructed using [create]. - /// - /// If [snapshot] is passed, the isolate will be loaded from that path if it - /// exists. Otherwise, a snapshot of the isolate's code will be saved to that - /// path once the isolate is loaded. - static Future spawn(AssetEnvironment environment, - BarbackServer transformerServer, List ids, {String snapshot}) { - return mapFromIterableAsync(ids, value: (id) { - return id.getAssetId(environment.barback); - }).then((idsToAssetIds) { - var baseUrl = transformerServer.url; - var idsToUrls = mapMap(idsToAssetIds, value: (id, assetId) { - var path = assetId.path.replaceFirst('lib/', ''); - return Uri.parse('package:${id.package}/$path'); - }); - - var code = new StringBuffer(); - code.writeln("import 'dart:isolate';"); - - for (var url in idsToUrls.values) { - code.writeln("import '$url';"); - } - - code.writeln("import r'package:\$pub/transformer_isolate.dart';"); - code.writeln( - "void main(_, SendPort replyTo) => loadTransformers(replyTo);"); - - log.fine("Loading transformers from $ids"); - - var port = new ReceivePort(); - return dart.runInIsolate( - code.toString(), - port.sendPort, - packageRoot: baseUrl.resolve('packages'), - snapshot: snapshot).then((_) => port.first).then((sendPort) { - return new TransformerIsolate._(sendPort, environment.mode, idsToUrls); - }).catchError((error, stackTrace) { - if (error is! CrossIsolateException) throw error; - if (error.type != 'IsolateSpawnException') throw error; - - // TODO(nweiz): don't parse this as a string once issues 12617 and 12689 - // are fixed. - var firstErrorLine = error.message.split('\n')[1]; - - // The isolate error message contains the fully expanded path, not the - // "package:" URI, so we have to be liberal in what we look for in the - // error message. - var missingTransformer = idsToUrls.keys.firstWhere( - (id) => - firstErrorLine.startsWith("Uncaught Error: Load Error: Failure getting ") && - firstErrorLine.contains(idsToUrls[id].path), - orElse: () => throw error); - var packageUri = idToPackageUri(idsToAssetIds[missingTransformer]); - - // If there was an IsolateSpawnException and the import that actually - // failed was the one we were loading transformers from, throw an - // application exception with a more user-friendly message. - fail('Transformer library "$packageUri" not found.', error, stackTrace); - }); - }); - } - - TransformerIsolate._(this._port, this._mode, this._idsToUrls); - - /// Instantiate the transformers in the [config.id] with - /// [config.configuration]. - /// - /// If there are no transformers defined in the given library, this will - /// return an empty set. - Future> create(TransformerConfig config) { - return call(_port, { - 'library': _idsToUrls[config.id].toString(), - 'mode': _mode.name, - 'configuration': JSON.encode(config.configuration) - }).then((transformers) { - transformers = transformers.map( - (transformer) => deserializeTransformerLike(transformer, config)).toSet(); - log.fine("Transformers from $config: $transformers"); - return transformers; - }).catchError((error, stackTrace) { - throw new TransformerLoadError(error, config.span); - }); - } -} - -/// An error thrown when a transformer fails to load. -class TransformerLoadError extends SourceSpanException implements - WrappedException { - final CrossIsolateException innerError; - Chain get innerChain => innerError.stackTrace; - - TransformerLoadError(CrossIsolateException error, SourceSpan span) - : innerError = error, - super("Error loading transformer: ${error.message}", span); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_loader.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_loader.dart deleted file mode 100644 index 2333e3c65ac..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/transformer_loader.dart +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.transformer_loader; - -import 'dart:async'; - -import 'package:barback/barback.dart'; - -import '../log.dart' as log; -import '../utils.dart'; -import 'asset_environment.dart'; -import 'barback_server.dart'; -import 'dart2js_transformer.dart'; -import 'excluding_transformer.dart'; -import 'transformer_config.dart'; -import 'transformer_id.dart'; -import 'transformer_isolate.dart'; - -/// A class that loads transformers defined in specific files. -class TransformerLoader { - final AssetEnvironment _environment; - - final BarbackServer _transformerServer; - - final _isolates = new Map(); - - final _transformers = new Map>(); - - /// The packages that use each transformer id. - /// - /// Used for error reporting. - final _transformerUsers = new Map>(); - - TransformerLoader(this._environment, this._transformerServer) { - for (var package in _environment.graph.packages.values) { - for (var config in unionAll(package.pubspec.transformers)) { - _transformerUsers.putIfAbsent( - config.id, - () => new Set()).add(package.name); - } - } - } - - /// Loads a transformer plugin isolate that imports the transformer libraries - /// indicated by [ids]. - /// - /// Once the returned future completes, transformer instances from this - /// isolate can be created using [transformersFor] or [transformersForPhase]. - /// - /// This skips any ids that have already been loaded. - Future load(Iterable ids, {String snapshot}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - ids = ids.where(((id) { - return !_isolates.containsKey(id); - })).toList(); - join0() { - new Future.value( - log.progress("Loading ${toSentence(ids)} transformers", (() { - return TransformerIsolate.spawn( - _environment, - _transformerServer, - ids, - snapshot: snapshot); - }))).then((x0) { - try { - var isolate = x0; - var it0 = ids.iterator; - break0() { - completer0.complete(); - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var id = it0.current; - _isolates[id] = isolate; - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (ids.isEmpty) { - completer0.complete(null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Instantiates and returns all transformers in the library indicated by - /// [config] with the given configuration. - /// - /// If this is called before the library has been loaded into an isolate via - /// [load], it will return an empty set. - Future> transformersFor(TransformerConfig config) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - join1() { - var transformer; - join2() { - _transformers[config] = - new Set.from([ExcludingTransformer.wrap(transformer, config)]); - completer0.complete(_transformers[config]); - } - catch0(error, stackTrace) { - try { - if (error is FormatException) { - fail(error.message, error, stackTrace); - join2(); - } else { - throw error; - } - } catch (error, stackTrace) { - completer0.completeError(error, stackTrace); - } - } - try { - transformer = new Dart2JSTransformer.withSettings( - _environment, - new BarbackSettings(config.configuration, _environment.mode)); - join2(); - } catch (e0, s0) { - catch0(e0, s0); - } - } - if (_isolates.containsKey(config.id)) { - new Future.value(_isolates[config.id].create(config)).then((x0) { - try { - var transformers = x0; - join3() { - var message = "No transformers"; - join4() { - var location; - join5() { - var users = - toSentence(ordered(_transformerUsers[config.id])); - fail( - "${message} were defined in ${location},\n" "required by ${users}."); - join1(); - } - if (config.id.path == null) { - location = - 'package:${config.id.package}/transformer.dart or ' - 'package:${config.id.package}/${config.id.package}.dart'; - join5(); - } else { - location = 'package:${config}.dart'; - join5(); - } - } - if (config.configuration.isNotEmpty) { - message += " that accept configuration"; - join4(); - } else { - join4(); - } - } - if (transformers.isNotEmpty) { - _transformers[config] = transformers; - completer0.complete(transformers); - } else { - join3(); - } - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } else { - join6() { - join1(); - } - if (config.id.package != '\$dart2js') { - completer0.complete(new Future.value(new Set())); - } else { - join6(); - } - } - } - if (_transformers.containsKey(config)) { - completer0.complete(_transformers[config]); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Loads all transformers defined in each phase of [phases]. - /// - /// If any library hasn't yet been loaded via [load], it will be ignored. - Future>> - transformersForPhases(Iterable> phases) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value(Future.wait(phases.map(((phase) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value( - waitAndPrintErrors(phase.map(transformersFor))).then((x0) { - try { - var transformers = x0; - completer0.complete(unionAll(transformers)); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x0) { - try { - var result = x0; - completer0.complete(result.toList()); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/barback/web_socket_api.dart b/sdk/lib/_internal/pub_generated/lib/src/barback/web_socket_api.dart deleted file mode 100644 index 3d5d4e1cc9f..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/barback/web_socket_api.dart +++ /dev/null @@ -1,321 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.barback.web_socket_api; - -import 'dart:async'; -import 'dart:io'; - -import 'package:http_parser/http_parser.dart'; -import 'package:path/path.dart' as path; -import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc; - -import '../exit_codes.dart' as exit_codes; -import '../io.dart'; -import '../log.dart' as log; -import '../utils.dart'; -import 'asset_environment.dart'; - -/// Implements the [WebSocket] API for communicating with a running pub serve -/// process, mainly for use by the Editor. -/// -/// This is a [JSON-RPC 2.0](http://www.jsonrpc.org/specification) server. Its -/// methods are described in the method-level documentation below. -class WebSocketApi { - final AssetEnvironment _environment; - final json_rpc.Server _server; - - /// Whether the application should exit when this connection closes. - bool _exitOnClose = false; - - WebSocketApi(CompatibleWebSocket socket, this._environment) - : _server = new json_rpc.Server(socket) { - _server.registerMethod("urlToAssetId", _urlToAssetId); - _server.registerMethod("pathToUrls", _pathToUrls); - _server.registerMethod("serveDirectory", _serveDirectory); - _server.registerMethod("unserveDirectory", _unserveDirectory); - - /// Tells the server to exit as soon as this WebSocket connection is closed. - /// - /// This takes no arguments and returns no results. It can safely be called - /// as a JSON-RPC notification. - _server.registerMethod("exitOnClose", () { - _exitOnClose = true; - }); - } - - /// Listens on the socket. - /// - /// Returns a future that completes when the socket has closed. It will - /// complete with an error if the socket had an error, otherwise it will - /// complete to `null`. - Future listen() { - return _server.listen().then((_) { - if (!_exitOnClose) return; - log.message("WebSocket connection closed, terminating."); - flushThenExit(exit_codes.SUCCESS); - }); - } - - /// Given a URL to an asset that is served by pub, returns the ID of the - /// asset that would be accessed by that URL. - /// - /// The method name is "urlToAssetId" and it takes a "url" parameter for the - /// URL being mapped: - /// - /// "params": { - /// "url": "http://localhost:8080/index.html" - /// } - /// - /// If successful, it returns a map containing the asset ID's package and - /// path: - /// - /// "result": { - /// "package": "myapp", - /// "path": "web/index.html" - /// } - /// - /// The "path" key in the result is a URL path that's relative to the root - /// directory of the package identified by "package". The location of this - /// package may vary depending on which source it was installed from. - /// - /// An optional "line" key may be provided whose value must be an integer. If - /// given, the result will also include a "line" key that maps the line in - /// the served final file back to the corresponding source line in the asset - /// that was used to generate that file. - /// - /// Examples (where "myapp" is the root package and pub serve is being run - /// normally with "web" bound to port 8080 and "test" to 8081): - /// - /// http://localhost:8080/index.html -> myapp|web/index.html - /// http://localhost:8081/sub/main.dart -> myapp|test/sub/main.dart - /// - /// If the URL is not a domain being served by pub, this returns an error: - /// - /// http://localhost:1234/index.html -> NOT_SERVED error - /// - /// This does *not* currently support the implicit index.html behavior that - /// pub serve provides for user-friendliness: - /// - /// http://localhost:1234 -> NOT_SERVED error - /// - /// This does *not* currently check to ensure the asset actually exists. It - /// only maps what the corresponding asset *should* be for that URL. - Future _urlToAssetId(json_rpc.Parameters params) { - var url = params["url"].asUri; - - // If a line number was given, map it to the output line. - var line = params["line"].asIntOr(null); - - return _environment.getAssetIdForUrl(url).then((id) { - if (id == null) { - throw new json_rpc.RpcException( - _Error.NOT_SERVED, - '"${url.host}:${url.port}" is not being served by pub.'); - } - - // TODO(rnystrom): When this is hooked up to actually talk to barback to - // see if assets exist, consider supporting implicit index.html at that - // point. - - var result = { - "package": id.package, - "path": id.path - }; - - // Map the line. - // TODO(rnystrom): Right now, source maps are not supported and it just - // passes through the original line. This lets the editor start using - // this API before we've fully implemented it. See #12339 and #16061. - if (line != null) result["line"] = line; - - return result; - }); - } - - /// Given a path on the filesystem, returns the URLs served by pub that can be - /// used to access asset found at that path. - /// - /// The method name is "pathToUrls" and it takes a "path" key (a native OS - /// path which may be absolute or relative to the root directory of the - /// entrypoint package) for the path being mapped: - /// - /// "params": { - /// "path": "web/index.html" - /// } - /// - /// If successful, it returns a map containing the list of URLs that can be - /// used to access that asset. - /// - /// "result": { - /// "urls": ["http://localhost:8080/index.html"] - /// } - /// - /// The "path" key may refer to a path in another package, either by referring - /// to its location within the top-level "packages" directory or by referring - /// to its location on disk. Only the "lib" directory is visible in other - /// packages: - /// - /// "params": { - /// "path": "packages/http/http.dart" - /// } - /// - /// Assets in the "lib" directory will usually have one URL for each server: - /// - /// "result": { - /// "urls": [ - /// "http://localhost:8080/packages/http/http.dart", - /// "http://localhost:8081/packages/http/http.dart" - /// ] - /// } - /// - /// An optional "line" key may be provided whose value must be an integer. If - /// given, the result will also include a "line" key that maps the line in - /// the source file to the corresponding output line in the resulting asset - /// served at the URL. - /// - /// Examples (where "myapp" is the root package and pub serve is being run - /// normally with "web" bound to port 8080 and "test" to 8081): - /// - /// web/index.html -> http://localhost:8080/index.html - /// test/sub/main.dart -> http://localhost:8081/sub/main.dart - /// - /// If the asset is not in a directory being served by pub, returns an error: - /// - /// example/index.html -> NOT_SERVED error - Future _pathToUrls(json_rpc.Parameters params) { - var assetPath = params["path"].asString; - var line = params["line"].asIntOr(null); - - return _environment.getUrlsForAssetPath(assetPath).then((urls) { - if (urls.isEmpty) { - throw new json_rpc.RpcException( - _Error.NOT_SERVED, - 'Asset path "$assetPath" is not currently being served.'); - } - - var result = { - "urls": urls.map((url) => url.toString()).toList() - }; - - // Map the line. - // TODO(rnystrom): Right now, source maps are not supported and it just - // passes through the original line. This lets the editor start using - // this API before we've fully implemented it. See #12339 and #16061. - if (line != null) result["line"] = line; - - return result; - }); - } - - /// Given a relative directory path within the entrypoint package, binds a - /// new port to serve from that path and returns its URL. - /// - /// The method name is "serveDirectory" and it takes a "path" key (a native - /// OS path relative to the root of the entrypoint package) for the directory - /// being served: - /// - /// "params": { - /// "path": "example/awesome" - /// } - /// - /// If successful, it returns a map containing the URL that can be used to - /// access the directory. - /// - /// "result": { - /// "url": "http://localhost:8083" - /// } - /// - /// If the directory is already being served, returns the previous URL. - Future _serveDirectory(json_rpc.Parameters params) { - var rootDirectory = _validateRelativePath(params, "path"); - return _environment.serveDirectory(rootDirectory).then((server) { - return { - "url": server.url.toString() - }; - }).catchError((error) { - if (error is! OverlappingSourceDirectoryException) throw error; - - var dir = pluralize( - "directory", - error.overlappingDirectories.length, - plural: "directories"); - var overlapping = - toSentence(error.overlappingDirectories.map((dir) => '"$dir"')); - print("data: ${error.overlappingDirectories}"); - throw new json_rpc.RpcException( - _Error.OVERLAPPING, - 'Path "$rootDirectory" overlaps already served $dir $overlapping.', - data: { - "directories": error.overlappingDirectories - }); - }); - } - - /// Given a relative directory path within the entrypoint package, unbinds - /// the server previously bound to that directory and returns its (now - /// unreachable) URL. - /// - /// The method name is "unserveDirectory" and it takes a "path" key (a - /// native OS path relative to the root of the entrypoint package) for the - /// directory being unserved: - /// - /// "params": { - /// "path": "example/awesome" - /// } - /// - /// If successful, it returns a map containing the URL that used to be used - /// to access the directory. - /// - /// "result": { - /// "url": "http://localhost:8083" - /// } - /// - /// If no server is bound to that directory, it returns a `NOT_SERVED` error. - Future _unserveDirectory(json_rpc.Parameters params) { - var rootDirectory = _validateRelativePath(params, "path"); - return _environment.unserveDirectory(rootDirectory).then((url) { - if (url == null) { - throw new json_rpc.RpcException( - _Error.NOT_SERVED, - 'Directory "$rootDirectory" is not bound to a server.'); - } - - return { - "url": url.toString() - }; - }); - } - - /// Validates that [command] has a field named [key] whose value is a string - /// containing a relative path that doesn't reach out of the entrypoint - /// package's root directory. - /// - /// Returns the path if found, or throws a [_WebSocketException] if - /// validation failed. - String _validateRelativePath(json_rpc.Parameters params, String key) { - var pathString = params[key].asString; - - if (!path.isRelative(pathString)) { - throw new json_rpc.RpcException.invalidParams( - '"$key" must be a relative path. Got "$pathString".'); - } - - if (!path.isWithin(".", pathString)) { - throw new json_rpc.RpcException.invalidParams( - '"$key" cannot reach out of its containing directory. ' 'Got "$pathString".'); - } - - return pathString; - } -} - -/// The pub-specific JSON RPC error codes. -class _Error { - /// The specified directory is not being served. - static const NOT_SERVED = 1; - - /// The specified directory overlaps one or more ones already being served. - static const OVERLAPPING = 2; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/cached_package.dart b/sdk/lib/_internal/pub_generated/lib/src/cached_package.dart deleted file mode 100644 index 1e1c595e8d6..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/cached_package.dart +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.cached_package; - -import 'package:path/path.dart' as p; -import 'package:pub_semver/pub_semver.dart'; -import 'package:yaml/yaml.dart'; - -import 'barback/transformer_config.dart'; -import 'io.dart'; -import 'package.dart'; -import 'pubspec.dart'; - -/// A [Package] whose `lib` directory has been precompiled and cached. -/// -/// When users of this class request path information about files that are -/// cached, this returns the cached information. It also wraps the package's -/// pubspec to report no transformers, since the transformations have all been -/// applied already. -class CachedPackage extends Package { - /// The directory contianing the cached assets from this package. - /// - /// Although only `lib` is cached, this directory corresponds to the root of - /// the package. The actual cached assets exist in `$_cacheDir/lib`. - final String _cacheDir; - - /// Creates a new cached package wrapping [inner] with the cache at - /// [_cacheDir]. - CachedPackage(Package inner, this._cacheDir) - : super(new _CachedPubspec(inner.pubspec), inner.dir); - - String path(String part1, [String part2, String part3, String part4, - String part5, String part6, String part7]) { - if (_pathInCache(part1)) { - return p.join(_cacheDir, part1, part2, part3, part4, part5, part6, part7); - } else { - return super.path(part1, part2, part3, part4, part5, part6, part7); - } - } - - String relative(String path) { - if (p.isWithin(path, _cacheDir)) return p.relative(path, from: _cacheDir); - return super.relative(path); - } - - /// This will include the cached, transformed versions of files if [beneath] - /// is within a cached directory, but not otherwise. - List listFiles({String beneath, recursive: true, bool useGitIgnore: - false}) { - if (beneath == null) { - return super.listFiles(recursive: recursive, useGitIgnore: useGitIgnore); - } - - if (_pathInCache(beneath)) return listDir(p.join(_cacheDir, beneath)); - return super.listFiles( - beneath: beneath, - recursive: recursive, - useGitIgnore: useGitIgnore); - } - - /// Returns whether [relativePath], a path relative to the package's root, - /// is in a cached directory. - bool _pathInCache(String relativePath) => p.isWithin('lib', relativePath); -} - -/// A pubspec wrapper that reports no transformers. -class _CachedPubspec implements Pubspec { - final Pubspec _inner; - - YamlMap get fields => _inner.fields; - String get name => _inner.name; - Version get version => _inner.version; - List get dependencies => _inner.dependencies; - List get devDependencies => _inner.devDependencies; - List get dependencyOverrides => _inner.dependencyOverrides; - PubspecEnvironment get environment => _inner.environment; - String get publishTo => _inner.publishTo; - Map get executables => _inner.executables; - bool get isPrivate => _inner.isPrivate; - bool get isEmpty => _inner.isEmpty; - List get allErrors => _inner.allErrors; - - List> get transformers => const []; - - _CachedPubspec(this._inner); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command.dart b/sdk/lib/_internal/pub_generated/lib/src/command.dart deleted file mode 100644 index 3724b408f10..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command.dart +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command; - -import 'package:args/args.dart'; -import 'package:args/command_runner.dart'; -import 'package:path/path.dart' as path; - -import 'entrypoint.dart'; -import 'log.dart' as log; -import 'global_packages.dart'; -import 'system_cache.dart'; - -/// The base class for commands for the pub executable. -/// -/// A command may either be a "leaf" command or it may be a parent for a set -/// of subcommands. Only leaf commands are ever actually invoked. If a command -/// has subcommands, then one of those must always be chosen. -abstract class PubCommand extends Command { - SystemCache get cache { - if (_cache == null) { - _cache = new SystemCache.withSources(isOffline: isOffline); - } - return _cache; - } - SystemCache _cache; - - GlobalPackages get globals { - if (_globals == null) { - _globals = new GlobalPackages(cache); - } - return _globals; - } - GlobalPackages _globals; - - /// Gets the [Entrypoint] package for the current working directory. - /// - /// This will load the pubspec and fail with an error if the current directory - /// is not a package. - Entrypoint get entrypoint { - // Lazy load it. - if (_entrypoint == null) { - _entrypoint = new Entrypoint( - path.current, - cache, - packageSymlinks: globalResults['package-symlinks']); - } - return _entrypoint; - } - Entrypoint _entrypoint; - - /// The URL for web documentation for this command. - String get docUrl => null; - - /// Override this and return `false` to disallow trailing options from being - /// parsed after a non-option argument is parsed. - bool get allowTrailingOptions => true; - - ArgParser get argParser { - // Lazily initialize the parser because the superclass constructor requires - // it but we want to initialize it based on [allowTrailingOptions]. - if (_argParser == null) { - _argParser = new ArgParser(allowTrailingOptions: allowTrailingOptions); - } - return _argParser; - } - ArgParser _argParser; - - /// Override this to use offline-only sources instead of hitting the network. - /// - /// This will only be called before the [SystemCache] is created. After that, - /// it has no effect. This only needs to be set in leaf commands. - bool get isOffline => false; - - String get usageFooter { - if (docUrl == null) return null; - return "See $docUrl for detailed documentation."; - } - - void printUsage() { - log.message(usage); - } - - /// Parses a user-supplied integer [intString] named [name]. - /// - /// If the parsing fails, prints a usage message and exits. - int parseInt(String intString, String name) { - try { - return int.parse(intString); - } on FormatException catch (_) { - usageException('Could not parse $name "$intString".'); - } - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/barback.dart b/sdk/lib/_internal/pub_generated/lib/src/command/barback.dart deleted file mode 100644 index 5fdc519b6ab..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/barback.dart +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.barback; - -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as path; - -import '../command.dart'; -import '../io.dart'; -import '../log.dart' as log; -import '../utils.dart'; - -final _arrow = getSpecial('\u2192', '=>'); - -/// The set of top level directories in the entrypoint package that are built -/// when the user does "--all". -final _allSourceDirectories = - new Set.from(["benchmark", "bin", "example", "test", "web"]); - -/// Shared base class for [BuildCommand] and [ServeCommand]. -abstract class BarbackCommand extends PubCommand { - /// The build mode. - BarbackMode get mode => new BarbackMode(argResults["mode"]); - - /// The directories in the entrypoint package that should be added to the - /// build environment. - final sourceDirectories = new Set(); - - /// The default build mode. - BarbackMode get defaultMode => BarbackMode.RELEASE; - - /// Override this to specify the default source directories if none are - /// provided on the command line. - List get defaultSourceDirectories; - - BarbackCommand() { - argParser.addOption( - "mode", - defaultsTo: defaultMode.toString(), - help: "Mode to run transformers in."); - - argParser.addFlag( - "all", - help: "Use all default source directories.", - defaultsTo: false, - negatable: false); - } - - Future run() { - // Switch to JSON output if specified. We need to do this before parsing - // the source directories so an error will be correctly reported in JSON - // format. - log.json.enabled = - argResults.options.contains("format") && argResults["format"] == "json"; - - _parseSourceDirectories(); - return onRunTransformerCommand(); - } - - /// Override this to run the actual command. - Future onRunTransformerCommand(); - - /// Parses the command-line arguments to determine the set of source - /// directories to add to the build environment. - /// - /// If there are no arguments, this will just be [defaultSourceDirectories]. - /// - /// If the `--all` flag is set, then it will be all default directories - /// that exist. - /// - /// Otherwise, all arguments should be the paths of directories to include. - /// - /// Throws an exception if the arguments are invalid. - void _parseSourceDirectories() { - if (argResults["all"]) { - _addAllDefaultSources(); - return; - } - - // If no directories were specified, use the defaults. - if (argResults.rest.isEmpty) { - _addDefaultSources(); - return; - } - - sourceDirectories.addAll(argResults.rest); - - // Prohibit "lib". - var disallowed = sourceDirectories.where((dir) { - var parts = path.split(path.normalize(dir)); - return parts.isNotEmpty && parts.first == "lib"; - }); - - if (disallowed.isNotEmpty) { - usageException( - _directorySentence(disallowed, "is", "are", "not allowed")); - } - - // Make sure the source directories don't reach out of the package. - var invalid = sourceDirectories.where((dir) => !path.isWithin('.', dir)); - if (invalid.isNotEmpty) { - usageException( - _directorySentence(invalid, "isn't", "aren't", "in this package")); - } - - // Make sure all of the source directories exist. - var missing = - sourceDirectories.where((dir) => !dirExists(entrypoint.root.path(dir))); - - if (missing.isNotEmpty) { - dataError(_directorySentence(missing, "does", "do", "not exist")); - } - - // Make sure the directories don't overlap. - var sources = sourceDirectories.toList(); - var overlapping = new Set(); - for (var i = 0; i < sources.length; i++) { - for (var j = i + 1; j < sources.length; j++) { - if (path.isWithin(sources[i], sources[j]) || - path.isWithin(sources[j], sources[i])) { - overlapping.add(sources[i]); - overlapping.add(sources[j]); - } - } - } - - if (overlapping.isNotEmpty) { - usageException( - _directorySentence(overlapping, "cannot", "cannot", "overlap")); - } - } - - /// Handles "--all" by adding all default source directories that are - /// present. - void _addAllDefaultSources() { - if (argResults.rest.isNotEmpty) { - usageException('Directory names are not allowed if "--all" is passed.'); - } - - // Include every build directory that exists in the package. - var dirs = - _allSourceDirectories.where((dir) => dirExists(entrypoint.root.path(dir))); - - if (dirs.isEmpty) { - var defaultDirs = - toSentence(_allSourceDirectories.map((name) => '"$name"')); - dataError( - 'There are no source directories present.\n' - 'The default directories are $defaultDirs.'); - } - - sourceDirectories.addAll(dirs); - } - - /// Adds the default sources that should be used if no directories are passed - /// on the command line. - void _addDefaultSources() { - sourceDirectories.addAll( - defaultSourceDirectories.where((dir) => dirExists(entrypoint.root.path(dir)))); - - // TODO(rnystrom): Hackish. Assumes there will only be one or two - // default sources. That's true for pub build and serve, but isn't as - // general as it could be. - if (sourceDirectories.isEmpty) { - var defaults; - if (defaultSourceDirectories.length == 1) { - defaults = 'a "${defaultSourceDirectories.first}" directory'; - } else { - defaults = - '"${defaultSourceDirectories[0]}" and/or ' - '"${defaultSourceDirectories[1]}" directories'; - } - - dataError( - "Your package must have $defaults,\n" - "or you must specify the source directories."); - } - } - - /// Converts a list of [directoryNames] to a sentence. - /// - /// After the list of directories, [singularVerb] will be used if there is - /// only one directory and [pluralVerb] will be used if there are more than - /// one. Then [suffix] is added to the end of the sentence, and, finally, a - /// period is added. - String _directorySentence(Iterable directoryNames, - String singularVerb, String pluralVerb, String suffix) { - var directories = - pluralize('Directory', directoryNames.length, plural: 'Directories'); - var names = toSentence(directoryNames.map((dir) => '"$dir"')); - var verb = - pluralize(singularVerb, directoryNames.length, plural: pluralVerb); - - var result = "$directories $names $verb"; - if (suffix != null) result += " $suffix"; - result += "."; - - return result; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/build.dart b/sdk/lib/_internal/pub_generated/lib/src/command/build.dart deleted file mode 100644 index 80060c86f9d..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/build.dart +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.build; - -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as path; - -import '../barback/asset_environment.dart'; -import '../exit_codes.dart' as exit_codes; -import '../io.dart'; -import '../log.dart' as log; -import '../utils.dart'; -import 'barback.dart'; - -final _arrow = getSpecial('\u2192', '=>'); - -/// Handles the `build` pub command. -class BuildCommand extends BarbackCommand { - String get name => "build"; - String get description => "Apply transformers to build a package."; - String get invocation => "pub build [options] [directories...]"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-build.html"; - List get aliases => const ["deploy", "settle-up"]; - - /// The path to the application's build output directory. - String get outputDirectory => argResults["output"]; - - List get defaultSourceDirectories => ["web"]; - - /// The number of files that have been built and written to disc so far. - int builtFiles = 0; - - BuildCommand() { - argParser.addOption( - "format", - help: "How output should be displayed.", - allowed: ["text", "json"], - defaultsTo: "text"); - - argParser.addOption( - "output", - abbr: "o", - help: "Directory to write build outputs to.", - defaultsTo: "build"); - } - - Future onRunTransformerCommand() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - cleanDir(outputDirectory); - var errorsJson = []; - var logJson = []; - completer0.complete( - AssetEnvironment.create( - entrypoint, - mode, - useDart2JS: true).then(((environment) { - environment.barback.errors.listen((error) { - log.error(log.red("Build error:\n$error")); - if (log.json.enabled) { - errorsJson.add({ - "error": error.toString() - }); - } - }); - if (log.json.enabled) { - environment.barback.log.listen( - (entry) => logJson.add(_logEntryToJson(entry))); - } - return log.progress("Building ${entrypoint.root.name}", () { - return Future.wait( - sourceDirectories.map((dir) => environment.serveDirectory(dir))).then((_) { - return environment.barback.getAllAssets(); - }); - }).then((assets) { - var dart2JSEntrypoints = assets.where( - (asset) => asset.id.path.endsWith(".dart.js")).map((asset) => asset.id); - return Future.wait(assets.map(_writeAsset)).then((_) { - builtFiles += _copyBrowserJsFiles(dart2JSEntrypoints); - log.message( - 'Built $builtFiles ${pluralize('file', builtFiles)} ' 'to "$outputDirectory".'); - log.json.message({ - "buildResult": "success", - "outputDirectory": outputDirectory, - "numFiles": builtFiles, - "log": logJson - }); - }); - }); - })).catchError(((error) { - if (error is! BarbackException) throw error; - log.error(log.red("Build failed.")); - log.json.message({ - "buildResult": "failure", - "errors": errorsJson, - "log": logJson - }); - return flushThenExit(exit_codes.DATA); - }))); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Writes [asset] to the appropriate build directory. - /// - /// If [asset] is in the special "packages" directory, writes it to every - /// build directory. - Future _writeAsset(Asset asset) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - var destPath = _idToPath(asset.id); - join1() { - completer0.complete(_writeOutputFile(asset, destPath)); - } - if (path.isWithin("packages", destPath)) { - completer0.complete(Future.wait(sourceDirectories.map(((buildDir) { - return _writeOutputFile(asset, path.join(buildDir, destPath)); - })))); - } else { - join1(); - } - } - if (mode == BarbackMode.RELEASE && asset.id.extension == ".dart") { - completer0.complete(null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Converts [id] to a relative path in the output directory for that asset. - /// - /// This corresponds to the URL that could be used to request that asset from - /// pub serve. - /// - /// Examples (where entrypoint is "myapp"): - /// - /// myapp|web/index.html -> web/index.html - /// myapp|lib/lib.dart -> packages/myapp/lib.dart - /// foo|lib/foo.dart -> packages/foo/foo.dart - /// myapp|test/main.dart -> test/main.dart - /// foo|test/main.dart -> ERROR - /// - /// Throws a [FormatException] if [id] is not a valid public asset. - String _idToPath(AssetId id) { - var parts = path.split(path.fromUri(id.path)); - - if (parts.length < 2) { - throw new FormatException( - "Can not build assets from top-level directory."); - } - - // Map "lib" to the "packages" directory. - if (parts[0] == "lib") { - return path.join("packages", id.package, path.joinAll(parts.skip(1))); - } - - // Shouldn't be trying to access non-public directories of other packages. - assert(id.package == entrypoint.root.name); - - // Allow any path in the entrypoint package. - return path.joinAll(parts); - } - - /// Writes the contents of [asset] to [relativePath] within the build - /// directory. - Future _writeOutputFile(Asset asset, String relativePath) { - builtFiles++; - var destPath = path.join(outputDirectory, relativePath); - ensureDir(path.dirname(destPath)); - return createFileFromStream(asset.read(), destPath); - } - - /// If this package depends directly on the `browser` package, this ensures - /// that the JavaScript bootstrap files are copied into `packages/browser/` - /// directories next to each entrypoint in [entrypoints]. - /// - /// Returns the number of files it copied. - int _copyBrowserJsFiles(Iterable entrypoints) { - // Must depend on the browser package. - if (!entrypoint.root.immediateDependencies.any( - (dep) => dep.name == 'browser' && dep.source == 'hosted')) { - return 0; - } - - // Get all of the subdirectories that contain Dart entrypoints. - var entrypointDirs = - entrypoints// Convert the asset path to a native-separated one and get the - // directory containing the entrypoint. - .map( - (id) => - path.dirname( - path.fromUri( - id.path)))// Don't copy files to the top levels of the build directories since - // the normal lib asset copying will take care of that. - .where((dir) => path.split(dir).length > 1).toSet(); - - for (var dir in entrypointDirs) { - // TODO(nweiz): we should put browser JS files next to any HTML file - // rather than any entrypoint. An HTML file could import an entrypoint - // that's not adjacent. - _addBrowserJs(dir, "dart"); - _addBrowserJs(dir, "interop"); - } - - return entrypointDirs.length * 2; - } - - // TODO(nweiz): do something more principled when issue 6101 is fixed. - /// Ensures that the [name].js file is copied into [directory] in [target], - /// under `packages/browser/`. - void _addBrowserJs(String directory, String name) { - var jsPath = entrypoint.root.path( - outputDirectory, - directory, - 'packages', - 'browser', - '$name.js'); - ensureDir(path.dirname(jsPath)); - - // TODO(rnystrom): This won't work if we get rid of symlinks and the top - // level "packages" directory. Will need to copy from the browser - // directory. - copyFile(path.join(entrypoint.packagesDir, 'browser', '$name.js'), jsPath); - } - - /// Converts [entry] to a JSON object for use with JSON-formatted output. - Map _logEntryToJson(LogEntry entry) { - var data = { - "level": entry.level.name, - "transformer": { - "name": entry.transform.transformer.toString(), - "primaryInput": { - "package": entry.transform.primaryId.package, - "path": entry.transform.primaryId.path - }, - }, - "assetId": { - "package": entry.assetId.package, - "path": entry.assetId.path - }, - "message": entry.message - }; - - if (entry.span != null) { - data["span"] = { - "url": entry.span.sourceUrl, - "start": { - "line": entry.span.start.line, - "column": entry.span.start.column - }, - "end": { - "line": entry.span.end.line, - "column": entry.span.end.column - }, - }; - } - - return data; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache.dart deleted file mode 100644 index 432f0965535..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/cache.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.cache; - -import '../command.dart'; -import 'cache_add.dart'; -import 'cache_list.dart'; -import 'cache_repair.dart'; - -/// Handles the `cache` pub command. -class CacheCommand extends PubCommand { - String get name => "cache"; - String get description => "Work with the system cache."; - String get invocation => "pub cache "; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-cache.html"; - - CacheCommand() { - addSubcommand(new CacheAddCommand()); - addSubcommand(new CacheListCommand()); - addSubcommand(new CacheRepairCommand()); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache_add.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache_add.dart deleted file mode 100644 index 1ad264662d0..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/cache_add.dart +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.cache_add; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; - -import '../command.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../utils.dart'; - -/// Handles the `cache add` pub command. -class CacheAddCommand extends PubCommand { - String get name => "add"; - String get description => "Install a package."; - String get invocation => - "pub cache add [--version ] [--all]"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-cache.html"; - - CacheAddCommand() { - argParser.addFlag( - "all", - help: "Install all matching versions.", - negatable: false); - - argParser.addOption("version", abbr: "v", help: "Version constraint."); - } - - Future run() { - // Make sure there is a package. - if (argResults.rest.isEmpty) { - usageException("No package to add given."); - } - - // Don't allow extra arguments. - if (argResults.rest.length > 1) { - var unexpected = argResults.rest.skip(1).map((arg) => '"$arg"'); - var arguments = pluralize("argument", unexpected.length); - usageException("Unexpected $arguments ${toSentence(unexpected)}."); - } - - var package = argResults.rest.single; - - // Parse the version constraint, if there is one. - var constraint = VersionConstraint.any; - if (argResults["version"] != null) { - try { - constraint = new VersionConstraint.parse(argResults["version"]); - } on FormatException catch (error) { - usageException(error.message); - } - } - - // TODO(rnystrom): Support installing from git too. - var source = cache.sources["hosted"]; - - // TODO(rnystrom): Allow specifying the server. - return source.getVersions(package, package).then((versions) { - versions = versions.where(constraint.allows).toList(); - - if (versions.isEmpty) { - // TODO(rnystrom): Show most recent unmatching version? - fail("Package $package has no versions that match $constraint."); - } - - downloadVersion(Version version) { - var id = new PackageId(package, source.name, version, package); - return cache.contains(id).then((contained) { - if (contained) { - // TODO(rnystrom): Include source and description if not hosted. - // See solve_report.dart for code to harvest. - log.message("Already cached ${id.name} ${id.version}."); - return null; - } - - // Download it. - return source.downloadToSystemCache(id); - }); - } - - if (argResults["all"]) { - // Install them in ascending order. - versions.sort(); - return Future.forEach(versions, downloadVersion); - } else { - // Pick the best matching version. - versions.sort(Version.prioritize); - return downloadVersion(versions.last); - } - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache_list.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache_list.dart deleted file mode 100644 index 78f7e8a0cac..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/cache_list.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.cache_list; - -import 'dart:convert'; - -import '../command.dart'; -import '../log.dart' as log; -import '../source/cached.dart'; - -/// Handles the `cache list` pub command. -class CacheListCommand extends PubCommand { - String get name => "list"; - String get description => "List packages in the system cache."; - String get invocation => "pub cache list"; - bool get hidden => true; - bool get takesArguments => false; - - void run() { - // TODO(keertip): Add flag to list packages from non default sources. - var packagesObj = {}; - - var source = cache.sources.defaultSource as CachedSource; - for (var package in source.getCachedPackages()) { - var packageInfo = packagesObj.putIfAbsent(package.name, () => {}); - packageInfo[package.version.toString()] = { - 'location': package.dir - }; - } - - // TODO(keertip): Add support for non-JSON format and check for --format - // flag. - log.message(JSON.encode({ - 'packages': packagesObj - })); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/cache_repair.dart b/sdk/lib/_internal/pub_generated/lib/src/command/cache_repair.dart deleted file mode 100644 index 5b1e13c7b12..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/cache_repair.dart +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.cache_repair; - -import 'dart:async'; - -import '../command.dart'; -import '../exit_codes.dart' as exit_codes; -import '../io.dart'; -import '../log.dart' as log; -import '../source/cached.dart'; -import '../utils.dart'; - -/// Handles the `cache repair` pub command. -class CacheRepairCommand extends PubCommand { - String get name => "repair"; - String get description => "Reinstall cached packages."; - String get invocation => "pub cache repair"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-cache.html"; - bool get takesArguments => false; - - Future run() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var successes = 0; - var failures = 0; - var it0 = cache.sources.iterator; - break0() { - join0() { - join1() { - new Future.value(globals.repairActivatedPackages()).then((x0) { - try { - var results = x0; - join2() { - join3() { - join4() { - join5() { - completer0.complete(); - } - if (failures > 0) { - new Future.value( - flushThenExit(exit_codes.UNAVAILABLE)).then((x1) { - try { - x1; - join5(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } else { - join5(); - } - } - if (successes == 0 && failures == 0) { - log.message( - "No packages in cache, so nothing to repair."); - join4(); - } else { - join4(); - } - } - if (results.last > 0) { - var packages = pluralize("package", results.last); - log.message( - "Failed to reactivate ${log.red(results.last)} ${packages}."); - join3(); - } else { - join3(); - } - } - if (results.first > 0) { - var packages = pluralize("package", results.first); - log.message( - "Reactivated ${log.green(results.first)} ${packages}."); - join2(); - } else { - join2(); - } - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } - if (failures > 0) { - var packages = pluralize("package", failures); - log.message( - "Failed to reinstall ${log.red(failures)} ${packages}."); - join1(); - } else { - join1(); - } - } - if (successes > 0) { - var packages = pluralize("package", successes); - log.message("Reinstalled ${log.green(successes)} ${packages}."); - join0(); - } else { - join0(); - } - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var source = it0.current; - join6() { - new Future.value(source.repairCachedPackages()).then((x2) { - trampoline0 = () { - trampoline0 = null; - try { - var results = x2; - successes += results.first; - failures += results.last; - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: completer0.completeError); - } - if (source is! CachedSource) { - continue0(); - } else { - join6(); - } - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/deps.dart b/sdk/lib/_internal/pub_generated/lib/src/command/deps.dart deleted file mode 100644 index ce5bcdd107f..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/deps.dart +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.list; - -import 'dart:async'; -import 'dart:collection'; - -import '../ascii_tree.dart' as tree; -import '../command.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../package_graph.dart'; -import '../utils.dart'; - -/// Handles the `deps` pub command. -class DepsCommand extends PubCommand { - String get name => "deps"; - String get description => "Print package dependencies."; - List get aliases => const ["dependencies", "tab"]; - String get invocation => "pub deps"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-deps.html"; - bool get takesArguments => false; - - /// The loaded package graph. - PackageGraph _graph; - - /// The [StringBuffer] used to accumulate the output. - StringBuffer _buffer; - - DepsCommand() { - argParser.addOption( - "style", - abbr: "s", - help: "How output should be displayed.", - allowed: ["compact", "tree", "list"], - defaultsTo: "tree"); - } - - Future run() { - return entrypoint.loadPackageGraph().then((graph) { - _graph = graph; - _buffer = new StringBuffer(); - - _buffer.writeln(_labelPackage(entrypoint.root)); - - switch (argResults["style"]) { - case "compact": - _outputCompact(); - break; - case "list": - _outputList(); - break; - case "tree": - _outputTree(); - break; - } - - log.message(_buffer); - }); - } - - /// Outputs a list of all of the package's immediate, dev, override, and - /// transitive dependencies. - /// - /// For each dependency listed, *that* package's immediate dependencies are - /// shown. Unlike [_outputList], this prints all of these dependencies on one - /// line. - void _outputCompact() { - var root = entrypoint.root; - _outputCompactPackages( - "dependencies", - root.dependencies.map((dep) => dep.name)); - _outputCompactPackages( - "dev dependencies", - root.devDependencies.map((dep) => dep.name)); - _outputCompactPackages( - "dependency overrides", - root.dependencyOverrides.map((dep) => dep.name)); - - var transitive = _getTransitiveDependencies(); - _outputCompactPackages("transitive dependencies", transitive); - } - - /// Outputs one section of packages in the compact output. - _outputCompactPackages(String section, Iterable names) { - if (names.isEmpty) return; - - _buffer.writeln(); - _buffer.writeln("$section:"); - for (var name in ordered(names)) { - var package = _graph.packages[name]; - - _buffer.write("- ${_labelPackage(package)}"); - if (package.dependencies.isEmpty) { - _buffer.writeln(); - } else { - var depNames = package.dependencies.map((dep) => dep.name); - var depsList = "[${depNames.join(' ')}]"; - _buffer.writeln(" ${log.gray(depsList)}"); - } - } - } - - /// Outputs a list of all of the package's immediate, dev, override, and - /// transitive dependencies. - /// - /// For each dependency listed, *that* package's immediate dependencies are - /// shown. - void _outputList() { - var root = entrypoint.root; - _outputListSection( - "dependencies", - root.dependencies.map((dep) => dep.name)); - _outputListSection( - "dev dependencies", - root.devDependencies.map((dep) => dep.name)); - _outputListSection( - "dependency overrides", - root.dependencyOverrides.map((dep) => dep.name)); - - var transitive = _getTransitiveDependencies(); - if (transitive.isEmpty) return; - - _outputListSection("transitive dependencies", ordered(transitive)); - } - - /// Outputs one section of packages in the list output. - _outputListSection(String name, Iterable deps) { - if (deps.isEmpty) return; - - _buffer.writeln(); - _buffer.writeln("$name:"); - - for (var name in deps) { - var package = _graph.packages[name]; - _buffer.writeln("- ${_labelPackage(package)}"); - - for (var dep in package.dependencies) { - _buffer.writeln( - " - ${log.bold(dep.name)} ${log.gray(dep.constraint)}"); - } - } - } - - /// Generates a dependency tree for the root package. - /// - /// If a package is encountered more than once (i.e. a shared or circular - /// dependency), later ones are not traversed. This is done in breadth-first - /// fashion so that a package will always be expanded at the shallowest - /// depth that it appears at. - void _outputTree() { - // The work list for the breadth-first traversal. It contains the package - // being added to the tree, and the parent map that will receive that - // package. - var toWalk = new Queue>(); - var visited = new Set(); - - // Start with the root dependencies. - var packageTree = {}; - for (var dep in entrypoint.root.immediateDependencies) { - toWalk.add(new Pair(_graph.packages[dep.name], packageTree)); - } - - // Do a breadth-first walk to the dependency graph. - while (toWalk.isNotEmpty) { - var pair = toWalk.removeFirst(); - var package = pair.first; - var map = pair.last; - - if (visited.contains(package.name)) { - map[log.gray('${package.name}...')] = {}; - continue; - } - - visited.add(package.name); - - // Populate the map with this package's dependencies. - var childMap = {}; - map[_labelPackage(package)] = childMap; - - for (var dep in package.dependencies) { - toWalk.add(new Pair(_graph.packages[dep.name], childMap)); - } - } - - _buffer.write(tree.fromMap(packageTree, showAllChildren: true)); - } - - String _labelPackage(Package package) => - "${log.bold(package.name)} ${package.version}"; - - /// Gets the names of the non-immediate dependencies of the root package. - Set _getTransitiveDependencies() { - var transitive = _graph.packages.keys.toSet(); - var root = entrypoint.root; - transitive.remove(root.name); - transitive.removeAll(root.dependencies.map((dep) => dep.name)); - transitive.removeAll(root.devDependencies.map((dep) => dep.name)); - transitive.removeAll(root.dependencyOverrides.map((dep) => dep.name)); - return transitive; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/downgrade.dart b/sdk/lib/_internal/pub_generated/lib/src/command/downgrade.dart deleted file mode 100644 index 87364022c38..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/downgrade.dart +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.downgrade; - -import 'dart:async'; - -import '../command.dart'; -import '../log.dart' as log; -import '../solver/version_solver.dart'; - -/// Handles the `downgrade` pub command. -class DowngradeCommand extends PubCommand { - String get name => "downgrade"; - String get description => - "Downgrade the current package's dependencies to oldest versions.\n\n" - "This doesn't modify the lockfile, so it can be reset with \"pub get\"."; - String get invocation => "pub downgrade [dependencies...]"; - - bool get isOffline => argResults['offline']; - - DowngradeCommand() { - argParser.addFlag( - 'offline', - help: 'Use cached packages instead of accessing the network.'); - - argParser.addFlag( - 'dry-run', - abbr: 'n', - negatable: false, - help: "Report what dependencies would change but don't change any."); - } - - Future run() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var dryRun = argResults['dry-run']; - new Future.value( - entrypoint.acquireDependencies( - SolveType.DOWNGRADE, - useLatest: argResults.rest, - dryRun: dryRun)).then((x0) { - try { - x0; - join0() { - completer0.complete(); - } - if (isOffline) { - log.warning( - "Warning: Downgrading when offline may not update you to " - "the oldest versions of your dependencies."); - join0(); - } else { - join0(); - } - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/get.dart b/sdk/lib/_internal/pub_generated/lib/src/command/get.dart deleted file mode 100644 index 70f75184ca0..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/get.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.get; - -import 'dart:async'; - -import '../command.dart'; -import '../solver/version_solver.dart'; - -/// Handles the `get` pub command. -class GetCommand extends PubCommand { - String get name => "get"; - String get description => "Get the current package's dependencies."; - String get invocation => "pub get"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-get.html"; - List get aliases => const ["install"]; - bool get isOffline => argResults["offline"]; - - GetCommand() { - argParser.addFlag( - 'offline', - help: 'Use cached packages instead of accessing the network.'); - - argParser.addFlag( - 'dry-run', - abbr: 'n', - negatable: false, - help: "Report what dependencies would change but don't change any."); - } - - Future run() { - return entrypoint.acquireDependencies( - SolveType.GET, - dryRun: argResults['dry-run']); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global.dart deleted file mode 100644 index c2ddfd8e3bd..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/global.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.global; - -import '../command.dart'; -import 'global_activate.dart'; -import 'global_deactivate.dart'; -import 'global_list.dart'; -import 'global_run.dart'; - -/// Handles the `global` pub command. -class GlobalCommand extends PubCommand { - String get name => "global"; - String get description => "Work with global packages."; - String get invocation => "pub global "; - - GlobalCommand() { - addSubcommand(new GlobalActivateCommand()); - addSubcommand(new GlobalDeactivateCommand()); - addSubcommand(new GlobalListCommand()); - addSubcommand(new GlobalRunCommand()); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_activate.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_activate.dart deleted file mode 100644 index f567f4bf04b..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/global_activate.dart +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.global_activate; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; - -import '../command.dart'; -import '../utils.dart'; - -/// Handles the `global activate` pub command. -class GlobalActivateCommand extends PubCommand { - String get name => "activate"; - String get description => "Make a package's executables globally available."; - String get invocation => "pub global activate "; - - GlobalActivateCommand() { - argParser.addOption( - "source", - abbr: "s", - help: "The source used to find the package.", - allowed: ["git", "hosted", "path"], - defaultsTo: "hosted"); - - argParser.addFlag( - "no-executables", - negatable: false, - help: "Do not put executables on PATH."); - - argParser.addOption( - "executable", - abbr: "x", - help: "Executable(s) to place on PATH.", - allowMultiple: true); - - argParser.addFlag( - "overwrite", - negatable: false, - help: "Overwrite executables from other packages with the same name."); - } - - Future run() { - // Default to `null`, which means all executables. - var executables; - if (argResults.wasParsed("executable")) { - if (argResults.wasParsed("no-executables")) { - usageException("Cannot pass both --no-executables and --executable."); - } - - executables = argResults["executable"]; - } else if (argResults["no-executables"]) { - // An empty list means no executables. - executables = []; - } - - var overwrite = argResults["overwrite"]; - var args = argResults.rest; - - readArg([String error]) { - if (args.isEmpty) usageException(error); - var arg = args.first; - args = args.skip(1); - return arg; - } - - validateNoExtraArgs() { - if (args.isEmpty) return; - var unexpected = args.map((arg) => '"$arg"'); - var arguments = pluralize("argument", unexpected.length); - usageException("Unexpected $arguments ${toSentence(unexpected)}."); - } - - switch (argResults["source"]) { - case "git": - var repo = readArg("No Git repository given."); - // TODO(rnystrom): Allow passing in a Git ref too. - validateNoExtraArgs(); - return globals.activateGit( - repo, - executables, - overwriteBinStubs: overwrite); - - case "hosted": - var package = readArg("No package to activate given."); - - // Parse the version constraint, if there is one. - var constraint = VersionConstraint.any; - if (args.isNotEmpty) { - try { - constraint = new VersionConstraint.parse(readArg()); - } on FormatException catch (error) { - usageException(error.message); - } - } - - validateNoExtraArgs(); - return globals.activateHosted( - package, - constraint, - executables, - overwriteBinStubs: overwrite); - - case "path": - var path = readArg("No package to activate given."); - validateNoExtraArgs(); - return globals.activatePath( - path, - executables, - overwriteBinStubs: overwrite); - } - - throw "unreachable"; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_deactivate.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_deactivate.dart deleted file mode 100644 index 595f6ffd798..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/global_deactivate.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.global_deactivate; - -import 'dart:async'; - -import '../command.dart'; -import '../log.dart' as log; -import '../utils.dart'; - -/// Handles the `global deactivate` pub command. -class GlobalDeactivateCommand extends PubCommand { - String get name => "deactivate"; - String get description => "Remove a previously activated package."; - String get invocation => "pub global deactivate "; - - void run() { - // Make sure there is a package. - if (argResults.rest.isEmpty) { - usageException("No package to deactivate given."); - } - - // Don't allow extra arguments. - if (argResults.rest.length > 1) { - var unexpected = argResults.rest.skip(1).map((arg) => '"$arg"'); - var arguments = pluralize("argument", unexpected.length); - usageException("Unexpected $arguments ${toSentence(unexpected)}."); - } - - if (!globals.deactivate(argResults.rest.first)) { - dataError("No active package ${log.bold(argResults.rest.first)}."); - } - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_list.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_list.dart deleted file mode 100644 index 1de107305db..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/global_list.dart +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.global_list; - -import 'dart:async'; - -import '../command.dart'; - -/// Handles the `global list` pub command. -class GlobalListCommand extends PubCommand { - String get name => "list"; - String get description => 'List globally activated packages.'; - String get invocation => 'pub global list'; - bool get allowTrailingOptions => false; - bool get takesArguments => false; - - void run() { - globals.listActivePackages(); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/global_run.dart b/sdk/lib/_internal/pub_generated/lib/src/command/global_run.dart deleted file mode 100644 index 54874c135a1..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/global_run.dart +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.global_run; - -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; - -import '../command.dart'; -import '../io.dart'; -import '../utils.dart'; - -/// Handles the `global run` pub command. -class GlobalRunCommand extends PubCommand { - String get name => "run"; - String get description => - "Run an executable from a globally activated package.\n" - "NOTE: We are currently optimizing this command's startup time."; - String get invocation => "pub global run : [args...]"; - bool get allowTrailingOptions => false; - - /// The mode for barback transformers. - BarbackMode get mode => new BarbackMode(argResults["mode"]); - - GlobalRunCommand() { - argParser.addOption( - "mode", - defaultsTo: "release", - help: 'Mode to run transformers in.'); - } - - Future run() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - var package; - var executable = argResults.rest[0]; - join1() { - var args = argResults.rest.skip(1).toList(); - join2() { - new Future.value( - globals.runExecutable(package, executable, args, mode: mode)).then((x0) { - try { - var exitCode = x0; - new Future.value(flushThenExit(exitCode)).then((x1) { - try { - x1; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } - if (p.split(executable).length > 1) { - usageException( - 'Cannot run an executable in a subdirectory of a global ' + 'package.'); - join2(); - } else { - join2(); - } - } - if (executable.contains(":")) { - var parts = split1(executable, ":"); - package = parts[0]; - executable = parts[1]; - join1(); - } else { - package = executable; - join1(); - } - } - if (argResults.rest.isEmpty) { - usageException("Must specify an executable to run."); - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/lish.dart b/sdk/lib/_internal/pub_generated/lib/src/command/lish.dart deleted file mode 100644 index ef5840e4302..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/lish.dart +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.lish; - -import 'dart:async'; - -import 'package:http/http.dart' as http; - -import '../command.dart'; -import '../ascii_tree.dart' as tree; -import '../http.dart'; -import '../io.dart'; -import '../log.dart' as log; -import '../oauth2.dart' as oauth2; -import '../source/hosted.dart'; -import '../utils.dart'; -import '../validator.dart'; - -/// Handles the `lish` and `publish` pub commands. -class LishCommand extends PubCommand { - String get name => "publish"; - String get description => "Publish the current package to pub.dartlang.org."; - String get invocation => "pub publish [options]"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-lish.html"; - List get aliases => const ["lish", "lush"]; - bool get takesArguments => false; - - /// The URL of the server to which to upload the package. - Uri get server { - // An explicit argument takes precedence. - if (argResults.wasParsed('server')) { - return Uri.parse(argResults['server']); - } - - // Otherwise, use the one specified in the pubspec. - if (entrypoint.root.pubspec.publishTo != null) { - return Uri.parse(entrypoint.root.pubspec.publishTo); - } - - // Otherwise, use the default. - return Uri.parse(HostedSource.defaultUrl); - } - - /// Whether the publish is just a preview. - bool get dryRun => argResults['dry-run']; - - /// Whether the publish requires confirmation. - bool get force => argResults['force']; - - LishCommand() { - argParser.addFlag( - 'dry-run', - abbr: 'n', - negatable: false, - help: 'Validate but do not publish the package.'); - argParser.addFlag( - 'force', - abbr: 'f', - negatable: false, - help: 'Publish without confirmation if there are no errors.'); - argParser.addOption( - 'server', - defaultsTo: HostedSource.defaultUrl, - help: 'The package server to which to upload this package.'); - } - - Future _publish(packageBytes) { - var cloudStorageUrl; - return oauth2.withClient(cache, (client) { - return log.progress('Uploading', () { - // TODO(nweiz): Cloud Storage can provide an XML-formatted error. We - // should report that error and exit. - var newUri = server.resolve("/api/packages/versions/new"); - return client.get(newUri, headers: PUB_API_HEADERS).then((response) { - var parameters = parseJsonResponse(response); - - var url = _expectField(parameters, 'url', response); - if (url is! String) invalidServerResponse(response); - cloudStorageUrl = Uri.parse(url); - var request = new http.MultipartRequest('POST', cloudStorageUrl); - request.headers['Pub-Request-Timeout'] = 'None'; - - var fields = _expectField(parameters, 'fields', response); - if (fields is! Map) invalidServerResponse(response); - fields.forEach((key, value) { - if (value is! String) invalidServerResponse(response); - request.fields[key] = value; - }); - - request.followRedirects = false; - request.files.add( - new http.MultipartFile.fromBytes( - 'file', - packageBytes, - filename: 'package.tar.gz')); - return client.send(request); - }).then(http.Response.fromStream).then((response) { - var location = response.headers['location']; - if (location == null) throw new PubHttpException(response); - return location; - }).then( - (location) => - client.get(location, headers: PUB_API_HEADERS)).then(handleJsonSuccess); - }); - }).catchError((error) { - if (error is! PubHttpException) throw error; - var url = error.response.request.url; - if (urisEqual(url, cloudStorageUrl)) { - // TODO(nweiz): the response may have XML-formatted information about - // the error. Try to parse that out once we have an easily-accessible - // XML parser. - fail('Failed to upload the package.'); - } else if (urisEqual(Uri.parse(url.origin), Uri.parse(server.origin))) { - handleJsonError(error.response); - } else { - throw error; - } - }); - } - - Future run() { - if (force && dryRun) { - usageException('Cannot use both --force and --dry-run.'); - } - - if (entrypoint.root.pubspec.isPrivate) { - dataError( - 'A private package cannot be published.\n' - 'You can enable this by changing the "publish_to" field in your ' 'pubspec.'); - } - - var files = entrypoint.root.listFiles(useGitIgnore: true); - log.fine('Archiving and publishing ${entrypoint.root}.'); - - // Show the package contents so the user can verify they look OK. - var package = entrypoint.root; - log.message( - 'Publishing ${package.name} ${package.version} to $server:\n' - '${tree.fromFiles(files, baseDir: entrypoint.root.dir)}'); - - var packageBytesFuture = - createTarGz(files, baseDir: entrypoint.root.dir).toBytes(); - - // Validate the package. - return _validate( - packageBytesFuture.then((bytes) => bytes.length)).then((isValid) { - if (isValid) return packageBytesFuture.then(_publish); - }); - } - - /// Returns the value associated with [key] in [map]. Throws a user-friendly - /// error if [map] doens't contain [key]. - _expectField(Map map, String key, http.Response response) { - if (map.containsKey(key)) return map[key]; - invalidServerResponse(response); - } - - /// Validates the package. Completes to false if the upload should not - /// proceed. - Future _validate(Future packageSize) { - return Validator.runAll(entrypoint, packageSize).then((pair) { - var errors = pair.first; - var warnings = pair.last; - - if (!errors.isEmpty) { - log.error( - "Sorry, your package is missing " - "${(errors.length > 1) ? 'some requirements' : 'a requirement'} " - "and can't be published yet.\nFor more information, see: " - "http://pub.dartlang.org/doc/pub-lish.html.\n"); - return false; - } - - if (force) return true; - - if (dryRun) { - var s = warnings.length == 1 ? '' : 's'; - log.warning("\nPackage has ${warnings.length} warning$s."); - return false; - } - - var message = '\nLooks great! Are you ready to upload your package'; - - if (!warnings.isEmpty) { - var s = warnings.length == 1 ? '' : 's'; - message = "\nPackage has ${warnings.length} warning$s. Upload anyway"; - } - - return confirm(message).then((confirmed) { - if (!confirmed) { - log.error("Package upload canceled."); - return false; - } - return true; - }); - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/list_package_dirs.dart b/sdk/lib/_internal/pub_generated/lib/src/command/list_package_dirs.dart deleted file mode 100644 index c68d8e0289d..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/list_package_dirs.dart +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.list_package_dirs; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../command.dart'; -import '../log.dart' as log; -import '../utils.dart'; - -/// Handles the `list-package-dirs` pub command. -class ListPackageDirsCommand extends PubCommand { - String get name => "list-package-dirs"; - String get description => "Print local paths to dependencies."; - String get invocation => "pub list-package-dirs"; - bool get takesArguments => false; - bool get hidden => true; - - ListPackageDirsCommand() { - argParser.addOption( - "format", - help: "How output should be displayed.", - allowed: ["json"]); - } - - Future run() { - log.json.enabled = true; - - if (!entrypoint.lockFileExists) { - dataError('Package "myapp" has no lockfile. Please run "pub get" first.'); - } - - var output = {}; - - // Include the local paths to all locked packages. - var packages = {}; - var futures = []; - entrypoint.lockFile.packages.forEach((name, package) { - var source = entrypoint.cache.sources[package.source]; - futures.add(source.getDirectory(package).then((packageDir) { - packages[name] = path.join(packageDir, "lib"); - })); - }); - - output["packages"] = packages; - - // Include the self link. - packages[entrypoint.root.name] = entrypoint.root.path("lib"); - - // Include the file(s) which when modified will affect the results. For pub, - // that's just the pubspec and lockfile. - output["input_files"] = [entrypoint.lockFilePath, entrypoint.pubspecPath]; - - return Future.wait(futures).then((_) { - log.json.message(output); - }); - } -} - diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/run.dart b/sdk/lib/_internal/pub_generated/lib/src/command/run.dart deleted file mode 100644 index 0d63daf1239..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/run.dart +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.run; - -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; - -import '../command.dart'; -import '../executable.dart'; -import '../io.dart'; -import '../utils.dart'; - -/// Handles the `run` pub command. -class RunCommand extends PubCommand { - String get name => "run"; - String get description => - "Run an executable from a package.\n" - "NOTE: We are currently optimizing this command's startup time."; - String get invocation => "pub run [args...]"; - bool get allowTrailingOptions => false; - - RunCommand() { - argParser.addOption( - "mode", - help: 'Mode to run transformers in.\n' - '(defaults to "release" for dependencies, "debug" for ' 'entrypoint)'); - } - - Future run() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - var package = entrypoint.root.name; - var executable = argResults.rest[0]; - var args = argResults.rest.skip(1).toList(); - join1() { - var mode; - join2() { - new Future.value( - runExecutable(entrypoint, package, executable, args, mode: mode)).then((x0) { - try { - var exitCode = x0; - new Future.value(flushThenExit(exitCode)).then((x1) { - try { - x1; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } - if (argResults['mode'] != null) { - mode = new BarbackMode(argResults['mode']); - join2(); - } else { - join3() { - join2(); - } - if (package == entrypoint.root.name) { - mode = BarbackMode.DEBUG; - join3(); - } else { - mode = BarbackMode.RELEASE; - join3(); - } - } - } - if (executable.contains(":")) { - var components = split1(executable, ":"); - package = components[0]; - executable = components[1]; - join4() { - join1(); - } - if (p.split(executable).length > 1) { - usageException( - "Cannot run an executable in a subdirectory of a " + "dependency."); - join4(); - } else { - join4(); - } - } else { - join1(); - } - } - if (argResults.rest.isEmpty) { - usageException("Must specify an executable to run."); - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/serve.dart b/sdk/lib/_internal/pub_generated/lib/src/command/serve.dart deleted file mode 100644 index 5c5062b5263..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/serve.dart +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.serve; - -import 'dart:async'; -import 'dart:math' as math; - -import 'package:barback/barback.dart'; - -import '../barback/asset_environment.dart'; -import '../barback/pub_package_provider.dart'; -import '../log.dart' as log; -import '../utils.dart'; -import 'barback.dart'; - -final _arrow = getSpecial('\u2192', '=>'); - -/// Handles the `serve` pub command. -class ServeCommand extends BarbackCommand { - String get name => "serve"; - String get description => - 'Run a local web development server.\n\n' - 'By default, this serves "web/" and "test/", but an explicit list of \n' - 'directories to serve can be provided as well.'; - String get invocation => "pub serve [directories...]"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-serve.html"; - - PubPackageProvider _provider; - - String get hostname => argResults['hostname']; - - /// The base port for the servers. - /// - /// This will print a usage error and exit if the specified port is invalid. - int get port => parseInt(argResults['port'], 'port'); - - /// The port for the admin UI. - /// - /// This will print a usage error and exit if the specified port is invalid. - int get adminPort { - var adminPort = argResults['admin-port']; - return adminPort == null ? null : parseInt(adminPort, 'admin port'); - } - - /// `true` if Dart entrypoints should be compiled to JavaScript. - bool get useDart2JS => argResults['dart2js']; - - /// `true` if the admin server URL should be displayed on startup. - bool get logAdminUrl => argResults['log-admin-url']; - - BarbackMode get defaultMode => BarbackMode.DEBUG; - - List get defaultSourceDirectories => ["web", "test"]; - - /// This completer is used to keep pub running (by not completing) and to - /// pipe fatal errors to pub's top-level error-handling machinery. - final _completer = new Completer(); - - ServeCommand() { - argParser.addOption( - 'hostname', - defaultsTo: 'localhost', - help: 'The hostname to listen on.'); - argParser.addOption( - 'port', - defaultsTo: '8080', - help: 'The base port to listen on.'); - - // TODO(rnystrom): A hidden option to print the URL that the admin server - // is bound to on startup. Since this is currently only used for the Web - // Socket interface, we don't want to show it to users, but the tests and - // Editor need this logged to know what port to bind to. - // Remove this (and always log) when #16954 is fixed. - argParser.addFlag('log-admin-url', defaultsTo: false, hide: true); - - // TODO(nweiz): Make this public when issue 16954 is fixed. - argParser.addOption('admin-port', hide: true); - - argParser.addFlag( - 'dart2js', - defaultsTo: true, - help: 'Compile Dart to JavaScript.'); - argParser.addFlag( - 'force-poll', - defaultsTo: false, - help: 'Force the use of a polling filesystem watcher.'); - } - - Future onRunTransformerCommand() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var port = parseInt(argResults['port'], 'port'); - join0(x0) { - var adminPort = x0; - join1(x1) { - var watcherType = x1; - new Future.value( - AssetEnvironment.create( - entrypoint, - mode, - watcherType: watcherType, - hostname: hostname, - basePort: port, - useDart2JS: useDart2JS)).then((x2) { - try { - var environment = x2; - var directoryLength = sourceDirectories.map(((dir) { - return dir.length; - })).reduce(math.max); - new Future.value( - environment.startAdminServer(adminPort)).then((x3) { - try { - var server = x3; - server.results.listen(((_) { - assert(false); - }), onError: _fatalError); - join2() { - environment.pauseUpdates(); - var it0 = sourceDirectories.iterator; - break0() { - environment.barback.errors.listen(((error) { - log.error(log.red("Build error:\n$error")); - })); - environment.barback.results.listen(((result) { - if (result.succeeded) { - log.message( - "Build completed ${log.green('successfully')}"); - } else { - log.message( - "Build completed with " "${log.red(result.errors.length)} errors."); - } - }), onError: _fatalError); - environment.resumeUpdates(); - new Future.value(_completer.future).then((x4) { - try { - x4; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var directory = it0.current; - new Future.value( - _startServer(environment, directory, directoryLength)).then((x5) { - trampoline0 = () { - trampoline0 = null; - try { - x5; - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: completer0.completeError); - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - if (logAdminUrl) { - log.message( - "Running admin server on " "${log.bold('http://${hostname}:${server.port}')}"); - join2(); - } else { - join2(); - } - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }, onError: completer0.completeError); - } catch (e3, s3) { - completer0.completeError(e3, s3); - } - }, onError: completer0.completeError); - } - if (argResults['force-poll']) { - join1(WatcherType.POLLING); - } else { - join1(WatcherType.AUTO); - } - } - if (argResults['admin-port'] == null) { - join0(null); - } else { - join0(parseInt(argResults['admin-port'], 'admin port')); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - Future _startServer(AssetEnvironment environment, String rootDirectory, - int directoryLength) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value(environment.serveDirectory(rootDirectory)).then((x0) { - try { - var server = x0; - join0() { - var prefix = - log.gray(padRight("[${server.rootDirectory}]", directoryLength + 2)); - server.results.listen(((result) { - var buffer = new StringBuffer(); - buffer.write("$prefix "); - if (result.isSuccess) { - buffer.write( - "${log.green('GET')} ${result.url.path} $_arrow ${result.id}"); - } else { - buffer.write("${log.red('GET')} ${result.url.path} $_arrow"); - var error = result.error.toString(); - if (error.contains("\n")) { - buffer.write("\n${prefixLines(error)}"); - } else { - buffer.write(" $error"); - } - } - log.message(buffer); - }), onError: _fatalError); - log.message( - "Serving ${entrypoint.root.name} " - "${padRight(server.rootDirectory, directoryLength)} " - "on ${log.bold('http://${hostname}:${server.port}')}"); - completer0.complete(); - } - if (mode == BarbackMode.RELEASE) { - server.allowAsset = ((url) { - return !url.path.endsWith(".dart"); - }); - join0(); - } else { - join0(); - } - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Reports [error] and exits the server. - void _fatalError(error, [stackTrace]) { - if (_completer.isCompleted) return; - _completer.completeError(error, stackTrace); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/upgrade.dart b/sdk/lib/_internal/pub_generated/lib/src/command/upgrade.dart deleted file mode 100644 index e7f21597b56..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/upgrade.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.upgrade; - -import 'dart:async'; - -import '../command.dart'; -import '../log.dart' as log; -import '../solver/version_solver.dart'; - -/// Handles the `upgrade` pub command. -class UpgradeCommand extends PubCommand { - String get name => "upgrade"; - String get description => - "Upgrade the current package's dependencies to latest versions."; - String get invocation => "pub upgrade [dependencies...]"; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-upgrade.html"; - List get aliases => const ["update"]; - - bool get isOffline => argResults['offline']; - - UpgradeCommand() { - argParser.addFlag( - 'offline', - help: 'Use cached packages instead of accessing the network.'); - - argParser.addFlag( - 'dry-run', - abbr: 'n', - negatable: false, - help: "Report what dependencies would change but don't change any."); - } - - Future run() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var dryRun = argResults['dry-run']; - new Future.value( - entrypoint.acquireDependencies( - SolveType.UPGRADE, - useLatest: argResults.rest, - dryRun: dryRun)).then((x0) { - try { - x0; - join0() { - completer0.complete(); - } - if (isOffline) { - log.warning( - "Warning: Upgrading when offline may not update you to the " - "latest versions of your dependencies."); - join0(); - } else { - join0(); - } - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/uploader.dart b/sdk/lib/_internal/pub_generated/lib/src/command/uploader.dart deleted file mode 100644 index e43bbaea598..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/uploader.dart +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.uploader; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../command.dart'; -import '../entrypoint.dart'; -import '../exit_codes.dart' as exit_codes; -import '../http.dart'; -import '../io.dart'; -import '../log.dart' as log; -import '../oauth2.dart' as oauth2; -import '../source/hosted.dart'; - -/// Handles the `uploader` pub command. -class UploaderCommand extends PubCommand { - String get name => "uploader"; - String get description => - "Manage uploaders for a package on pub.dartlang.org."; - String get invocation => "pub uploader [options] {add/remove} "; - String get docUrl => "http://dartlang.org/tools/pub/cmd/pub-uploader.html"; - - /// The URL of the package hosting server. - Uri get server => Uri.parse(argResults['server']); - - UploaderCommand() { - argParser.addOption( - 'server', - defaultsTo: HostedSource.defaultUrl, - help: 'The package server on which the package is hosted.'); - argParser.addOption( - 'package', - help: 'The package whose uploaders will be modified.\n' - '(defaults to the current package)'); - } - - Future run() { - if (argResults.rest.isEmpty) { - log.error('No uploader command given.'); - this.printUsage(); - return flushThenExit(exit_codes.USAGE); - } - - var rest = argResults.rest.toList(); - - // TODO(rnystrom): Use subcommands for these. - var command = rest.removeAt(0); - if (!['add', 'remove'].contains(command)) { - log.error('Unknown uploader command "$command".'); - this.printUsage(); - return flushThenExit(exit_codes.USAGE); - } else if (rest.isEmpty) { - log.error('No uploader given for "pub uploader $command".'); - this.printUsage(); - return flushThenExit(exit_codes.USAGE); - } - - return new Future.sync(() { - var package = argResults['package']; - if (package != null) return package; - return new Entrypoint(path.current, cache).root.name; - }).then((package) { - var uploader = rest[0]; - return oauth2.withClient(cache, (client) { - if (command == 'add') { - var url = - server.resolve("/api/packages/" "${Uri.encodeComponent(package)}/uploaders"); - return client.post(url, headers: PUB_API_HEADERS, body: { - "email": uploader - }); - } else { // command == 'remove' - var url = server.resolve( - "/api/packages/" "${Uri.encodeComponent(package)}/uploaders/" - "${Uri.encodeComponent(uploader)}"); - return client.delete(url, headers: PUB_API_HEADERS); - } - }); - }).then( - handleJsonSuccess).catchError( - (error) => handleJsonError(error.response), - test: (e) => e is PubHttpException); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command/version.dart b/sdk/lib/_internal/pub_generated/lib/src/command/version.dart deleted file mode 100644 index de40572a3a4..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command/version.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command.version; - -import '../command.dart'; -import '../log.dart' as log; -import '../sdk.dart' as sdk; - -/// Handles the `version` pub command. -class VersionCommand extends PubCommand { - String get name => "version"; - String get description => "Print pub version."; - String get invocation => "pub version"; - - void run() { - log.message("Pub ${sdk.version}"); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/command_runner.dart b/sdk/lib/_internal/pub_generated/lib/src/command_runner.dart deleted file mode 100644 index 6bb615311c0..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/command_runner.dart +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.command_runner; - -import 'dart:async'; -import 'dart:io'; - -import 'package:args/args.dart'; -import 'package:args/command_runner.dart'; -import 'package:http/http.dart' as http; -import 'package:stack_trace/stack_trace.dart'; - -import 'command/build.dart'; -import 'command/cache.dart'; -import 'command/deps.dart'; -import 'command/downgrade.dart'; -import 'command/get.dart'; -import 'command/global.dart'; -import 'command/lish.dart'; -import 'command/list_package_dirs.dart'; -import 'command/run.dart'; -import 'command/serve.dart'; -import 'command/upgrade.dart'; -import 'command/uploader.dart'; -import 'command/version.dart'; -import 'exceptions.dart'; -import 'exit_codes.dart' as exit_codes; -import 'http.dart'; -import 'io.dart'; -import 'log.dart' as log; -import 'sdk.dart' as sdk; -import 'solver/version_solver.dart'; -import 'utils.dart'; - -class PubCommandRunner extends CommandRunner { - String get usageFooter => - "See http://dartlang.org/tools/pub for detailed " "documentation."; - - PubCommandRunner() - : super("pub", "Pub is a package manager for Dart.") { - argParser.addFlag('version', negatable: false, help: 'Print pub version.'); - argParser.addFlag( - 'trace', - help: 'Print debugging information when an error occurs.'); - argParser.addOption( - 'verbosity', - help: 'Control output verbosity.', - allowed: ['normal', 'io', 'solver', 'all'], - allowedHelp: { - 'normal': 'Show errors, warnings, and user messages.', - 'io': 'Also show IO operations.', - 'solver': 'Show steps during version resolution.', - 'all': 'Show all output including internal tracing messages.' - }); - argParser.addFlag( - 'verbose', - abbr: 'v', - negatable: false, - help: 'Shortcut for "--verbosity=all".'); - argParser.addFlag( - 'with-prejudice', - hide: !isAprilFools, - negatable: false, - help: 'Execute commands with prejudice.'); - argParser.addFlag( - 'package-symlinks', - hide: true, - negatable: true, - defaultsTo: true); - - addCommand(new BuildCommand()); - addCommand(new CacheCommand()); - addCommand(new DepsCommand()); - addCommand(new DowngradeCommand()); - addCommand(new GlobalCommand()); - addCommand(new GetCommand()); - addCommand(new ListPackageDirsCommand()); - addCommand(new LishCommand()); - addCommand(new RunCommand()); - addCommand(new ServeCommand()); - addCommand(new UpgradeCommand()); - addCommand(new UploaderCommand()); - addCommand(new VersionCommand()); - } - - Future run(List arguments) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var options; - join0() { - new Future.value(runCommand(options)).then((x0) { - try { - x0; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - catch0(error, s1) { - try { - if (error is UsageException) { - log.error(error.message); - new Future.value(flushThenExit(exit_codes.USAGE)).then((x1) { - try { - x1; - join0(); - } catch (e1, s2) { - completer0.completeError(e1, s2); - } - }, onError: completer0.completeError); - } else { - throw error; - } - } catch (error, s1) { - completer0.completeError(error, s1); - } - } - try { - options = super.parse(arguments); - join0(); - } catch (e2, s3) { - catch0(e2, s3); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - Future runCommand(ArgResults options) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - log.withPrejudice = options['with-prejudice']; - join0() { - join1() { - break0() { - log.fine('Pub ${sdk.version}'); - new Future.value(_validatePlatform()).then((x0) { - try { - x0; - var captureStackChains = - options['trace'] || - options['verbose'] || - options['verbosity'] == 'all'; - join2() { - completer0.complete(); - } - catch0(error, chain) { - try { - log.exception(error, chain); - join3() { - new Future.value( - flushThenExit(_chooseExitCode(error))).then((x1) { - try { - x1; - join2(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (options['trace']) { - log.dumpTranscript(); - join3(); - } else { - join4() { - join3(); - } - if (!isUserFacingException(error)) { - log.error(""" -This is an unexpected error. Please run - - pub --trace ${options.arguments.map(((arg) { - return "'$arg'"; - })).join(' ')} - -and include the results in a bug report on http://dartbug.com/new. -"""); - join4(); - } else { - join4(); - } - } - } catch (error, chain) { - completer0.completeError(error, chain); - } - } - try { - new Future.value(captureErrors((() { - return super.runCommand(options); - }), captureStackChains: captureStackChains)).then((x2) { - try { - x2; - new Future.value( - flushThenExit(exit_codes.SUCCESS)).then((x3) { - try { - x3; - join2(); - } catch (e1, s1) { - catch0(e1, s1); - } - }, onError: catch0); - } catch (e2, s2) { - catch0(e2, s2); - } - }, onError: catch0); - } catch (e3, s3) { - catch0(e3, s3); - } - } catch (e4, s4) { - completer0.completeError(e4, s4); - } - }, onError: completer0.completeError); - } - switch (options['verbosity']) { - case 'normal': - log.verbosity = log.Verbosity.NORMAL; - break0(); - break; - case 'io': - log.verbosity = log.Verbosity.IO; - break0(); - break; - case 'solver': - log.verbosity = log.Verbosity.SOLVER; - break0(); - break; - case 'all': - log.verbosity = log.Verbosity.ALL; - break0(); - break; - default: - join5() { - break0(); - } - if (options['verbose']) { - log.verbosity = log.Verbosity.ALL; - join5(); - } else { - join5(); - } - break; - } - } - if (options['trace']) { - log.recordTranscript(); - join1(); - } else { - join1(); - } - } - if (options['version']) { - log.message('Pub ${sdk.version}'); - completer0.complete(null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - void printUsage() { - log.message(usage); - } - - /// Returns the appropriate exit code for [exception], falling back on 1 if no - /// appropriate exit code could be found. - int _chooseExitCode(exception) { - while (exception is WrappedException) exception = exception.innerError; - - if (exception is HttpException || - exception is http.ClientException || - exception is SocketException || - exception is PubHttpException || - exception is DependencyNotFoundException) { - return exit_codes.UNAVAILABLE; - } else if (exception is FormatException || exception is DataException) { - return exit_codes.DATA; - } else if (exception is UsageException) { - return exit_codes.USAGE; - } else { - return 1; - } - } - - /// Checks that pub is running on a supported platform. - /// - /// If it isn't, it prints an error message and exits. Completes when the - /// validation is done. - Future _validatePlatform() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - new Future.value(runProcess('ver', [])).then((x0) { - try { - var result = x0; - join1() { - completer0.complete(); - } - if (result.stdout.join('\n').contains('XP')) { - log.error('Sorry, but pub is not supported on Windows XP.'); - new Future.value(flushThenExit(exit_codes.USAGE)).then((x1) { - try { - x1; - join1(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } else { - join1(); - } - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } - if (Platform.operatingSystem != 'windows') { - completer0.complete(null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/dart.dart b/sdk/lib/_internal/pub_generated/lib/src/dart.dart deleted file mode 100644 index 2f83268174f..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/dart.dart +++ /dev/null @@ -1,323 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// A library for compiling Dart code and manipulating analyzer parse trees. -library pub.dart; - -import 'dart:async'; -import 'dart:io'; -import 'dart:isolate'; - -import 'package:analyzer/analyzer.dart'; -import 'package:path/path.dart' as path; - -import '../../../../../../pkg/compiler/lib/compiler.dart' as compiler; -import '../../../../../../pkg/compiler/lib/src/filenames.dart' show appendSlash; - -import '../../asset/dart/serialize.dart'; -import 'io.dart'; -import 'log.dart' as log; - -/// Interface to communicate with dart2js. -/// -/// This is basically an amalgamation of dart2js's -/// [compiler.CompilerInputProvider], [compiler.CompilerOutputProvider], and -/// [compiler.DiagnosticHandler] function types so that we can provide them -/// as a single unit. -abstract class CompilerProvider { - /// The URI to the root directory where "dart:" libraries can be found. - /// - /// This is used as the base URL to generate library URLs that are then sent - /// back to [provideInput]. - Uri get libraryRoot; - - /// Given [uri], responds with a future that completes to the contents of - /// the input file at that URI. - /// - /// The future can complete to a string or a list of bytes. - Future /*>*/ provideInput(Uri uri); - - /// Reports a diagnostic message from dart2js to the user. - void handleDiagnostic(Uri uri, int begin, int end, String message, - compiler.Diagnostic kind); - - /// Given a [name] (which will be "" for the entrypoint) and a file extension, - /// returns an [EventSink] that dart2js can write to to emit an output file. - EventSink provideOutput(String name, String extension); -} - -/// Compiles [entrypoint] to JavaScript (or to Dart if [toDart] is true) as -/// well as any ancillary outputs dart2js creates. -/// -/// Uses [provider] to communcate between dart2js and the caller. Returns a -/// future that completes when compilation is done. -/// -/// By default, the package root is assumed to be adjacent to [entrypoint], but -/// if [packageRoot] is passed that will be used instead. -Future compile(String entrypoint, CompilerProvider provider, - {Iterable commandLineOptions, bool checked: false, bool csp: false, - bool minify: true, bool verbose: false, Map environment, - String packageRoot, bool analyzeAll: false, bool preserveUris: false, - bool suppressWarnings: false, bool suppressHints: false, - bool suppressPackageWarnings: true, bool terse: false, - bool includeSourceMapUrls: false, bool toDart: false}) { - return new Future.sync(() { - var options = ['--categories=Client,Server']; - if (checked) options.add('--enable-checked-mode'); - if (csp) options.add('--csp'); - if (minify) options.add('--minify'); - if (verbose) options.add('--verbose'); - if (analyzeAll) options.add('--analyze-all'); - if (preserveUris) options.add('--preserve-uris'); - if (suppressWarnings) options.add('--suppress-warnings'); - if (suppressHints) options.add('--suppress-hints'); - if (!suppressPackageWarnings) options.add('--show-package-warnings'); - if (terse) options.add('--terse'); - if (toDart) options.add('--output-type=dart'); - - var sourceUrl = path.toUri(entrypoint); - options.add("--out=$sourceUrl.js"); - - // Add the source map URLs. - if (includeSourceMapUrls) { - options.add("--source-map=$sourceUrl.js.map"); - } - - if (environment == null) environment = {}; - if (commandLineOptions != null) options.addAll(commandLineOptions); - - if (packageRoot == null) { - packageRoot = path.join(path.dirname(entrypoint), 'packages'); - } - - return compiler.compile( - path.toUri(entrypoint), - provider.libraryRoot, - path.toUri(appendSlash(packageRoot)), - provider.provideInput, - provider.handleDiagnostic, - options, - provider.provideOutput, - environment); - }); -} - -/// Returns whether [dart] looks like an entrypoint file. -bool isEntrypoint(CompilationUnit dart) { - // Allow two or fewer arguments so that entrypoints intended for use with - // [spawnUri] get counted. - // - // TODO(nweiz): this misses the case where a Dart file doesn't contain main(), - // but it parts in another file that does. - return dart.declarations.any((node) { - return node is FunctionDeclaration && - node.name.name == "main" && - node.functionExpression.parameters.parameters.length <= 2; - }); -} - -/// Efficiently parses the import and export directives in [contents]. -/// -/// If [name] is passed, it's used as the filename for error reporting. -List parseImportsAndExports(String contents, {String name}) { - var collector = new _DirectiveCollector(); - parseDirectives(contents, name: name).accept(collector); - return collector.directives; -} - -/// A simple visitor that collects import and export nodes. -class _DirectiveCollector extends GeneralizingAstVisitor { - final directives = []; - - visitUriBasedDirective(UriBasedDirective node) => directives.add(node); -} - -/// Runs [code] in an isolate. -/// -/// [code] should be the contents of a Dart entrypoint. It may contain imports; -/// they will be resolved in the same context as the host isolate. [message] is -/// passed to the [main] method of the code being run; the caller is responsible -/// for using this to establish communication with the isolate. -/// -/// [packageRoot] controls the package root of the isolate. It may be either a -/// [String] or a [Uri]. -/// -/// If [snapshot] is passed, the isolate will be loaded from that path if it -/// exists. Otherwise, a snapshot of the isolate's code will be saved to that -/// path once the isolate is loaded. -Future runInIsolate(String code, message, {packageRoot, String snapshot}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - new Future.value(withTempDir(((dir) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var dartPath = path.join(dir, 'runInIsolate.dart'); - writeTextFile(dartPath, code, dontLogContents: true); - var port = new ReceivePort(); - join0(x0) { - new Future.value(Isolate.spawn(_isolateBuffer, { - 'replyTo': port.sendPort, - 'uri': path.toUri(dartPath).toString(), - 'packageRoot': x0, - 'message': message - })).then((x1) { - try { - x1; - new Future.value(port.first).then((x2) { - try { - var response = x2; - join1() { - join2() { - ensureDir(path.dirname(snapshot)); - var snapshotArgs = []; - join3() { - snapshotArgs.addAll( - ['--snapshot=${snapshot}', dartPath]); - new Future.value( - runProcess(Platform.executable, snapshotArgs)).then((x3) { - try { - var result = x3; - join4() { - log.warning( - "Failed to compile a snapshot to " "${path.relative(snapshot)}:\n" + - result.stderr.join("\n")); - completer0.complete(); - } - if (result.success) { - completer0.complete(null); - } else { - join4(); - } - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (packageRoot != null) { - snapshotArgs.add('--package-root=${packageRoot}'); - join3(); - } else { - join3(); - } - } - if (snapshot == null) { - completer0.complete(null); - } else { - join2(); - } - } - if (response['type'] == 'error') { - throw new CrossIsolateException.deserialize( - response['error']); - join1(); - } else { - join1(); - } - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }, onError: completer0.completeError); - } - if (packageRoot == null) { - join0(null); - } else { - join0(packageRoot.toString()); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }))).then((x0) { - try { - x0; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (snapshot != null && fileExists(snapshot)) { - log.fine("Spawning isolate from ${snapshot}."); - join1() { - join2() { - join0(); - } - catch0(error, s1) { - try { - if (error is IsolateSpawnException) { - log.fine( - "Couldn't load existing snapshot ${snapshot}:\n${error}"); - join2(); - } else { - throw error; - } - } catch (error, s1) { - completer0.completeError(error, s1); - } - } - try { - new Future.value( - Isolate.spawnUri( - path.toUri(snapshot), - [], - message, - packageRoot: packageRoot)).then((x1) { - try { - x1; - completer0.complete(null); - } catch (e1, s2) { - catch0(e1, s2); - } - }, onError: catch0); - } catch (e2, s3) { - catch0(e2, s3); - } - } - if (packageRoot != null) { - packageRoot = packageRoot.toString(); - join1(); - } else { - join1(); - } - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; -} - -// TODO(nweiz): remove this when issue 12617 is fixed. -/// A function used as a buffer between the host isolate and [spawnUri]. -/// -/// [spawnUri] synchronously loads the file and its imports, which can deadlock -/// the host isolate if there's an HTTP import pointing at a server in the host. -/// Adding an additional isolate in the middle works around this. -void _isolateBuffer(message) { - var replyTo = message['replyTo']; - var packageRoot = message['packageRoot']; - if (packageRoot != null) packageRoot = Uri.parse(packageRoot); - Isolate.spawnUri( - Uri.parse(message['uri']), - [], - message['message'], - packageRoot: packageRoot).then((_) => replyTo.send({ - 'type': 'success' - })).catchError((e, stack) { - replyTo.send({ - 'type': 'error', - 'error': CrossIsolateException.serialize(e, stack) - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/entrypoint.dart b/sdk/lib/_internal/pub_generated/lib/src/entrypoint.dart deleted file mode 100644 index 2ae51dc7b12..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/entrypoint.dart +++ /dev/null @@ -1,951 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.entrypoint; - -import 'dart:async'; - -import 'package:path/path.dart' as path; -import 'package:barback/barback.dart'; - -import 'barback/asset_environment.dart'; -import 'io.dart'; -import 'lock_file.dart'; -import 'log.dart' as log; -import 'package.dart'; -import 'package_graph.dart'; -import 'sdk.dart' as sdk; -import 'solver/version_solver.dart'; -import 'source/cached.dart'; -import 'system_cache.dart'; -import 'utils.dart'; - -/// The context surrounding the root package pub is operating on. -/// -/// Pub operates over a directed graph of dependencies that starts at a root -/// "entrypoint" package. This is typically the package where the current -/// working directory is located. An entrypoint knows the [root] package it is -/// associated with and is responsible for managing the "packages" directory -/// for it. -/// -/// That directory contains symlinks to all packages used by an app. These links -/// point either to the [SystemCache] or to some other location on the local -/// filesystem. -/// -/// While entrypoints are typically applications, a pure library package may end -/// up being used as an entrypoint. Also, a single package may be used as an -/// entrypoint in one context but not in another. For example, a package that -/// contains a reusable library may not be the entrypoint when used by an app, -/// but may be the entrypoint when you're running its tests. -class Entrypoint { - /// The root package this entrypoint is associated with. - final Package root; - - /// The system-wide cache which caches packages that need to be fetched over - /// the network. - final SystemCache cache; - - /// Whether to create and symlink a "packages" directory containing links to - /// the installed packages. - final bool _packageSymlinks; - - /// The lockfile for the entrypoint. - /// - /// If not provided to the entrypoint, it will be laoded lazily from disc. - LockFile _lockFile; - - /// The graph of all packages reachable from the entrypoint. - PackageGraph _packageGraph; - - /// Loads the entrypoint from a package at [rootDir]. - /// - /// If [packageSymlinks] is `true`, this will create a "packages" directory - /// with symlinks to the installed packages. This directory will be symlinked - /// into any directory that might contain an entrypoint. - Entrypoint(String rootDir, SystemCache cache, {bool packageSymlinks: true}) - : root = new Package.load(null, rootDir, cache.sources), - cache = cache, - _packageSymlinks = packageSymlinks; - - /// Creates an entrypoint given package and lockfile objects. - Entrypoint.inMemory(this.root, this._lockFile, this.cache) - : _packageSymlinks = false; - - /// The path to the entrypoint's "packages" directory. - String get packagesDir => root.path('packages'); - - /// `true` if the entrypoint package currently has a lock file. - bool get lockFileExists => _lockFile != null || entryExists(lockFilePath); - - LockFile get lockFile { - if (_lockFile != null) return _lockFile; - - if (!lockFileExists) { - _lockFile = new LockFile.empty(); - } else { - _lockFile = new LockFile.load(lockFilePath, cache.sources); - } - - return _lockFile; - } - - /// The path to the entrypoint package's pubspec. - String get pubspecPath => root.path('pubspec.yaml'); - - /// The path to the entrypoint package's lockfile. - String get lockFilePath => root.path('pubspec.lock'); - - /// Gets all dependencies of the [root] package. - /// - /// Performs version resolution according to [SolveType]. - /// - /// [useLatest], if provided, defines a list of packages that will be - /// unlocked and forced to their latest versions. If [upgradeAll] is - /// true, the previous lockfile is ignored and all packages are re-resolved - /// from scratch. Otherwise, it will attempt to preserve the versions of all - /// previously locked packages. - /// - /// Shows a report of the changes made relative to the previous lockfile. If - /// this is an upgrade or downgrade, all transitive dependencies are shown in - /// the report. Otherwise, only dependencies that were changed are shown. If - /// [dryRun] is `true`, no physical changes are made. - Future acquireDependencies(SolveType type, {List useLatest, - bool dryRun: false}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value( - resolveVersions( - type, - cache.sources, - root, - lockFile: lockFile, - useLatest: useLatest)).then((x0) { - try { - var result = x0; - join0() { - result.showReport(type); - join1() { - join2() { - new Future.value( - Future.wait(result.packages.map(_get))).then((x1) { - try { - var ids = x1; - _saveLockFile(ids); - join3() { - _linkOrDeleteSecondaryPackageDirs(); - result.summarizeChanges(type, dryRun: dryRun); - new Future.value(loadPackageGraph(result)).then((x2) { - try { - var packageGraph = x2; - packageGraph.loadTransformerCache().clearIfOutdated( - result.changedPackages); - join4() { - completer0.complete(); - } - catch0(error, stackTrace) { - try { - log.exception(error, stackTrace); - join4(); - } catch (error, stackTrace) { - completer0.completeError(error, stackTrace); - } - } - try { - new Future.value( - precompileDependencies(changed: result.changedPackages)).then((x3) { - try { - x3; - new Future.value( - precompileExecutables(changed: result.changedPackages)).then((x4) { - try { - x4; - join4(); - } catch (e0, s0) { - catch0(e0, s0); - } - }, onError: catch0); - } catch (e1, s1) { - catch0(e1, s1); - } - }, onError: catch0); - } catch (e2, s2) { - catch0(e2, s2); - } - } catch (e3, s3) { - completer0.completeError(e3, s3); - } - }, onError: completer0.completeError); - } - if (_packageSymlinks) { - _linkSelf(); - join3(); - } else { - join3(); - } - } catch (e4, s4) { - completer0.completeError(e4, s4); - } - }, onError: completer0.completeError); - } - if (_packageSymlinks) { - cleanDir(packagesDir); - join2(); - } else { - deleteEntry(packagesDir); - join2(); - } - } - if (dryRun) { - result.summarizeChanges(type, dryRun: dryRun); - completer0.complete(null); - } else { - join1(); - } - } - if (!result.succeeded) { - throw result.error; - join0(); - } else { - join0(); - } - } catch (e5, s5) { - completer0.completeError(e5, s5); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Precompile any transformed dependencies of the entrypoint. - /// - /// If [changed] is passed, only dependencies whose contents might be changed - /// if one of the given packages changes will be recompiled. - Future precompileDependencies({Iterable changed}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - new Future.value(loadPackageGraph()).then((x0) { - try { - var graph = x0; - var depsDir = path.join('.pub', 'deps', 'debug'); - var dependenciesToPrecompile = - graph.packages.values.where(((package) { - if (package.pubspec.transformers.isEmpty) return false; - if (graph.isPackageMutable(package.name)) return false; - if (!dirExists(path.join(depsDir, package.name))) return true; - if (changed == null) return true; - return overlaps( - graph.transitiveDependencies( - package.name).map((package) => package.name).toSet(), - changed); - })).map(((package) { - return package.name; - })).toSet(); - join1() { - join2() { - join3() { - completer0.complete(); - } - catch0(_, s0) { - try { - var it0 = dependenciesToPrecompile.iterator; - break0() { - completer0.completeError(_, s0); - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var package = it0.current; - deleteEntry(path.join(depsDir, package)); - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (_, s0) { - completer0.completeError(_, s0); - } - } - try { - new Future.value( - log.progress("Precompiling dependencies", (() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var packagesToLoad = unionAll( - dependenciesToPrecompile.map(graph.transitiveDependencies)).map(((package) { - return package.name; - })).toSet(); - new Future.value( - AssetEnvironment.create( - this, - BarbackMode.DEBUG, - packages: packagesToLoad, - useDart2JS: false)).then((x0) { - try { - var environment = x0; - environment.barback.errors.listen(((_) { - })); - new Future.value( - environment.barback.getAllAssets()).then((x1) { - try { - var assets = x1; - new Future.value( - waitAndPrintErrors(assets.map(((asset) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - var destPath = - path.join(depsDir, asset.id.package, path.fromUri(asset.id.path)); - ensureDir(path.dirname(destPath)); - new Future.value( - createFileFromStream(asset.read(), destPath)).then((x0) { - try { - x0; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (!dependenciesToPrecompile.contains( - asset.id.package)) { - completer0.complete(null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x2) { - try { - x2; - log.message( - "Precompiled " + - toSentence(ordered(dependenciesToPrecompile).map(log.bold)) + - "."); - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }))).then((x1) { - try { - x1; - join3(); - } catch (e0, s1) { - catch0(e0, s1); - } - }, onError: catch0); - } catch (e1, s2) { - catch0(e1, s2); - } - } - if (dependenciesToPrecompile.isEmpty) { - completer0.complete(null); - } else { - join2(); - } - } - if (dirExists(depsDir)) { - var it1 = dependenciesToPrecompile.iterator; - break1() { - var it2 = listDir(depsDir).iterator; - break2() { - join1(); - } - var trampoline2; - continue2() { - trampoline2 = null; - if (it2.moveNext()) { - var subdir = it2.current; - var package = graph.packages[path.basename(subdir)]; - join4() { - trampoline2 = continue2; - do trampoline2(); while (trampoline2 != null); - } - if (package == null || - package.pubspec.transformers.isEmpty || - graph.isPackageMutable(package.name)) { - deleteEntry(subdir); - join4(); - } else { - join4(); - } - } else { - break2(); - } - } - trampoline2 = continue2; - do trampoline2(); while (trampoline2 != null); - } - var trampoline1; - continue1() { - trampoline1 = null; - if (it1.moveNext()) { - var package = it1.current; - deleteEntry(path.join(depsDir, package)); - trampoline1 = continue1; - do trampoline1(); while (trampoline1 != null); - } else { - break1(); - } - } - trampoline1 = continue1; - do trampoline1(); while (trampoline1 != null); - } else { - join1(); - } - } catch (e2, s3) { - completer0.completeError(e2, s3); - } - }, onError: completer0.completeError); - } - if (changed != null) { - changed = changed.toSet(); - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Precompiles all executables from dependencies that don't transitively - /// depend on [this] or on a path dependency. - Future precompileExecutables({Iterable changed}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - var binDir = path.join('.pub', 'bin'); - var sdkVersionPath = path.join(binDir, 'sdk-version'); - var sdkMatches = - fileExists(sdkVersionPath) && - readTextFile(sdkVersionPath) == "${sdk.version}\n"; - join1() { - new Future.value(loadPackageGraph()).then((x0) { - try { - var graph = x0; - var executables = - new Map.fromIterable(root.immediateDependencies, key: ((dep) { - return dep.name; - }), value: ((dep) { - return _executablesForPackage(graph, dep.name, changed); - })); - var it0 = executables.keys.toList().iterator; - break0() { - join2() { - join3() { - new Future.value( - log.progress("Precompiling executables", (() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - ensureDir(binDir); - writeTextFile(sdkVersionPath, "${sdk.version}\n"); - var packagesToLoad = - unionAll(executables.keys.map(graph.transitiveDependencies)).map(((package) { - return package.name; - })).toSet(); - var executableIds = - unionAll(executables.values.map(((ids) { - return ids.toSet(); - }))); - new Future.value( - AssetEnvironment.create( - this, - BarbackMode.RELEASE, - packages: packagesToLoad, - entrypoints: executableIds, - useDart2JS: false)).then((x0) { - try { - var environment = x0; - environment.barback.errors.listen(((error) { - log.error(log.red("Build error:\n$error")); - })); - new Future.value( - waitAndPrintErrors(executables.keys.map(((package) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var dir = path.join(binDir, package); - cleanDir(dir); - new Future.value( - environment.precompileExecutables( - package, - dir, - executableIds: executables[package])).then((x0) { - try { - x0; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x1) { - try { - x1; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }))).then((x1) { - try { - x1; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (executables.isEmpty) { - completer0.complete(null); - } else { - join3(); - } - } - if (!sdkMatches) { - deleteEntry(binDir); - join2(); - } else { - join2(); - } - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var package = it0.current; - join4() { - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - if (executables[package].isEmpty) { - executables.remove(package); - join4(); - } else { - join4(); - } - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } - if (!sdkMatches) { - changed = null; - join1(); - } else { - join1(); - } - } - if (changed != null) { - changed = changed.toSet(); - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Returns the list of all executable assets for [packageName] that should be - /// precompiled. - /// - /// If [changed] isn't `null`, executables for [packageName] will only be - /// compiled if they might depend on a package in [changed]. - List _executablesForPackage(PackageGraph graph, String packageName, - Set changed) { - var package = graph.packages[packageName]; - var binDir = package.path('bin'); - if (!dirExists(binDir)) return []; - if (graph.isPackageMutable(packageName)) return []; - - var executables = package.executableIds; - - // If we don't know which packages were changed, always precompile the - // executables. - if (changed == null) return executables; - - // If any of the package's dependencies changed, recompile the executables. - if (graph.transitiveDependencies( - packageName).any((package) => changed.contains(package.name))) { - return executables; - } - - // If any executables doesn't exist, precompile them regardless of what - // changed. Since we delete the bin directory before recompiling, we need to - // recompile all executables. - var executablesExist = executables.every( - (executable) => - fileExists( - path.join( - '.pub', - 'bin', - packageName, - "${path.url.basename(executable.path)}.snapshot"))); - if (!executablesExist) return executables; - - // Otherwise, we don't need to recompile. - return []; - } - - /// Makes sure the package at [id] is locally available. - /// - /// This automatically downloads the package to the system-wide cache as well - /// if it requires network access to retrieve (specifically, if the package's - /// source is a [CachedSource]). - Future _get(PackageId id) { - if (id.isRoot) return new Future.value(id); - - var source = cache.sources[id.source]; - return new Future.sync(() { - if (!_packageSymlinks) { - if (source is! CachedSource) return null; - return source.downloadToSystemCache(id); - } - - var packageDir = path.join(packagesDir, id.name); - if (entryExists(packageDir)) deleteEntry(packageDir); - return source.get(id, packageDir); - }).then((_) => source.resolveId(id)); - } - - /// Determines whether or not the lockfile is out of date with respect to the - /// pubspec. - /// - /// This will be `false` if there is no lockfile at all, or if the pubspec - /// contains dependencies that are not in the lockfile or that don't match - /// what's in there. - bool _isLockFileUpToDate(LockFile lockFile) { - /// If this is an entrypoint for an in-memory package, trust the in-memory - /// lockfile provided for it. - if (root.dir == null) return true; - - return root.immediateDependencies.every((package) { - var locked = lockFile.packages[package.name]; - if (locked == null) return false; - - if (package.source != locked.source) return false; - if (!package.constraint.allows(locked.version)) return false; - - var source = cache.sources[package.source]; - if (source == null) return false; - - return source.descriptionsEqual(package.description, locked.description); - }); - } - - /// Determines whether all of the packages in the lockfile are already - /// installed and available. - /// - /// Note: this assumes [isLockFileUpToDate] has already been called and - /// returned `true`. - Future _arePackagesAvailable(LockFile lockFile) { - return Future.wait(lockFile.packages.values.map((package) { - var source = cache.sources[package.source]; - - // This should only be called after [_isLockFileUpToDate] has returned - // `true`, which ensures all of the sources in the lock file are valid. - assert(source != null); - - // We only care about cached sources. Uncached sources aren't "installed". - // If one of those is missing, we want to show the user the file not - // found error later since installing won't accomplish anything. - if (source is! CachedSource) return new Future.value(true); - - // Get the directory. - return source.getDirectory(package).then((dir) { - // See if the directory is there and looks like a package. - return dirExists(dir) || fileExists(path.join(dir, "pubspec.yaml")); - }); - })).then((results) { - // Make sure they are all true. - return results.every((result) => result); - }); - } - - /// Gets dependencies if the lockfile is out of date with respect to the - /// pubspec. - Future ensureLockFileIsUpToDate() { - return new Future.sync(() { - // If we don't have a current lock file, we definitely need to install. - if (!_isLockFileUpToDate(lockFile)) { - if (lockFileExists) { - log.message( - "Your pubspec has changed, so we need to update your lockfile:"); - } else { - log.message( - "You don't have a lockfile, so we need to generate that:"); - } - - return false; - } - - // If we do have a lock file, we still need to make sure the packages - // are actually installed. The user may have just gotten a package that - // includes a lockfile. - return _arePackagesAvailable(lockFile).then((available) { - if (!available) { - log.message( - "You are missing some dependencies, so we need to install them " "first:"); - } - - return available; - }); - }).then((upToDate) { - if (upToDate) return null; - return acquireDependencies(SolveType.GET); - }); - } - - /// Loads the package graph for the application and all of its transitive - /// dependencies. - /// - /// If [result] is passed, this loads the graph from it without re-parsing the - /// lockfile or any pubspecs. Otherwise, before loading, this makes sure the - /// lockfile and dependencies are installed and up to date. - Future loadPackageGraph([SolveResult result]) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - new Future.value(log.progress("Loading package graph", (() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - new Future.value(ensureLockFileIsUpToDate()).then((x0) { - try { - x0; - new Future.value( - Future.wait(lockFile.packages.values.map(((id) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var source = cache.sources[id.source]; - new Future.value( - source.getDirectory(id)).then((x0) { - try { - var dir = x0; - completer0.complete( - new Package.load(id.name, dir, cache.sources)); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x1) { - try { - var packages = x1; - var packageMap = - new Map.fromIterable(packages, key: ((p) { - return p.name; - })); - packageMap[root.name] = root; - completer0.complete( - new PackageGraph(this, lockFile, packageMap)); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } - if (result != null) { - new Future.value(Future.wait(result.packages.map(((id) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value( - cache.sources[id.source].getDirectory(id)).then((x0) { - try { - var dir = x0; - completer0.complete( - new Package(result.pubspecs[id.name], dir)); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - })))).then((x2) { - try { - var packages = x2; - completer0.complete( - new PackageGraph( - this, - new LockFile(result.packages), - new Map.fromIterable(packages, key: ((package) { - return package.name; - })))); - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }, onError: completer0.completeError); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }), fine: true)).then((x0) { - try { - var graph = x0; - _packageGraph = graph; - completer0.complete(graph); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (_packageGraph != null) { - completer0.complete(_packageGraph); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Saves a list of concrete package versions to the `pubspec.lock` file. - void _saveLockFile(List packageIds) { - _lockFile = new LockFile(packageIds); - var lockFilePath = root.path('pubspec.lock'); - writeTextFile(lockFilePath, _lockFile.serialize(root.dir, cache.sources)); - } - - /// Creates a self-referential symlink in the `packages` directory that allows - /// a package to import its own files using `package:`. - void _linkSelf() { - var linkPath = path.join(packagesDir, root.name); - // Create the symlink if it doesn't exist. - if (entryExists(linkPath)) return; - ensureDir(packagesDir); - createPackageSymlink( - root.name, - root.dir, - linkPath, - isSelfLink: true, - relative: true); - } - - /// If [packageSymlinks] is true, add "packages" directories to the whitelist - /// of directories that may contain Dart entrypoints. - /// - /// Otherwise, delete any "packages" directories in the whitelist of - /// directories that may contain Dart entrypoints. - void _linkOrDeleteSecondaryPackageDirs() { - // Only the main "bin" directory gets a "packages" directory, not its - // subdirectories. - var binDir = root.path('bin'); - if (dirExists(binDir)) _linkOrDeleteSecondaryPackageDir(binDir); - - // The others get "packages" directories in subdirectories too. - for (var dir in ['benchmark', 'example', 'test', 'tool', 'web']) { - _linkOrDeleteSecondaryPackageDirsRecursively(root.path(dir)); - } - } - - /// If [packageSymlinks] is true, creates a symlink to the "packages" - /// directory in [dir] and all its subdirectories. - /// - /// Otherwise, deletes any "packages" directories in [dir] and all its - /// subdirectories. - void _linkOrDeleteSecondaryPackageDirsRecursively(String dir) { - if (!dirExists(dir)) return; - _linkOrDeleteSecondaryPackageDir(dir); - _listDirWithoutPackages( - dir).where(dirExists).forEach(_linkOrDeleteSecondaryPackageDir); - } - - // TODO(nweiz): roll this into [listDir] in io.dart once issue 4775 is fixed. - /// Recursively lists the contents of [dir], excluding hidden `.DS_Store` - /// files and `package` files. - List _listDirWithoutPackages(dir) { - return flatten(listDir(dir).map((file) { - if (path.basename(file) == 'packages') return []; - if (!dirExists(file)) return []; - var fileAndSubfiles = [file]; - fileAndSubfiles.addAll(_listDirWithoutPackages(file)); - return fileAndSubfiles; - })); - } - - /// If [packageSymlinks] is true, creates a symlink to the "packages" - /// directory in [dir]. - /// - /// Otherwise, deletes a "packages" directories in [dir] if one exists. - void _linkOrDeleteSecondaryPackageDir(String dir) { - var symlink = path.join(dir, 'packages'); - if (entryExists(symlink)) deleteEntry(symlink); - if (_packageSymlinks) createSymlink(packagesDir, symlink, relative: true); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/error_group.dart b/sdk/lib/_internal/pub_generated/lib/src/error_group.dart deleted file mode 100644 index 7efebf3cd6b..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/error_group.dart +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.error_group; - -import 'dart:async'; - -/// An [ErrorGroup] entangles the errors of multiple [Future]s and [Stream]s -/// with one another. -/// -/// This allows APIs to expose multiple [Future]s and [Stream]s that have -/// identical error conditions without forcing API consumers to attach error -/// handling to objects they don't care about. -/// -/// To use an [ErrorGroup], register [Future]s and [Stream]s with it using -/// [registerFuture] and [registerStream]. These methods return wrapped versions -/// of the [Future]s and [Stream]s, which should then be used in place of the -/// originals. For example: -/// -/// var errorGroup = new ErrorGroup(); -/// future = errorGroup.registerFuture(future); -/// stream = errorGroup.registerStream(stream); -/// -/// An [ErrorGroup] has two major effects on its wrapped members: -/// -/// * An error in any member of the group will be propagated to every member -/// that hasn't already completed. If those members later complete, their -/// values will be ignored. -/// * If any member of this group has a listener, errors on members without -/// listeners won't get passed to the top-level error handler. -class ErrorGroup { - /// The [Future]s that are members of [this]. - final _futures = <_ErrorGroupFuture>[]; - - /// The [Stream]s that are members of [this]. - final _streams = <_ErrorGroupStream>[]; - - /// Whether [this] has completed, either successfully or with an error. - var _isDone = false; - - /// The [Completer] for [done]. - final _doneCompleter = new Completer(); - - /// The underlying [Future] for [done]. - /// - /// We need to be able to access it internally as an [_ErrorGroupFuture] so - /// we can check if it has listeners and signal errors on it. - _ErrorGroupFuture _done; - - /// Returns a [Future] that completes successully when all members of [this] - /// are complete, or with an error if any member receives an error. - /// - /// This [Future] is effectively in the group in that an error on it won't be - /// passed to the top-level error handler unless no members of the group have - /// listeners attached. - Future get done => _done; - - /// Creates a new group with no members. - ErrorGroup() { - this._done = new _ErrorGroupFuture(this, _doneCompleter.future); - } - - /// Registers a [Future] as a member of [this]. - /// - /// Returns a wrapped version of [future] that should be used in its place. - /// - /// If all members of [this] have already completed successfully or with an - /// error, it's a [StateError] to try to register a new [Future]. - Future registerFuture(Future future) { - if (_isDone) { - throw new StateError( - "Can't register new members on a complete " "ErrorGroup."); - } - - var wrapped = new _ErrorGroupFuture(this, future); - _futures.add(wrapped); - return wrapped; - } - - /// Registers a [Stream] as a member of [this]. - /// - /// Returns a wrapped version of [stream] that should be used in its place. - /// The returned [Stream] will be multi-subscription if and only if [stream] - /// is. - /// - /// Since all errors in a group are passed to all members, the returned - /// [Stream] will automatically unsubscribe all its listeners when it - /// encounters an error. - /// - /// If all members of [this] have already completed successfully or with an - /// error, it's a [StateError] to try to register a new [Stream]. - Stream registerStream(Stream stream) { - if (_isDone) { - throw new StateError( - "Can't register new members on a complete " "ErrorGroup."); - } - - var wrapped = new _ErrorGroupStream(this, stream); - _streams.add(wrapped); - return wrapped; - } - - /// Sends [error] to all members of [this]. - /// - /// Like errors that come from members, this will only be passed to the - /// top-level error handler if no members have listeners. - /// - /// If all members of [this] have already completed successfully or with an - /// error, it's a [StateError] to try to signal an error. - void signalError(var error, [StackTrace stackTrace]) { - if (_isDone) { - throw new StateError("Can't signal errors on a complete ErrorGroup."); - } - - _signalError(error, stackTrace); - } - - /// Signal an error internally. - /// - /// This is just like [signalError], but instead of throwing an error if - /// [this] is complete, it just does nothing. - void _signalError(var error, [StackTrace stackTrace]) { - if (_isDone) return; - - var caught = false; - for (var future in _futures) { - if (future._isDone || future._hasListeners) caught = true; - future._signalError(error, stackTrace); - } - - for (var stream in _streams) { - if (stream._isDone || stream._hasListeners) caught = true; - stream._signalError(error, stackTrace); - } - - _isDone = true; - _done._signalError(error, stackTrace); - if (!caught && !_done._hasListeners) scheduleMicrotask(() { - throw error; - }); - } - - /// Notifies [this] that one of its member [Future]s is complete. - void _signalFutureComplete(_ErrorGroupFuture future) { - if (_isDone) return; - - _isDone = _futures.every((future) => future._isDone) && - _streams.every((stream) => stream._isDone); - if (_isDone) _doneCompleter.complete(); - } - - /// Notifies [this] that one of its member [Stream]s is complete. - void _signalStreamComplete(_ErrorGroupStream stream) { - if (_isDone) return; - - _isDone = _futures.every((future) => future._isDone) && - _streams.every((stream) => stream._isDone); - if (_isDone) _doneCompleter.complete(); - } -} - -/// A [Future] wrapper that keeps track of whether it's been completed and -/// whether it has any listeners. -/// -/// It also notifies its parent [ErrorGroup] when it completes successfully or -/// receives an error. -class _ErrorGroupFuture implements Future { - /// The parent [ErrorGroup]. - final ErrorGroup _group; - - /// Whether [this] has completed, either successfully or with an error. - var _isDone = false; - - /// The underlying [Completer] for [this]. - final _completer = new Completer(); - - /// Whether [this] has any listeners. - bool _hasListeners = false; - - /// Creates a new [_ErrorGroupFuture] that's a child of [_group] and wraps - /// [inner]. - _ErrorGroupFuture(this._group, Future inner) { - inner.then((value) { - if (!_isDone) _completer.complete(value); - _isDone = true; - _group._signalFutureComplete(this); - }).catchError(_group._signalError); - - // Make sure _completer.future doesn't automatically send errors to the - // top-level. - _completer.future.catchError((_) {}); - } - - Future then(onValue(value), {Function onError}) { - _hasListeners = true; - return _completer.future.then(onValue, onError: onError); - } - - Future catchError(Function onError, {bool test(Object error)}) { - _hasListeners = true; - return _completer.future.catchError(onError, test: test); - } - - Future whenComplete(void action()) { - _hasListeners = true; - return _completer.future.whenComplete(action); - } - - Future timeout(Duration timeLimit, {void onTimeout()}) { - _hasListeners = true; - return _completer.future.timeout(timeLimit, onTimeout: onTimeout); - } - - Stream asStream() { - _hasListeners = true; - return _completer.future.asStream(); - } - - /// Signal that an error from [_group] should be propagated through [this], - /// unless it's already complete. - void _signalError(var error, [StackTrace stackTrace]) { - if (!_isDone) _completer.completeError(error, stackTrace); - _isDone = true; - } -} - -// TODO(nweiz): currently streams never top-level unhandled errors (issue 7843). -// When this is fixed, this class will need to prevent such errors from being -// top-leveled. -/// A [Stream] wrapper that keeps track of whether it's been completed and -/// whether it has any listeners. -/// -/// It also notifies its parent [ErrorGroup] when it completes successfully or -/// receives an error. -class _ErrorGroupStream extends Stream { - /// The parent [ErrorGroup]. - final ErrorGroup _group; - - /// Whether [this] has completed, either successfully or with an error. - var _isDone = false; - - /// The underlying [StreamController] for [this]. - final StreamController _controller; - - /// The controller's [Stream]. - /// - /// May be different than `_controller.stream` if the wrapped stream is a - /// broadcasting stream. - Stream _stream; - - /// The [StreamSubscription] that connects the wrapped [Stream] to - /// [_controller]. - StreamSubscription _subscription; - - /// Whether [this] has any listeners. - bool get _hasListeners => _controller.hasListener; - - /// Creates a new [_ErrorGroupFuture] that's a child of [_group] and wraps - /// [inner]. - _ErrorGroupStream(this._group, Stream inner) - : _controller = new StreamController(sync: true) { - // Use old-style asBroadcastStream behavior - cancel source _subscription - // the first time the stream has no listeners. - _stream = inner.isBroadcast ? - _controller.stream.asBroadcastStream(onCancel: (sub) => sub.cancel()) : - _controller.stream; - _subscription = inner.listen((v) { - _controller.add(v); - }, onError: (e, [stackTrace]) { - _group._signalError(e, stackTrace); - }, onDone: () { - _isDone = true; - _group._signalStreamComplete(this); - _controller.close(); - }); - } - - StreamSubscription listen(void onData(value), {Function onError, void - onDone(), bool cancelOnError}) { - return _stream.listen( - onData, - onError: onError, - onDone: onDone, - cancelOnError: true); - } - - /// Signal that an error from [_group] should be propagated through [this], - /// unless it's already complete. - void _signalError(var e, [StackTrace stackTrace]) { - if (_isDone) return; - _subscription.cancel(); - // Call these asynchronously to work around issue 7913. - new Future.value().then((_) { - _controller.addError(e, stackTrace); - _controller.close(); - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/exceptions.dart b/sdk/lib/_internal/pub_generated/lib/src/exceptions.dart deleted file mode 100644 index 7d4f5a39b92..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/exceptions.dart +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.exceptions; - -import 'dart:io'; -import 'dart:isolate'; - -import "package:analyzer/analyzer.dart"; -import 'package:args/command_runner.dart'; -import "package:http/http.dart" as http; -import "package:stack_trace/stack_trace.dart"; -import "package:yaml/yaml.dart"; - -import '../../asset/dart/serialize.dart'; - -/// An exception class for exceptions that are intended to be seen by the user. -/// -/// These exceptions won't have any debugging information printed when they're -/// thrown. -class ApplicationException implements Exception { - final String message; - - ApplicationException(this.message); - - String toString() => message; -} - -/// An exception class for exceptions that are intended to be seen by the user -/// and are associated with a problem in a file at some path. -class FileException implements ApplicationException { - final String message; - - /// The path to the file that was missing or erroneous. - final String path; - - FileException(this.message, this.path); - - String toString() => message; -} - -/// A class for exceptions that wrap other exceptions. -class WrappedException extends ApplicationException { - /// The underlying exception that [this] is wrapping, if any. - final innerError; - - /// The stack chain for [innerError] if it exists. - final Chain innerChain; - - WrappedException(String message, this.innerError, [StackTrace innerTrace]) - : innerChain = innerTrace == null ? null : new Chain.forTrace(innerTrace), - super(message); -} - -/// A class for exceptions that shouldn't be printed at the top level. -/// -/// This is usually used when an exception has already been printed using -/// [log.exception]. -class SilentException extends WrappedException { - SilentException(innerError, [StackTrace innerTrace]) - : super(innerError.toString(), innerError, innerTrace); -} - -/// A class for errors in a command's input data. -/// -/// This corresponds to the [exit_codes.DATA] exit code. -class DataException extends ApplicationException { - DataException(String message) - : super(message); -} - -/// An class for exceptions where a package could not be found in a [Source]. -/// -/// The source is responsible for wrapping its internal exceptions in this so -/// that other code in pub can use this to show a more detailed explanation of -/// why the package was being requested. -class PackageNotFoundException extends WrappedException { - PackageNotFoundException(String message, [innerError, StackTrace innerTrace]) - : super(message, innerError, innerTrace); -} - -/// All the names of user-facing exceptions. -final _userFacingExceptions = new Set.from( - ['ApplicationException', 'GitException', // This refers to http.ClientException. - 'ClientException', - // Errors coming from the Dart analyzer are probably caused by syntax errors - // in user code, so they're user-facing. - 'AnalyzerError', - 'AnalyzerErrorGroup', - // An error spawning an isolate probably indicates a transformer with an - // invalid import. - 'IsolateSpawnException', // IOException and subclasses. - 'CertificateException', - 'FileSystemException', - 'HandshakeException', - 'HttpException', - 'IOException', - 'ProcessException', - 'RedirectException', - 'SignalException', - 'SocketException', - 'StdoutException', - 'TlsException', - 'WebSocketException']); - -/// Returns whether [error] is a user-facing error object. -/// -/// This includes both [ApplicationException] and any dart:io errors. -bool isUserFacingException(error) { - if (error is CrossIsolateException) { - return _userFacingExceptions.contains(error.type); - } - - // TODO(nweiz): unify this list with _userFacingExceptions when issue 5897 is - // fixed. - return error is ApplicationException || - error is AnalyzerError || - error is AnalyzerErrorGroup || - error is IsolateSpawnException || - error is IOException || - error is http.ClientException || - error is YamlException || - error is UsageException; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/executable.dart b/sdk/lib/_internal/pub_generated/lib/src/executable.dart deleted file mode 100644 index 621557232c0..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/executable.dart +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.executable; - -import 'dart:async'; -import 'dart:io'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; -import 'package:stack_trace/stack_trace.dart'; - -import 'barback/asset_environment.dart'; -import 'entrypoint.dart'; -import 'exit_codes.dart' as exit_codes; -import 'io.dart'; -import 'log.dart' as log; -import 'utils.dart'; - -/// Runs [executable] from [package] reachable from [entrypoint]. -/// -/// The executable string is a relative Dart file path using native path -/// separators with or without a trailing ".dart" extension. It is contained -/// within [package], which should either be the entrypoint package or an -/// immediate dependency of it. -/// -/// Arguments from [args] will be passed to the spawned Dart application. -/// -/// If [mode] is passed, it's used as the barback mode; it defaults to -/// [BarbackMode.RELEASE]. -/// -/// Returns the exit code of the spawned app. -Future runExecutable(Entrypoint entrypoint, String package, - String executable, Iterable args, {bool isGlobal: false, - BarbackMode mode}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - join1() { - join2() { - join3() { - var localSnapshotPath = - p.join(".pub", "bin", package, "${executable}.dart.snapshot"); - join4() { - var rootDir = "bin"; - var parts = p.split(executable); - join5() { - var assetPath = "${p.url.joinAll(p.split(executable))}.dart"; - var id = new AssetId(package, assetPath); - new Future.value( - AssetEnvironment.create( - entrypoint, - mode, - useDart2JS: false, - entrypoints: [id])).then((x0) { - try { - var environment = x0; - environment.barback.errors.listen(((error) { - log.error(log.red("Build error:\n$error")); - })); - var server; - join6() { - join7() { - var vmArgs = []; - vmArgs.add("--checked"); - var relativePath = - p.url.relative(assetPath, from: p.url.joinAll(p.split(server.rootDirectory))); - vmArgs.add( - server.url.resolve(relativePath).toString()); - vmArgs.addAll(args); - new Future.value( - Process.start(Platform.executable, vmArgs)).then((x1) { - try { - var process = x1; - process.stderr.listen(stderr.add); - process.stdout.listen(stdout.add); - stdin.listen(process.stdin.add); - completer0.complete(process.exitCode); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - catch0(error, stackTrace) { - try { - if (error is AssetNotFoundException) { - var message = - "Could not find ${log.bold(executable + ".dart")}"; - join8() { - log.error("${message}."); - log.fine(new Chain.forTrace(stackTrace)); - completer0.complete(exit_codes.NO_INPUT); - } - if (package != entrypoint.root.name) { - message += - " in package ${log.bold(server.package)}"; - join8(); - } else { - join8(); - } - } else { - throw error; - } - } catch (error, stackTrace) { - completer0.completeError(error, stackTrace); - } - } - try { - new Future.value( - environment.barback.getAssetById(id)).then((x2) { - try { - x2; - join7(); - } catch (e1, s1) { - catch0(e1, s1); - } - }, onError: catch0); - } catch (e2, s2) { - catch0(e2, s2); - } - } - if (package == entrypoint.root.name) { - new Future.value( - environment.serveDirectory(rootDir)).then((x3) { - try { - server = x3; - join6(); - } catch (e3, s3) { - completer0.completeError(e3, s3); - } - }, onError: completer0.completeError); - } else { - new Future.value( - environment.servePackageBinDirectory(package)).then((x4) { - try { - server = x4; - join6(); - } catch (e4, s4) { - completer0.completeError(e4, s4); - } - }, onError: completer0.completeError); - } - } catch (e5, s5) { - completer0.completeError(e5, s5); - } - }, onError: completer0.completeError); - } - if (parts.length > 1) { - assert(!isGlobal && package == entrypoint.root.name); - rootDir = parts.first; - join5(); - } else { - executable = p.join("bin", executable); - join5(); - } - } - if (!isGlobal && - fileExists(localSnapshotPath) && - mode == BarbackMode.RELEASE) { - completer0.complete( - _runCachedExecutable(entrypoint, localSnapshotPath, args)); - } else { - join4(); - } - } - if (p.extension(executable) == ".dart") { - executable = p.withoutExtension(executable); - join3(); - } else { - join3(); - } - } - if (log.verbosity == log.Verbosity.NORMAL) { - log.verbosity = log.Verbosity.WARNING; - join2(); - } else { - join2(); - } - } - if (entrypoint.root.name != package && - !entrypoint.root.immediateDependencies.any(((dep) { - return dep.name == package; - }))) { - new Future.value(entrypoint.loadPackageGraph()).then((x5) { - try { - var graph = x5; - join9() { - join1(); - } - if (graph.packages.containsKey(package)) { - dataError( - 'Package "${package}" is not an immediate dependency.\n' - 'Cannot run executables in transitive dependencies.'); - join9(); - } else { - dataError( - 'Could not find package "${package}". Did you forget to add a ' 'dependency?'); - join9(); - } - } catch (e6, s6) { - completer0.completeError(e6, s6); - } - }, onError: completer0.completeError); - } else { - join1(); - } - } - if (mode == null) { - mode = BarbackMode.RELEASE; - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; -} - -/// Runs the snapshot at [path] with [args] and hooks its stdout, stderr, and -/// sdtin to this process's. -/// -/// If [recompile] is passed, it's called if the snapshot is out-of-date. It's -/// expected to regenerate a snapshot at [path], after which the snapshot will -/// be re-run. It may return a Future. -/// -/// If [checked] is set, runs the snapshot in checked mode. -/// -/// Returns the snapshot's exit code. -/// -/// This doesn't do any validation of the snapshot's SDK version. -Future runSnapshot(String path, Iterable args, {recompile(), - bool checked: false}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var vmArgs = [path]..addAll(args); - join0() { - var stdin1; - var stdin2; - join1() { - runProcess(input) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - new Future.value( - Process.start(Platform.executable, vmArgs)).then((x0) { - try { - var process = x0; - process.stderr.listen(stderr.add); - process.stdout.listen(stdout.add); - input.listen(process.stdin.add); - completer0.complete(process.exitCode); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - new Future.value(runProcess(stdin1)).then((x0) { - try { - var exitCode = x0; - join2() { - new Future.value(recompile()).then((x1) { - try { - x1; - completer0.complete(runProcess(stdin2)); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (recompile == null || exitCode != 255) { - completer0.complete(exitCode); - } else { - join2(); - } - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } - if (recompile == null) { - stdin1 = stdin; - join1(); - } else { - var pair = tee(stdin); - stdin1 = pair.first; - stdin2 = pair.last; - join1(); - } - } - if (checked) { - vmArgs.insert(0, "--checked"); - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; -} - -/// Runs the executable snapshot at [snapshotPath]. -Future _runCachedExecutable(Entrypoint entrypoint, String snapshotPath, - List args) { - return runSnapshot(snapshotPath, args, checked: true, recompile: () { - log.fine("Precompiled executable is out of date."); - return entrypoint.precompileExecutables(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/exit_codes.dart b/sdk/lib/_internal/pub_generated/lib/src/exit_codes.dart deleted file mode 100644 index ebe8e8deab8..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/exit_codes.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Exit code constants. -/// -/// From [the BSD sysexits manpage][manpage]. Not every constant here is used, -/// even though some of the unused ones may be appropriate for errors -/// encountered by pub. -/// -/// [manpage]: http://www.freebsd.org/cgi/man.cgi?query=sysexits -library pub.exit_codes; - -/// The command completely successfully. -const SUCCESS = 0; - -/// The command was used incorrectly. -const USAGE = 64; - -/// The input data was incorrect. -const DATA = 65; - -/// An input file did not exist or was unreadable. -const NO_INPUT = 66; - -/// The user specified did not exist. -const NO_USER = 67; - -/// The host specified did not exist. -const NO_HOST = 68; - -/// A service is unavailable. -const UNAVAILABLE = 69; - -/// An internal software error has been detected. -const SOFTWARE = 70; - -/// An operating system error has been detected. -const OS = 71; - -/// Some system file did not exist or was unreadable. -const OS_FILE = 72; - -/// A user-specified output file cannot be created. -const CANT_CREATE = 73; - -/// An error occurred while doing I/O on some file. -const IO = 74; - -/// Temporary failure, indicating something that is not really an error. -const TEMP_FAIL = 75; - -/// The remote system returned something invalid during a protocol exchange. -const PROTOCOL = 76; - -/// The user did not have sufficient permissions. -const NO_PERM = 77; - -/// Something was unconfigured or mis-configured. -const CONFIG = 78; diff --git a/sdk/lib/_internal/pub_generated/lib/src/git.dart b/sdk/lib/_internal/pub_generated/lib/src/git.dart deleted file mode 100644 index a574e8a6865..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/git.dart +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Helper functionality for invoking Git. -library pub.git; - -import 'dart:async'; -import 'dart:io'; - -import 'package:stack_trace/stack_trace.dart'; - -import 'exceptions.dart'; -import 'io.dart'; -import 'log.dart' as log; -import 'utils.dart'; - -/// An exception thrown because a git command failed. -class GitException implements ApplicationException { - /// The arguments to the git command. - final List args; - - /// The standard error emitted by git. - final String stderr; - - String get message => 'Git error. Command: git ${args.join(" ")}\n$stderr'; - - GitException(Iterable args, this.stderr) - : args = args.toList(); - - String toString() => message; -} - -/// Tests whether or not the git command-line app is available for use. -bool get isInstalled { - if (_isInstalledCache != null) return _isInstalledCache; - _isInstalledCache = _gitCommand != null; - return _isInstalledCache; -} -bool _isInstalledCache; - -/// Run a git process with [args] from [workingDir]. -/// -/// Returns the stdout as a list of strings if it succeeded. Completes to an -/// exception if it failed. -Future> run(List args, {String workingDir, Map environment}) { - if (!isInstalled) { - fail( - "Cannot find a Git executable.\n" "Please ensure Git is correctly installed."); - } - - log.muteProgress(); - return runProcess( - _gitCommand, - args, - workingDir: workingDir, - environment: environment).then((result) { - if (!result.success) throw new GitException(args, result.stderr.join("\n")); - - return result.stdout; - }).whenComplete(() { - log.unmuteProgress(); - }); -} - -/// Like [run], but synchronous. -List runSync(List args, {String workingDir, Map environment}) { - if (!isInstalled) { - fail( - "Cannot find a Git executable.\n" "Please ensure Git is correctly installed."); - } - - var result = runProcessSync( - _gitCommand, - args, - workingDir: workingDir, - environment: environment); - if (!result.success) throw new GitException(args, result.stderr.join("\n")); - return result.stdout; -} - -/// Returns the name of the git command-line app, or null if Git could not be -/// found on the user's PATH. -String get _gitCommand { - if (_commandCache != null) return _commandCache; - - var command; - if (_tryGitCommand("git")) { - _commandCache = "git"; - } else if (_tryGitCommand("git.cmd")) { - _commandCache = "git.cmd"; - } else { - return null; - } - - log.fine('Determined git command $command.'); - return _commandCache; -} -String _commandCache; - -/// Checks whether [command] is the Git command for this computer. -bool _tryGitCommand(String command) { - // If "git --version" prints something familiar, git is working. - try { - var result = runProcessSync(command, ["--version"]); - var regexp = new RegExp("^git version"); - return result.stdout.length == 1 && regexp.hasMatch(result.stdout.single); - } on ProcessException catch (error, stackTrace) { - var chain = new Chain.forTrace(stackTrace); - // If the process failed, they probably don't have it. - log.message('Git command is not "$command": $error\n$chain'); - return false; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/global_packages.dart b/sdk/lib/_internal/pub_generated/lib/src/global_packages.dart deleted file mode 100644 index 3dfed379245..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/global_packages.dart +++ /dev/null @@ -1,1109 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.global_packages; - -import 'dart:async'; -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:barback/barback.dart'; -import 'package:pub_semver/pub_semver.dart'; - -import 'barback/asset_environment.dart'; -import 'entrypoint.dart'; -import 'exceptions.dart'; -import 'executable.dart' as exe; -import 'io.dart'; -import 'lock_file.dart'; -import 'log.dart' as log; -import 'package.dart'; -import 'pubspec.dart'; -import 'sdk.dart' as sdk; -import 'solver/version_solver.dart'; -import 'source/cached.dart'; -import 'source/git.dart'; -import 'source/path.dart'; -import 'system_cache.dart'; -import 'utils.dart'; - -/// Maintains the set of packages that have been globally activated. -/// -/// These have been hand-chosen by the user to make their executables in bin/ -/// available to the entire system. This lets them access them even when the -/// current working directory is not inside another entrypoint package. -/// -/// Only one version of a given package name can be globally activated at a -/// time. Activating a different version of a package will deactivate the -/// previous one. -/// -/// This handles packages from uncached and cached sources a little differently. -/// For a cached source, the package is physically in the user's pub cache and -/// we don't want to mess with it by putting a lockfile in there. Instead, when -/// we activate the package, we create a full lockfile and put it in the -/// "global_packages" directory. It's named ".lock". Unlike a normal -/// lockfile, it also contains an entry for the root package itself, so that we -/// know the version and description that was activated. -/// -/// Uncached packages (i.e. "path" packages) are somewhere else on the user's -/// local file system and can have a lockfile directly in place. (And, in fact, -/// we want to ensure we honor the user's lockfile there.) To activate it, we -/// just need to know where that package directory is. For that, we create a -/// lockfile that *only* contains the root package's [PackageId] -- basically -/// just the path to the directory where the real lockfile lives. -class GlobalPackages { - /// The [SystemCache] containing the global packages. - final SystemCache cache; - - /// The directory where the lockfiles for activated packages are stored. - String get _directory => p.join(cache.rootDir, "global_packages"); - - /// The directory where binstubs for global package executables are stored. - String get _binStubDir => p.join(cache.rootDir, "bin"); - - /// Creates a new global package registry backed by the given directory on - /// the user's file system. - /// - /// The directory may not physically exist yet. If not, this will create it - /// when needed. - GlobalPackages(this.cache); - - /// Caches the package located in the Git repository [repo] and makes it the - /// active global version. - /// - /// [executables] is the names of the executables that should have binstubs. - /// If `null`, all executables in the package will get binstubs. If empty, no - /// binstubs will be created. - /// - /// if [overwriteBinStubs] is `true`, any binstubs that collide with - /// existing binstubs in other packages will be overwritten by this one's. - /// Otherwise, the previous ones will be preserved. - Future activateGit(String repo, List executables, - {bool overwriteBinStubs}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var source = cache.sources["git"] as GitSource; - new Future.value(source.getPackageNameFromRepo(repo)).then((x0) { - try { - var name = x0; - _describeActive(name); - new Future.value( - _installInCache( - new PackageDep(name, "git", VersionConstraint.any, repo), - executables, - overwriteBinStubs: overwriteBinStubs)).then((x1) { - try { - x1; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Finds the latest version of the hosted package with [name] that matches - /// [constraint] and makes it the active global version. - /// - /// [executables] is the names of the executables that should have binstubs. - /// If `null`, all executables in the package will get binstubs. If empty, no - /// binstubs will be created. - /// - /// if [overwriteBinStubs] is `true`, any binstubs that collide with - /// existing binstubs in other packages will be overwritten by this one's. - /// Otherwise, the previous ones will be preserved. - Future activateHosted(String name, VersionConstraint constraint, - List executables, {bool overwriteBinStubs}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - _describeActive(name); - new Future.value( - _installInCache( - new PackageDep(name, "hosted", constraint, name), - executables, - overwriteBinStubs: overwriteBinStubs)).then((x0) { - try { - x0; - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Makes the local package at [path] globally active. - /// - /// [executables] is the names of the executables that should have binstubs. - /// If `null`, all executables in the package will get binstubs. If empty, no - /// binstubs will be created. - /// - /// if [overwriteBinStubs] is `true`, any binstubs that collide with - /// existing binstubs in other packages will be overwritten by this one's. - /// Otherwise, the previous ones will be preserved. - Future activatePath(String path, List executables, - {bool overwriteBinStubs}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var entrypoint = new Entrypoint(path, cache); - new Future.value(entrypoint.ensureLockFileIsUpToDate()).then((x0) { - try { - x0; - var name = entrypoint.root.name; - _describeActive(name); - var fullPath = canonicalize(entrypoint.root.dir); - var id = new PackageId( - name, - "path", - entrypoint.root.version, - PathSource.describePath(fullPath)); - _writeLockFile(name, new LockFile([id])); - var binDir = p.join(_directory, name, 'bin'); - join0() { - _updateBinStubs( - entrypoint.root, - executables, - overwriteBinStubs: overwriteBinStubs); - completer0.complete(); - } - if (dirExists(binDir)) { - deleteEntry(binDir); - join0(); - } else { - join0(); - } - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Installs the package [dep] and its dependencies into the system cache. - Future _installInCache(PackageDep dep, List executables, - {bool overwriteBinStubs}) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var source = cache.sources[dep.source]; - var root = new Package.inMemory( - new Pubspec( - "pub global activate", - dependencies: [dep], - sources: cache.sources)); - new Future.value( - resolveVersions(SolveType.GET, cache.sources, root)).then((x0) { - try { - var result = x0; - join0() { - result.showReport(SolveType.GET); - new Future.value( - Future.wait(result.packages.map(_cacheDependency))).then((x1) { - try { - var ids = x1; - var lockFile = new LockFile(ids); - new Future.value( - new Entrypoint.inMemory( - root, - lockFile, - cache).loadPackageGraph(result)).then((x2) { - try { - var graph = x2; - new Future.value( - _precompileExecutables(graph.entrypoint, dep.name)).then((x3) { - try { - var snapshots = x3; - _writeLockFile(dep.name, lockFile); - _updateBinStubs( - graph.packages[dep.name], - executables, - overwriteBinStubs: overwriteBinStubs, - snapshots: snapshots); - completer0.complete(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e2, s2) { - completer0.completeError(e2, s2); - } - }, onError: completer0.completeError); - } - if (!result.succeeded) { - join1() { - join2() { - throw result.error; - join0(); - } - if (result.error is NoVersionException) { - dataError(result.error.message); - join2(); - } else { - join2(); - } - } - if (result.error.package != dep.name) { - throw result.error; - join1(); - } else { - join1(); - } - } else { - join0(); - } - } catch (e3, s3) { - completer0.completeError(e3, s3); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Precompiles the executables for [package] and saves them in the global - /// cache. - /// - /// Returns a map from executable name to path for the snapshots that were - /// successfully precompiled. - Future> _precompileExecutables(Entrypoint entrypoint, - String package) { - return log.progress("Precompiling executables", () { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var binDir = p.join(_directory, package, 'bin'); - cleanDir(binDir); - new Future.value(entrypoint.loadPackageGraph()).then((x0) { - try { - var graph = x0; - new Future.value( - AssetEnvironment.create( - entrypoint, - BarbackMode.RELEASE, - entrypoints: graph.packages[package].executableIds, - useDart2JS: false)).then((x1) { - try { - var environment = x1; - environment.barback.errors.listen(((error) { - log.error(log.red("Build error:\n$error")); - })); - completer0.complete( - environment.precompileExecutables(package, binDir)); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } catch (e1, s1) { - completer0.completeError(e1, s1); - } - }, onError: completer0.completeError); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - }); - } - - /// Downloads [id] into the system cache if it's a cached package. - /// - /// Returns the resolved [PackageId] for [id]. - Future _cacheDependency(PackageId id) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var source = cache.sources[id.source]; - join0() { - completer0.complete(source.resolveId(id)); - } - if (!id.isRoot && source is CachedSource) { - new Future.value(source.downloadToSystemCache(id)).then((x0) { - try { - x0; - join0(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Finishes activating package [package] by saving [lockFile] in the cache. - void _writeLockFile(String package, LockFile lockFile) { - ensureDir(p.join(_directory, package)); - - // TODO(nweiz): This cleans up Dart 1.6's old lockfile location. Remove it - // when Dart 1.6 is old enough that we don't think anyone will have these - // lockfiles anymore (issue 20703). - var oldPath = p.join(_directory, "$package.lock"); - if (fileExists(oldPath)) deleteEntry(oldPath); - - writeTextFile( - _getLockFilePath(package), - lockFile.serialize(cache.rootDir, cache.sources)); - - var id = lockFile.packages[package]; - log.message('Activated ${_formatPackage(id)}.'); - } - - /// Shows the user the currently active package with [name], if any. - void _describeActive(String name) { - try { - var lockFile = new LockFile.load(_getLockFilePath(name), cache.sources); - var id = lockFile.packages[name]; - - if (id.source == 'git') { - var url = GitSource.urlFromDescription(id.description); - log.message( - 'Package ${log.bold(name)} is currently active from Git ' - 'repository "${url}".'); - } else if (id.source == 'path') { - var path = PathSource.pathFromDescription(id.description); - log.message( - 'Package ${log.bold(name)} is currently active at path ' '"$path".'); - } else { - log.message( - 'Package ${log.bold(name)} is currently active at version ' - '${log.bold(id.version)}.'); - } - } on IOException catch (error) { - // If we couldn't read the lock file, it's not activated. - return null; - } - } - - /// Deactivates a previously-activated package named [name]. - /// - /// Returns `false` if no package with [name] was currently active. - bool deactivate(String name) { - var dir = p.join(_directory, name); - if (!dirExists(dir)) return false; - - _deleteBinStubs(name); - - var lockFile = new LockFile.load(_getLockFilePath(name), cache.sources); - var id = lockFile.packages[name]; - log.message('Deactivated package ${_formatPackage(id)}.'); - - deleteEntry(dir); - - return true; - } - - /// Finds the active package with [name]. - /// - /// Returns an [Entrypoint] loaded with the active package if found. - Future find(String name) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var lockFilePath = _getLockFilePath(name); - var lockFile; - join0() { - var id = lockFile.packages[name]; - lockFile.packages.remove(name); - var source = cache.sources[id.source]; - join1() { - assert(id.source == "path"); - completer0.complete( - new Entrypoint(PathSource.pathFromDescription(id.description), cache)); - } - if (source is CachedSource) { - new Future.value( - cache.sources[id.source].getDirectory(id)).then((x0) { - try { - var dir = x0; - var package = new Package.load(name, dir, cache.sources); - completer0.complete( - new Entrypoint.inMemory(package, lockFile, cache)); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } else { - join1(); - } - } - catch0(error, s1) { - try { - if (error is IOException) { - var oldLockFilePath = p.join(_directory, '${name}.lock'); - join2() { - ensureDir(p.dirname(lockFilePath)); - new File(oldLockFilePath).renameSync(lockFilePath); - join0(); - } - catch1(error, s2) { - try { - if (error is IOException) { - dataError("No active package ${log.bold(name)}."); - join2(); - } else { - throw error; - } - } catch (error, s2) { - completer0.completeError(error, s2); - } - } - try { - lockFile = new LockFile.load(oldLockFilePath, cache.sources); - join2(); - } catch (e1, s3) { - catch1(e1, s3); - } - } else { - throw error; - } - } catch (error, s1) { - completer0.completeError(error, s1); - } - } - try { - lockFile = new LockFile.load(lockFilePath, cache.sources); - join0(); - } catch (e2, s4) { - catch0(e2, s4); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Runs [package]'s [executable] with [args]. - /// - /// If [executable] is available in its precompiled form, that will be - /// recompiled if the SDK has been upgraded since it was first compiled and - /// then run. Otherwise, it will be run from source. - /// - /// If [mode] is passed, it's used as the barback mode; it defaults to - /// [BarbackMode.RELEASE]. - /// - /// Returns the exit code from the executable. - Future runExecutable(String package, String executable, - Iterable args, {BarbackMode mode}) { - if (mode == null) mode = BarbackMode.RELEASE; - - var binDir = p.join(_directory, package, 'bin'); - if (mode != BarbackMode.RELEASE || - !fileExists(p.join(binDir, '$executable.dart.snapshot'))) { - return find(package).then((entrypoint) { - return exe.runExecutable( - entrypoint, - package, - executable, - args, - mode: mode, - isGlobal: true); - }); - } - - // Unless the user overrides the verbosity, we want to filter out the - // normal pub output shown while loading the environment. - if (log.verbosity == log.Verbosity.NORMAL) { - log.verbosity = log.Verbosity.WARNING; - } - - var snapshotPath = p.join(binDir, '$executable.dart.snapshot'); - return exe.runSnapshot(snapshotPath, args, recompile: () { - log.fine( - "$package:$executable is out of date and needs to be " "recompiled."); - return find( - package).then( - (entrypoint) => - entrypoint.loadPackageGraph()).then( - (graph) => _precompileExecutables(graph.entrypoint, package)); - }); - } - - /// Gets the path to the lock file for an activated cached package with - /// [name]. - String _getLockFilePath(String name) => - p.join(_directory, name, "pubspec.lock"); - - /// Shows the user a formatted list of globally activated packages. - void listActivePackages() { - if (!dirExists(_directory)) return; - - listDir(_directory).map(_loadPackageId).toList() - ..sort((id1, id2) => id1.name.compareTo(id2.name)) - ..forEach((id) => log.message(_formatPackage(id))); - } - - /// Returns the [PackageId] for the globally-activated package at [path]. - /// - /// [path] should be a path within [_directory]. It can either be an old-style - /// path to a single lockfile or a new-style path to a directory containing a - /// lockfile. - PackageId _loadPackageId(String path) { - var name = p.basenameWithoutExtension(path); - if (!fileExists(path)) path = p.join(path, 'pubspec.lock'); - - var id = - new LockFile.load(p.join(_directory, path), cache.sources).packages[name]; - - if (id == null) { - throw new FormatException( - "Pubspec for activated package $name didn't " "contain an entry for itself."); - } - - return id; - } - - /// Returns formatted string representing the package [id]. - String _formatPackage(PackageId id) { - if (id.source == 'git') { - var url = GitSource.urlFromDescription(id.description); - return '${log.bold(id.name)} ${id.version} from Git repository "$url"'; - } else if (id.source == 'path') { - var path = PathSource.pathFromDescription(id.description); - return '${log.bold(id.name)} ${id.version} at path "$path"'; - } else { - return '${log.bold(id.name)} ${id.version}'; - } - } - - /// Repairs any corrupted globally-activated packages and their binstubs. - /// - /// Returns a pair of two [int]s. The first indicates how many packages were - /// successfully re-activated; the second indicates how many failed. - Future> repairActivatedPackages() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var executables = {}; - join0() { - var successes = 0; - var failures = 0; - join1() { - join2() { - completer0.complete(new Pair(successes, failures)); - } - if (executables.isNotEmpty) { - var packages = pluralize("package", executables.length); - var message = - new StringBuffer("Binstubs exist for non-activated " "packages:\n"); - executables.forEach(((package, executableNames) { - executableNames.forEach( - (executable) => deleteEntry(p.join(_binStubDir, executable))); - message.writeln( - " From ${log.bold(package)}: " "${toSentence(executableNames)}"); - })); - log.error(message); - join2(); - } else { - join2(); - } - } - if (dirExists(_directory)) { - var it0 = listDir(_directory).iterator; - break0() { - join1(); - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var entry = it0.current; - var id; - join3() { - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - catch0(error, stackTrace) { - try { - var message = - "Failed to reactivate " "${log.bold(p.basenameWithoutExtension(entry))}"; - join4() { - log.error(message, error, stackTrace); - failures++; - tryDeleteEntry(entry); - join3(); - } - if (id != null) { - message += " ${id.version}"; - join5() { - join4(); - } - if (id.source != "hosted") { - message += " from ${id.source}"; - join5(); - } else { - join5(); - } - } else { - join4(); - } - } catch (error, stackTrace) { - completer0.completeError(error, stackTrace); - } - } - try { - id = _loadPackageId(entry); - log.message( - "Reactivating ${log.bold(id.name)} ${id.version}..."); - new Future.value(find(id.name)).then((x0) { - trampoline0 = () { - trampoline0 = null; - try { - var entrypoint = x0; - new Future.value( - entrypoint.loadPackageGraph()).then((x1) { - trampoline0 = () { - trampoline0 = null; - try { - var graph = x1; - new Future.value( - _precompileExecutables(entrypoint, id.name)).then((x2) { - trampoline0 = () { - trampoline0 = null; - try { - var snapshots = x2; - var packageExecutables = - executables.remove(id.name); - join6() { - _updateBinStubs( - graph.packages[id.name], - packageExecutables, - overwriteBinStubs: true, - snapshots: snapshots, - suggestIfNotOnPath: false); - successes++; - join3(); - } - if (packageExecutables == null) { - packageExecutables = []; - join6(); - } else { - join6(); - } - } catch (e0, s0) { - catch0(e0, s0); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: catch0); - } catch (e1, s1) { - catch0(e1, s1); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: catch0); - } catch (e2, s2) { - catch0(e2, s2); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: catch0); - } catch (e3, s3) { - catch0(e3, s3); - } - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } else { - join1(); - } - } - if (dirExists(_binStubDir)) { - var it1 = listDir(_binStubDir).iterator; - break1() { - join0(); - } - var trampoline1; - continue1() { - trampoline1 = null; - if (it1.moveNext()) { - var entry = it1.current; - join7() { - trampoline1 = continue1; - do trampoline1(); while (trampoline1 != null); - } - catch1(error, stackTrace) { - try { - log.error( - "Error reading binstub for " "\"${p.basenameWithoutExtension(entry)}\"", - error, - stackTrace); - tryDeleteEntry(entry); - join7(); - } catch (error, stackTrace) { - completer0.completeError(error, stackTrace); - } - } - try { - var binstub = readTextFile(entry); - var package = _binStubProperty(binstub, "Package"); - join8() { - var executable = _binStubProperty(binstub, "Executable"); - join9() { - executables.putIfAbsent(package, (() { - return []; - })).add(executable); - join7(); - } - if (executable == null) { - throw new ApplicationException("No 'Executable' property."); - join9(); - } else { - join9(); - } - } - if (package == null) { - throw new ApplicationException("No 'Package' property."); - join8(); - } else { - join8(); - } - } catch (e4, s4) { - catch1(e4, s4); - } - } else { - break1(); - } - } - trampoline1 = continue1; - do trampoline1(); while (trampoline1 != null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Updates the binstubs for [package]. - /// - /// A binstub is a little shell script in `PUB_CACHE/bin` that runs an - /// executable from a globally activated package. This removes any old - /// binstubs from the previously activated version of the package and - /// (optionally) creates new ones for the executables listed in the package's - /// pubspec. - /// - /// [executables] is the names of the executables that should have binstubs. - /// If `null`, all executables in the package will get binstubs. If empty, no - /// binstubs will be created. - /// - /// If [overwriteBinStubs] is `true`, any binstubs that collide with - /// existing binstubs in other packages will be overwritten by this one's. - /// Otherwise, the previous ones will be preserved. - /// - /// If [snapshots] is given, it is a map of the names of executables whose - /// snapshots were precompiled to the paths of those snapshots. Binstubs for - /// those will run the snapshot directly and skip pub entirely. - /// - - /// If [suggestIfNotOnPath] is `true` (the default), this will warn the user if - /// the bin directory isn't on their path. - void _updateBinStubs(Package package, List executables, - {bool overwriteBinStubs, Map snapshots, bool suggestIfNotOnPath: - true}) { - if (snapshots == null) snapshots = const {}; - - // Remove any previously activated binstubs for this package, in case the - // list of executables has changed. - _deleteBinStubs(package.name); - - if ((executables != null && executables.isEmpty) || - package.pubspec.executables.isEmpty) { - return; - } - - ensureDir(_binStubDir); - - var installed = []; - var collided = {}; - var allExecutables = ordered(package.pubspec.executables.keys); - for (var executable in allExecutables) { - if (executables != null && !executables.contains(executable)) continue; - - var script = package.pubspec.executables[executable]; - - var previousPackage = _createBinStub( - package, - executable, - script, - overwrite: overwriteBinStubs, - snapshot: snapshots[script]); - if (previousPackage != null) { - collided[executable] = previousPackage; - - if (!overwriteBinStubs) continue; - } - - installed.add(executable); - } - - if (installed.isNotEmpty) { - var names = namedSequence("executable", installed.map(log.bold)); - log.message("Installed $names."); - } - - // Show errors for any collisions. - if (collided.isNotEmpty) { - for (var command in ordered(collided.keys)) { - if (overwriteBinStubs) { - log.warning( - "Replaced ${log.bold(command)} previously installed from " - "${log.bold(collided[command])}."); - } else { - log.warning( - "Executable ${log.bold(command)} was already installed " - "from ${log.bold(collided[command])}."); - } - } - - if (!overwriteBinStubs) { - log.warning( - "Deactivate the other package(s) or activate " - "${log.bold(package.name)} using --overwrite."); - } - } - - // Show errors for any unknown executables. - if (executables != null) { - var unknown = ordered( - executables.where((exe) => !package.pubspec.executables.keys.contains(exe))); - if (unknown.isNotEmpty) { - dataError("Unknown ${namedSequence('executable', unknown)}."); - } - } - - // Show errors for any missing scripts. - // TODO(rnystrom): This can print false positives since a script may be - // produced by a transformer. Do something better. - var binFiles = package.listFiles( - beneath: "bin", - recursive: false).map((path) => package.relative(path)).toList(); - for (var executable in installed) { - var script = package.pubspec.executables[executable]; - var scriptPath = p.join("bin", "$script.dart"); - if (!binFiles.contains(scriptPath)) { - log.warning( - 'Warning: Executable "$executable" runs "$scriptPath", ' - 'which was not found in ${log.bold(package.name)}.'); - } - } - - if (suggestIfNotOnPath && installed.isNotEmpty) { - _suggestIfNotOnPath(installed.first); - } - } - - /// Creates a binstub named [executable] that runs [script] from [package]. - /// - /// If [overwrite] is `true`, this will replace an existing binstub with that - /// name for another package. - /// - /// If [snapshot] is non-null, it is a path to a snapshot file. The binstub - /// will invoke that directly. Otherwise, it will run `pub global run`. - /// - /// If a collision occurs, returns the name of the package that owns the - /// existing binstub. Otherwise returns `null`. - String _createBinStub(Package package, String executable, String script, - {bool overwrite, String snapshot}) { - var binStubPath = p.join(_binStubDir, executable); - - if (Platform.operatingSystem == "windows") binStubPath += ".bat"; - - // See if the binstub already exists. If so, it's for another package - // since we already deleted all of this package's binstubs. - var previousPackage; - if (fileExists(binStubPath)) { - var contents = readTextFile(binStubPath); - previousPackage = _binStubProperty(contents, "Package"); - if (previousPackage == null) { - log.fine("Could not parse binstub $binStubPath:\n$contents"); - } else if (!overwrite) { - return previousPackage; - } - } - - // If the script was precompiled to a snapshot, just invoke that directly - // and skip pub global run entirely. - var invocation; - if (snapshot != null) { - // We expect absolute paths from the precompiler since relative ones - // won't be relative to the right directory when the user runs this. - assert(p.isAbsolute(snapshot)); - invocation = 'dart "$snapshot"'; - } else { - invocation = "pub global run ${package.name}:$script"; - } - - if (Platform.operatingSystem == "windows") { - var batch = """ -@echo off -rem This file was created by pub v${sdk.version}. -rem Package: ${package.name} -rem Version: ${package.version} -rem Executable: ${executable} -rem Script: ${script} -$invocation %* -"""; - - if (snapshot != null) { - batch += """ - -rem The VM exits with code 255 if the snapshot version is out-of-date. -rem If it is, we need to delete it and run "pub global" manually. -if not errorlevel 255 ( - exit /b %errorlevel% -) - -pub global run ${package.name}:$script %* -"""; - } - - writeTextFile(binStubPath, batch); - } else { - var bash = """ -#!/usr/bin/env sh -# This file was created by pub v${sdk.version}. -# Package: ${package.name} -# Version: ${package.version} -# Executable: ${executable} -# Script: ${script} -$invocation "\$@" -"""; - - if (snapshot != null) { - bash += """ - -# The VM exits with code 255 if the snapshot version is out-of-date. -# If it is, we need to delete it and run "pub global" manually. -exit_code=\$? -if [ \$exit_code != 255 ]; then - exit \$exit_code -fi - -pub global run ${package.name}:$script "\$@" -"""; - } - - writeTextFile(binStubPath, bash); - - // Make it executable. - var result = Process.runSync('chmod', ['+x', binStubPath]); - if (result.exitCode != 0) { - // Couldn't make it executable so don't leave it laying around. - try { - deleteEntry(binStubPath); - } on IOException catch (err) { - // Do nothing. We're going to fail below anyway. - log.fine("Could not delete binstub:\n$err"); - } - - fail( - 'Could not make "$binStubPath" executable (exit code ' - '${result.exitCode}):\n${result.stderr}'); - } - } - - return previousPackage; - } - - /// Deletes all existing binstubs for [package]. - void _deleteBinStubs(String package) { - if (!dirExists(_binStubDir)) return; - - for (var file in listDir(_binStubDir, includeDirs: false)) { - var contents = readTextFile(file); - var binStubPackage = _binStubProperty(contents, "Package"); - if (binStubPackage == null) { - log.fine("Could not parse binstub $file:\n$contents"); - continue; - } - - if (binStubPackage == package) { - log.fine("Deleting old binstub $file"); - deleteEntry(file); - } - } - } - - /// Checks to see if the binstubs are on the user's PATH and, if not, suggests - /// that the user add the directory to their PATH. - /// - /// [installed] should be the name of an installed executable that can be used - /// to test whether accessing it on the path works. - void _suggestIfNotOnPath(String installed) { - if (Platform.operatingSystem == "windows") { - // See if the shell can find one of the binstubs. - // "\q" means return exit code 0 if found or 1 if not. - var result = runProcessSync("where", [r"\q", installed + ".bat"]); - if (result.exitCode == 0) return; - - log.warning( - "${log.yellow('Warning:')} Pub installs executables into " - "${log.bold(_binStubDir)}, which is not on your path.\n" - "You can fix that by adding that directory to your system's " - '"Path" environment variable.\n' - 'A web search for "configure windows path" will show you how.'); - } else { - // See if the shell can find one of the binstubs. - var result = runProcessSync("which", [installed]); - if (result.exitCode == 0) return; - - var binDir = _binStubDir; - if (binDir.startsWith(Platform.environment['HOME'])) { - binDir = - p.join("~", p.relative(binDir, from: Platform.environment['HOME'])); - } - - log.warning( - "${log.yellow('Warning:')} Pub installs executables into " - "${log.bold(binDir)}, which is not on your path.\n" - "You can fix that by adding this to your shell's config file " - "(.bashrc, .bash_profile, etc.):\n" "\n" - " ${log.bold('export PATH="\$PATH":"$binDir"')}\n" "\n"); - } - } - - /// Returns the value of the property named [name] in the bin stub script - /// [source]. - String _binStubProperty(String source, String name) { - var pattern = new RegExp(quoteRegExp(name) + r": ([a-zA-Z0-9_-]+)"); - var match = pattern.firstMatch(source); - return match == null ? null : match[1]; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/http.dart b/sdk/lib/_internal/pub_generated/lib/src/http.dart deleted file mode 100644 index eea72ae86b4..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/http.dart +++ /dev/null @@ -1,270 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Helpers for dealing with HTTP. -library pub.http; - -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:http/http.dart' as http; -import 'package:http_throttle/http_throttle.dart'; - -import 'io.dart'; -import 'log.dart' as log; -import 'oauth2.dart' as oauth2; -import 'sdk.dart' as sdk; -import 'utils.dart'; - -// TODO(nweiz): make this configurable -/// The amount of time in milliseconds to allow HTTP requests before assuming -/// they've failed. -final HTTP_TIMEOUT = 30 * 1000; - -/// Headers and field names that should be censored in the log output. -final _CENSORED_FIELDS = const ['refresh_token', 'authorization']; - -/// Headers required for pub.dartlang.org API requests. -/// -/// The Accept header tells pub.dartlang.org which version of the API we're -/// expecting, so it can either serve that version or give us a 406 error if -/// it's not supported. -final PUB_API_HEADERS = const { - 'Accept': 'application/vnd.pub.v2+json' -}; - -/// An HTTP client that transforms 40* errors and socket exceptions into more -/// user-friendly error messages. -/// -/// This also adds a 30-second timeout to every request. This can be configured -/// on a per-request basis by setting the 'Pub-Request-Timeout' header to the -/// desired number of milliseconds, or to "None" to disable the timeout. -class _PubHttpClient extends http.BaseClient { - final _requestStopwatches = new Map(); - - http.Client _inner; - - _PubHttpClient([http.Client inner]) - : this._inner = inner == null ? new http.Client() : inner; - - Future send(http.BaseRequest request) { - _requestStopwatches[request] = new Stopwatch()..start(); - request.headers[HttpHeaders.USER_AGENT] = "Dart pub ${sdk.version}"; - _logRequest(request); - - // TODO(nweiz): remove this when issue 4061 is fixed. - var stackTrace; - try { - throw null; - } catch (_, localStackTrace) { - stackTrace = localStackTrace; - } - - var timeoutLength = HTTP_TIMEOUT; - var timeoutString = request.headers.remove('Pub-Request-Timeout'); - if (timeoutString == 'None') { - timeoutLength = null; - } else if (timeoutString != null) { - timeoutLength = int.parse(timeoutString); - } - - var future = _inner.send(request).then((streamedResponse) { - _logResponse(streamedResponse); - - var status = streamedResponse.statusCode; - // 401 responses should be handled by the OAuth2 client. It's very - // unlikely that they'll be returned by non-OAuth2 requests. We also want - // to pass along 400 responses from the token endpoint. - var tokenRequest = - urisEqual(streamedResponse.request.url, oauth2.tokenEndpoint); - if (status < 400 || status == 401 || (status == 400 && tokenRequest)) { - return streamedResponse; - } - - if (status == 406 && - request.headers['Accept'] == PUB_API_HEADERS['Accept']) { - fail( - "Pub ${sdk.version} is incompatible with the current version of " - "${request.url.host}.\n" "Upgrade pub to the latest version and try again."); - } - - if (status == 500 && - (request.url.host == "pub.dartlang.org" || - request.url.host == "storage.googleapis.com")) { - var message = - "HTTP error 500: Internal Server Error at " "${request.url}."; - - if (request.url.host == "pub.dartlang.org" || - request.url.host == "storage.googleapis.com") { - message += - "\nThis is likely a transient error. Please try again " "later."; - } - - fail(message); - } - - return http.Response.fromStream(streamedResponse).then((response) { - throw new PubHttpException(response); - }); - }).catchError((error, stackTrace) { - if (error is SocketException && error.osError != null) { - if (error.osError.errorCode == 8 || - error.osError.errorCode == -2 || - error.osError.errorCode == -5 || - error.osError.errorCode == 11001 || - error.osError.errorCode == 11004) { - fail( - 'Could not resolve URL "${request.url.origin}".', - error, - stackTrace); - } else if (error.osError.errorCode == -12276) { - fail( - 'Unable to validate SSL certificate for ' '"${request.url.origin}".', - error, - stackTrace); - } - } - throw error; - }); - - if (timeoutLength == null) return future; - return timeout( - future, - timeoutLength, - request.url, - 'fetching URL "${request.url}"'); - } - - /// Logs the fact that [request] was sent, and information about it. - void _logRequest(http.BaseRequest request) { - var requestLog = new StringBuffer(); - requestLog.writeln("HTTP ${request.method} ${request.url}"); - request.headers.forEach( - (name, value) => requestLog.writeln(_logField(name, value))); - - if (request.method == 'POST') { - var contentTypeString = request.headers[HttpHeaders.CONTENT_TYPE]; - if (contentTypeString == null) contentTypeString = ''; - var contentType = ContentType.parse(contentTypeString); - if (request is http.MultipartRequest) { - requestLog.writeln(); - requestLog.writeln("Body fields:"); - request.fields.forEach( - (name, value) => requestLog.writeln(_logField(name, value))); - - // TODO(nweiz): make MultipartRequest.files readable, and log them? - } else if (request is http.Request) { - if (contentType.value == 'application/x-www-form-urlencoded') { - requestLog.writeln(); - requestLog.writeln("Body fields:"); - request.bodyFields.forEach( - (name, value) => requestLog.writeln(_logField(name, value))); - } else if (contentType.value == 'text/plain' || - contentType.value == 'application/json') { - requestLog.write(request.body); - } - } - } - - log.fine(requestLog.toString().trim()); - } - - /// Logs the fact that [response] was received, and information about it. - void _logResponse(http.StreamedResponse response) { - // TODO(nweiz): Fork the response stream and log the response body. Be - // careful not to log OAuth2 private data, though. - - var responseLog = new StringBuffer(); - var request = response.request; - var stopwatch = _requestStopwatches.remove(request)..stop(); - responseLog.writeln( - "HTTP response ${response.statusCode} " - "${response.reasonPhrase} for ${request.method} ${request.url}"); - responseLog.writeln("took ${stopwatch.elapsed}"); - response.headers.forEach( - (name, value) => responseLog.writeln(_logField(name, value))); - - log.fine(responseLog.toString().trim()); - } - - /// Returns a log-formatted string for the HTTP field or header with the given - /// [name] and [value]. - String _logField(String name, String value) { - if (_CENSORED_FIELDS.contains(name.toLowerCase())) { - return "$name: "; - } else { - return "$name: $value"; - } - } -} - -/// The [_PubHttpClient] wrapped by [httpClient]. -final _pubClient = new _PubHttpClient(); - -/// The HTTP client to use for all HTTP requests. -final httpClient = new ThrottleClient(16, _pubClient); - -/// The underlying HTTP client wrapped by [httpClient]. -http.Client get innerHttpClient => _pubClient._inner; -set innerHttpClient(http.Client client) => _pubClient._inner = client; - -/// Handles a successful JSON-formatted response from pub.dartlang.org. -/// -/// These responses are expected to be of the form `{"success": {"message": -/// "some message"}}`. If the format is correct, the message will be printed; -/// otherwise an error will be raised. -void handleJsonSuccess(http.Response response) { - var parsed = parseJsonResponse(response); - if (parsed['success'] is! Map || - !parsed['success'].containsKey('message') || - parsed['success']['message'] is! String) { - invalidServerResponse(response); - } - log.message(parsed['success']['message']); -} - -/// Handles an unsuccessful JSON-formatted response from pub.dartlang.org. -/// -/// These responses are expected to be of the form `{"error": {"message": "some -/// message"}}`. If the format is correct, the message will be raised as an -/// error; otherwise an [invalidServerResponse] error will be raised. -void handleJsonError(http.Response response) { - var errorMap = parseJsonResponse(response); - if (errorMap['error'] is! Map || - !errorMap['error'].containsKey('message') || - errorMap['error']['message'] is! String) { - invalidServerResponse(response); - } - fail(errorMap['error']['message']); -} - -/// Parses a response body, assuming it's JSON-formatted. -/// -/// Throws a user-friendly error if the response body is invalid JSON, or if -/// it's not a map. -Map parseJsonResponse(http.Response response) { - var value; - try { - value = JSON.decode(response.body); - } on FormatException catch (e) { - invalidServerResponse(response); - } - if (value is! Map) invalidServerResponse(response); - return value; -} - -/// Throws an error describing an invalid response from the server. -void invalidServerResponse(http.Response response) => - fail('Invalid server response:\n${response.body}'); - -/// Exception thrown when an HTTP operation fails. -class PubHttpException implements Exception { - final http.Response response; - - const PubHttpException(this.response); - - String toString() => - 'HTTP error ${response.statusCode}: ' '${response.reasonPhrase}'; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/io.dart b/sdk/lib/_internal/pub_generated/lib/src/io.dart deleted file mode 100644 index 35df8d1d823..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/io.dart +++ /dev/null @@ -1,1028 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Helper functionality to make working with IO easier. -library pub.io; - -import 'dart:async'; -import 'dart:collection'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:path/path.dart' as path; -import 'package:pool/pool.dart'; -import 'package:http/http.dart' show ByteStream; -import 'package:http_multi_server/http_multi_server.dart'; -import 'package:stack_trace/stack_trace.dart'; - -import 'exit_codes.dart' as exit_codes; -import 'exceptions.dart'; -import 'error_group.dart'; -import 'log.dart' as log; -import 'sdk.dart' as sdk; -import 'utils.dart'; - -export 'package:http/http.dart' show ByteStream; - -/// The pool used for restricting access to asynchronous operations that consume -/// file descriptors. -/// -/// The maximum number of allocated descriptors is based on empirical tests that -/// indicate that beyond 32, additional file reads don't provide substantial -/// additional throughput. -final _descriptorPool = new Pool(32); - -/// Determines if a file or directory exists at [path]. -bool entryExists(String path) => - dirExists(path) || fileExists(path) || linkExists(path); - -/// Returns whether [link] exists on the file system. -/// -/// This returns `true` for any symlink, regardless of what it points at or -/// whether it's broken. -bool linkExists(String link) => new Link(link).existsSync(); - -/// Returns whether [file] exists on the file system. -/// -/// This returns `true` for a symlink only if that symlink is unbroken and -/// points to a file. -bool fileExists(String file) => new File(file).existsSync(); - -/// Returns the canonical path for [pathString]. -/// -/// This is the normalized, absolute path, with symlinks resolved. As in -/// [transitiveTarget], broken or recursive symlinks will not be fully resolved. -/// -/// This doesn't require [pathString] to point to a path that exists on the -/// filesystem; nonexistent or unreadable path entries are treated as normal -/// directories. -String canonicalize(String pathString) { - var seen = new Set(); - var components = - new Queue.from(path.split(path.normalize(path.absolute(pathString)))); - - // The canonical path, built incrementally as we iterate through [components]. - var newPath = components.removeFirst(); - - // Move through the components of the path, resolving each one's symlinks as - // necessary. A resolved component may also add new components that need to be - // resolved in turn. - while (!components.isEmpty) { - seen.add(path.join(newPath, path.joinAll(components))); - var resolvedPath = - resolveLink(path.join(newPath, components.removeFirst())); - var relative = path.relative(resolvedPath, from: newPath); - - // If the resolved path of the component relative to `newPath` is just ".", - // that means component was a symlink pointing to its parent directory. We - // can safely ignore such components. - if (relative == '.') continue; - - var relativeComponents = new Queue.from(path.split(relative)); - - // If the resolved path is absolute relative to `newPath`, that means it's - // on a different drive. We need to canonicalize the entire target of that - // symlink again. - if (path.isAbsolute(relative)) { - // If we've already tried to canonicalize the new path, we've encountered - // a symlink loop. Avoid going infinite by treating the recursive symlink - // as the canonical path. - if (seen.contains(relative)) { - newPath = relative; - } else { - newPath = relativeComponents.removeFirst(); - relativeComponents.addAll(components); - components = relativeComponents; - } - continue; - } - - // Pop directories off `newPath` if the component links upwards in the - // directory hierarchy. - while (relativeComponents.first == '..') { - newPath = path.dirname(newPath); - relativeComponents.removeFirst(); - } - - // If there's only one component left, [resolveLink] guarantees that it's - // not a link (or is a broken link). We can just add it to `newPath` and - // continue resolving the remaining components. - if (relativeComponents.length == 1) { - newPath = path.join(newPath, relativeComponents.single); - continue; - } - - // If we've already tried to canonicalize the new path, we've encountered a - // symlink loop. Avoid going infinite by treating the recursive symlink as - // the canonical path. - var newSubPath = path.join(newPath, path.joinAll(relativeComponents)); - if (seen.contains(newSubPath)) { - newPath = newSubPath; - continue; - } - - // If there are multiple new components to resolve, add them to the - // beginning of the queue. - relativeComponents.addAll(components); - components = relativeComponents; - } - return newPath; -} - -/// Returns the transitive target of [link] (if A links to B which links to C, -/// this will return C). -/// -/// If [link] is part of a symlink loop (e.g. A links to B which links back to -/// A), this returns the path to the first repeated link (so -/// `transitiveTarget("A")` would return `"A"` and `transitiveTarget("A")` would -/// return `"B"`). -/// -/// This accepts paths to non-links or broken links, and returns them as-is. -String resolveLink(String link) { - var seen = new Set(); - while (linkExists(link) && !seen.contains(link)) { - seen.add(link); - link = - path.normalize(path.join(path.dirname(link), new Link(link).targetSync())); - } - return link; -} - -/// Reads the contents of the text file [file]. -String readTextFile(String file) => - new File(file).readAsStringSync(encoding: UTF8); - -/// Reads the contents of the binary file [file]. -List readBinaryFile(String file) { - log.io("Reading binary file $file."); - var contents = new File(file).readAsBytesSync(); - log.io("Read ${contents.length} bytes from $file."); - return contents; -} - -/// Creates [file] and writes [contents] to it. -/// -/// If [dontLogContents] is true, the contents of the file will never be logged. -String writeTextFile(String file, String contents, {bool dontLogContents: - false}) { - // Sanity check: don't spew a huge file. - log.io("Writing ${contents.length} characters to text file $file."); - if (!dontLogContents && contents.length < 1024 * 1024) { - log.fine("Contents:\n$contents"); - } - - new File(file).writeAsStringSync(contents); - return file; -} - -/// Creates [file] and writes [contents] to it. -String writeBinaryFile(String file, List contents) { - log.io("Writing ${contents.length} bytes to binary file $file."); - new File(file).openSync(mode: FileMode.WRITE) - ..writeFromSync(contents) - ..closeSync(); - log.fine("Wrote text file $file."); - return file; -} - -/// Writes [stream] to a new file at path [file]. -/// -/// Replaces any file already at that path. Completes when the file is done -/// being written. -Future createFileFromStream(Stream> stream, String file) { - // TODO(nweiz): remove extra logging when we figure out the windows bot issue. - log.io("Creating $file from stream."); - - return _descriptorPool.withResource(() { - return stream.pipe(new File(file).openWrite()).then((_) { - log.fine("Created $file from stream."); - return file; - }); - }); -} - -/// Copies all files in [files] to the directory [destination]. -/// -/// Their locations in [destination] will be determined by their relative -/// location to [baseDir]. Any existing files at those paths will be -/// overwritten. -void copyFiles(Iterable files, String baseDir, String destination) { - for (var file in files) { - var newPath = path.join(destination, path.relative(file, from: baseDir)); - ensureDir(path.dirname(newPath)); - copyFile(file, newPath); - } -} - -/// Copies a file from [source] to [destination]. -void copyFile(String source, String destination) { - writeBinaryFile(destination, readBinaryFile(source)); -} - -/// Creates a directory [dir]. -String createDir(String dir) { - new Directory(dir).createSync(); - return dir; -} - -/// Ensures that [dir] and all its parent directories exist. -/// -/// If they don't exist, creates them. -String ensureDir(String dir) { - new Directory(dir).createSync(recursive: true); - return dir; -} - -/// Creates a temp directory in [dir], whose name will be [prefix] with -/// characters appended to it to make a unique name. -/// -/// Returns the path of the created directory. -String createTempDir(String base, String prefix) { - var tempDir = new Directory(base).createTempSync(prefix); - log.io("Created temp directory ${tempDir.path}"); - return tempDir.path; -} - -/// Creates a temp directory in the system temp directory, whose name will be -/// 'pub_' with characters appended to it to make a unique name. -/// -/// Returns the path of the created directory. -String createSystemTempDir() { - var tempDir = Directory.systemTemp.createTempSync('pub_'); - log.io("Created temp directory ${tempDir.path}"); - return tempDir.path; -} - -/// Lists the contents of [dir]. -/// -/// If [recursive] is `true`, lists subdirectory contents (defaults to `false`). -/// If [includeHidden] is `true`, includes files and directories beginning with -/// `.` (defaults to `false`). If [includeDirs] is `true`, includes directories -/// as well as files (defaults to `true`). -/// -/// [whiteList] is a list of hidden filenames to include even when -/// [includeHidden] is `false`. -/// -/// Note that dart:io handles recursive symlinks in an unfortunate way. You -/// end up with two copies of every entity that is within the recursive loop. -/// We originally had our own directory list code that addressed that, but it -/// had a noticeable performance impact. In the interest of speed, we'll just -/// live with that annoying behavior. -/// -/// The returned paths are guaranteed to begin with [dir]. Broken symlinks won't -/// be returned. -List listDir(String dir, {bool recursive: false, bool includeHidden: - false, bool includeDirs: true, Iterable whitelist}) { - if (whitelist == null) whitelist = []; - var whitelistFilter = createFileFilter(whitelist); - - // This is used in some performance-sensitive paths and can list many, many - // files. As such, it leans more havily towards optimization as opposed to - // readability than most code in pub. In particular, it avoids using the path - // package, since re-parsing a path is very expensive relative to string - // operations. - return new Directory( - dir).listSync(recursive: recursive, followLinks: true).where((entity) { - if (!includeDirs && entity is Directory) return false; - if (entity is Link) return false; - if (includeHidden) return true; - - // Using substring here is generally problematic in cases where dir has one - // or more trailing slashes. If you do listDir("foo"), you'll get back - // paths like "foo/bar". If you do listDir("foo/"), you'll get "foo/bar" - // (note the trailing slash was dropped. If you do listDir("foo//"), you'll - // get "foo//bar". - // - // This means if you strip off the prefix, the resulting string may have a - // leading separator (if the prefix did not have a trailing one) or it may - // not. However, since we are only using the results of that to call - // contains() on, the leading separator is harmless. - assert(entity.path.startsWith(dir)); - var pathInDir = entity.path.substring(dir.length); - - // If the basename is whitelisted, don't count its "/." as making the file - // hidden. - var whitelistedBasename = - whitelistFilter.firstWhere(pathInDir.contains, orElse: () => null); - if (whitelistedBasename != null) { - pathInDir = - pathInDir.substring(0, pathInDir.length - whitelistedBasename.length); - } - - if (pathInDir.contains("/.")) return false; - if (Platform.operatingSystem != "windows") return true; - return !pathInDir.contains("\\."); - }).map((entity) => entity.path).toList(); -} - -/// Returns whether [dir] exists on the file system. -/// -/// This returns `true` for a symlink only if that symlink is unbroken and -/// points to a directory. -bool dirExists(String dir) => new Directory(dir).existsSync(); - -/// Tries to resiliently perform [operation]. -/// -/// Some file system operations can intermittently fail on Windows because -/// other processes are locking a file. We've seen this with virus scanners -/// when we try to delete or move something while it's being scanned. To -/// mitigate that, on Windows, this will retry the operation a few times if it -/// fails. -void _attempt(String description, void operation()) { - if (Platform.operatingSystem != 'windows') { - operation(); - return; - } - - getErrorReason(error) { - if (error.osError.errorCode == 5) { - return "access was denied"; - } - - if (error.osError.errorCode == 32) { - return "it was in use by another process"; - } - - return null; - } - - for (var i = 0; i < 2; i++) { - try { - operation(); - return; - } on FileSystemException catch (error) { - var reason = getErrorReason(error); - if (reason == null) rethrow; - - log.io("Failed to $description because $reason. " "Retrying in 50ms."); - sleep(new Duration(milliseconds: 50)); - } - } - - try { - operation(); - } on FileSystemException catch (error) { - var reason = getErrorReason(error); - if (reason == null) rethrow; - - fail( - "Failed to $description because $reason.\n" - "This may be caused by a virus scanner or having a file\n" - "in the directory open in another application."); - } -} - -/// Deletes whatever's at [path], whether it's a file, directory, or symlink. -/// -/// If it's a directory, it will be deleted recursively. -void deleteEntry(String path) { - _attempt("delete entry", () { - if (linkExists(path)) { - log.io("Deleting link $path."); - new Link(path).deleteSync(); - } else if (dirExists(path)) { - log.io("Deleting directory $path."); - new Directory(path).deleteSync(recursive: true); - } else if (fileExists(path)) { - log.io("Deleting file $path."); - new File(path).deleteSync(); - } - }); -} - -/// Attempts to delete whatever's at [path], but doesn't throw an exception if -/// the deletion fails. -void tryDeleteEntry(String path) { - try { - deleteEntry(path); - } catch (error, stackTrace) { - log.fine( - "Failed to delete $path: $error\n" "${new Chain.forTrace(stackTrace)}"); - } -} - -/// "Cleans" [dir]. -/// -/// If that directory already exists, it is deleted. Then a new empty directory -/// is created. -void cleanDir(String dir) { - if (entryExists(dir)) deleteEntry(dir); - ensureDir(dir); -} - -/// Renames (i.e. moves) the directory [from] to [to]. -void renameDir(String from, String to) { - _attempt("rename directory", () { - log.io("Renaming directory $from to $to."); - try { - new Directory(from).renameSync(to); - } on IOException catch (error) { - // Ensure that [to] isn't left in an inconsistent state. See issue 12436. - if (entryExists(to)) deleteEntry(to); - rethrow; - } - }); -} - -/// Creates a new symlink at path [symlink] that points to [target]. -/// -/// Returns a [Future] which completes to the path to the symlink file. -/// -/// If [relative] is true, creates a symlink with a relative path from the -/// symlink to the target. Otherwise, uses the [target] path unmodified. -/// -/// Note that on Windows, only directories may be symlinked to. -void createSymlink(String target, String symlink, {bool relative: false}) { - if (relative) { - // Relative junction points are not supported on Windows. Instead, just - // make sure we have a clean absolute path because it will interpret a - // relative path to be relative to the cwd, not the symlink, and will be - // confused by forward slashes. - if (Platform.operatingSystem == 'windows') { - target = path.normalize(path.absolute(target)); - } else { - // If the directory where we're creating the symlink was itself reached - // by traversing a symlink, we want the relative path to be relative to - // it's actual location, not the one we went through to get to it. - var symlinkDir = canonicalize(path.dirname(symlink)); - target = path.normalize(path.relative(target, from: symlinkDir)); - } - } - - log.fine("Creating $symlink pointing to $target"); - new Link(symlink).createSync(target); -} - -/// Creates a new symlink that creates an alias at [symlink] that points to the -/// `lib` directory of package [target]. -/// -/// If [target] does not have a `lib` directory, this shows a warning if -/// appropriate and then does nothing. -/// -/// If [relative] is true, creates a symlink with a relative path from the -/// symlink to the target. Otherwise, uses the [target] path unmodified. -void createPackageSymlink(String name, String target, String symlink, - {bool isSelfLink: false, bool relative: false}) { - // See if the package has a "lib" directory. If not, there's nothing to - // symlink to. - target = path.join(target, 'lib'); - if (!dirExists(target)) return; - - log.fine("Creating ${isSelfLink ? "self" : ""}link for package '$name'."); - createSymlink(target, symlink, relative: relative); -} - -/// Whether pub is running from within the Dart SDK, as opposed to from the Dart -/// source repository. -final bool runningFromSdk = Platform.script.path.endsWith('.snapshot'); - -/// Resolves [target] relative to the path to pub's `asset` directory. -String assetPath(String target) { - if (runningFromSdk) { - return path.join( - sdk.rootDirectory, - 'lib', - '_internal', - 'pub', - 'asset', - target); - } else { - return path.join(pubRoot, 'asset', target); - } -} - -/// Returns the path to the root of pub's sources in the Dart repo. -String get pubRoot => path.join(repoRoot, 'sdk', 'lib', '_internal', 'pub'); - -/// Returns the path to the root of the Dart repository. -/// -/// This throws a [StateError] if it's called when running pub from the SDK. -String get repoRoot { - if (runningFromSdk) { - throw new StateError("Can't get the repo root from the SDK."); - } - - // Get the path to the directory containing this very file. - var libDir = path.dirname(libraryPath('pub.io')); - - // TODO(rnystrom): Remove this when #104 is fixed. - // If we are running from the async/await compiled build directory, walk out - // out of that. It will be something like: - // - // ///pub_async/lib/src - if (libDir.contains('pub_async')) { - return path.normalize(path.join(libDir, '..', '..', '..', '..', '..')); - } - - // Otherwise, assume we're running directly from the source location in the - // repo: - // - // /sdk/lib/_internal/pub/lib/src - return path.normalize(path.join(libDir, '..', '..', '..', '..', '..', '..')); -} - -/// A line-by-line stream of standard input. -final Stream stdinLines = - streamToLines(new ByteStream(stdin).toStringStream()); - -/// Displays a message and reads a yes/no confirmation from the user. -/// -/// Returns a [Future] that completes to `true` if the user confirms or `false` -/// if they do not. -/// -/// This will automatically append " (y/n)?" to the message, so [message] -/// should just be a fragment like, "Are you sure you want to proceed". -Future confirm(String message) { - log.fine('Showing confirm message: $message'); - if (runningAsTest) { - log.message("$message (y/n)?"); - } else { - stdout.write(log.format("$message (y/n)? ")); - } - return streamFirst( - stdinLines).then((line) => new RegExp(r"^[yY]").hasMatch(line)); -} - -/// Reads and discards all output from [stream]. -/// -/// Returns a [Future] that completes when the stream is closed. -Future drainStream(Stream stream) { - return stream.fold(null, (x, y) {}); -} - -/// Flushes the stdout and stderr streams, then exits the program with the given -/// status code. -/// -/// This returns a Future that will never complete, since the program will have -/// exited already. This is useful to prevent Future chains from proceeding -/// after you've decided to exit. -Future flushThenExit(int status) { - return Future.wait( - [stdout.close(), stderr.close()]).then((_) => exit(status)); -} - -/// Returns a [EventSink] that pipes all data to [consumer] and a [Future] that -/// will succeed when [EventSink] is closed or fail with any errors that occur -/// while writing. -Pair consumerToSink(StreamConsumer consumer) { - var controller = new StreamController(sync: true); - var done = controller.stream.pipe(consumer); - return new Pair(controller.sink, done); -} - -// TODO(nweiz): remove this when issue 7786 is fixed. -/// Pipes all data and errors from [stream] into [sink]. -/// -/// When [stream] is done, the returned [Future] is completed and [sink] is -/// closed if [closeSink] is true. -/// -/// When an error occurs on [stream], that error is passed to [sink]. If -/// [cancelOnError] is true, [Future] will be completed successfully and no -/// more data or errors will be piped from [stream] to [sink]. If -/// [cancelOnError] and [closeSink] are both true, [sink] will then be -/// closed. -Future store(Stream stream, EventSink sink, {bool cancelOnError: true, - bool closeSink: true}) { - var completer = new Completer(); - stream.listen(sink.add, onError: (e, stackTrace) { - sink.addError(e, stackTrace); - if (cancelOnError) { - completer.complete(); - if (closeSink) sink.close(); - } - }, onDone: () { - if (closeSink) sink.close(); - completer.complete(); - }, cancelOnError: cancelOnError); - return completer.future; -} - -/// Spawns and runs the process located at [executable], passing in [args]. -/// -/// Returns a [Future] that will complete with the results of the process after -/// it has ended. -/// -/// The spawned process will inherit its parent's environment variables. If -/// [environment] is provided, that will be used to augment (not replace) the -/// the inherited variables. -Future runProcess(String executable, List args, - {workingDir, Map environment}) { - return _descriptorPool.withResource(() { - return _doProcess( - Process.run, - executable, - args, - workingDir, - environment).then((result) { - var pubResult = - new PubProcessResult(result.stdout, result.stderr, result.exitCode); - log.processResult(executable, pubResult); - return pubResult; - }); - }); -} - -/// Spawns the process located at [executable], passing in [args]. -/// -/// Returns a [Future] that will complete with the [Process] once it's been -/// started. -/// -/// The spawned process will inherit its parent's environment variables. If -/// [environment] is provided, that will be used to augment (not replace) the -/// the inherited variables. -Future startProcess(String executable, List args, - {workingDir, Map environment}) { - return _descriptorPool.request().then((resource) { - return _doProcess( - Process.start, - executable, - args, - workingDir, - environment).then((ioProcess) { - var process = new PubProcess(ioProcess); - process.exitCode.whenComplete(resource.release); - return process; - }); - }); -} - -/// Like [runProcess], but synchronous. -PubProcessResult runProcessSync(String executable, List args, - {String workingDir, Map environment}) { - var result = - _doProcess(Process.runSync, executable, args, workingDir, environment); - var pubResult = - new PubProcessResult(result.stdout, result.stderr, result.exitCode); - log.processResult(executable, pubResult); - return pubResult; -} - -/// A wrapper around [Process] that exposes `dart:async`-style APIs. -class PubProcess { - /// The underlying `dart:io` [Process]. - final Process _process; - - /// The mutable field for [stdin]. - EventSink> _stdin; - - /// The mutable field for [stdinClosed]. - Future _stdinClosed; - - /// The mutable field for [stdout]. - ByteStream _stdout; - - /// The mutable field for [stderr]. - ByteStream _stderr; - - /// The mutable field for [exitCode]. - Future _exitCode; - - /// The sink used for passing data to the process's standard input stream. - /// - /// Errors on this stream are surfaced through [stdinClosed], [stdout], - /// [stderr], and [exitCode], which are all members of an [ErrorGroup]. - EventSink> get stdin => _stdin; - - // TODO(nweiz): write some more sophisticated Future machinery so that this - // doesn't surface errors from the other streams/futures, but still passes its - // unhandled errors to them. Right now it's impossible to recover from a stdin - // error and continue interacting with the process. - /// A [Future] that completes when [stdin] is closed, either by the user or by - /// the process itself. - /// - /// This is in an [ErrorGroup] with [stdout], [stderr], and [exitCode], so any - /// error in process will be passed to it, but won't reach the top-level error - /// handler unless nothing has handled it. - Future get stdinClosed => _stdinClosed; - - /// The process's standard output stream. - /// - /// This is in an [ErrorGroup] with [stdinClosed], [stderr], and [exitCode], - /// so any error in process will be passed to it, but won't reach the - /// top-level error handler unless nothing has handled it. - ByteStream get stdout => _stdout; - - /// The process's standard error stream. - /// - /// This is in an [ErrorGroup] with [stdinClosed], [stdout], and [exitCode], - /// so any error in process will be passed to it, but won't reach the - /// top-level error handler unless nothing has handled it. - ByteStream get stderr => _stderr; - - /// A [Future] that will complete to the process's exit code once the process - /// has finished running. - /// - /// This is in an [ErrorGroup] with [stdinClosed], [stdout], and [stderr], so - /// any error in process will be passed to it, but won't reach the top-level - /// error handler unless nothing has handled it. - Future get exitCode => _exitCode; - - /// Creates a new [PubProcess] wrapping [process]. - PubProcess(Process process) - : _process = process { - var errorGroup = new ErrorGroup(); - - var pair = consumerToSink(process.stdin); - _stdin = pair.first; - _stdinClosed = errorGroup.registerFuture(pair.last); - - _stdout = new ByteStream(errorGroup.registerStream(process.stdout)); - _stderr = new ByteStream(errorGroup.registerStream(process.stderr)); - - var exitCodeCompleter = new Completer(); - _exitCode = errorGroup.registerFuture(exitCodeCompleter.future); - _process.exitCode.then((code) => exitCodeCompleter.complete(code)); - } - - /// Sends [signal] to the underlying process. - bool kill([ProcessSignal signal = ProcessSignal.SIGTERM]) => - _process.kill(signal); -} - -/// Calls [fn] with appropriately modified arguments. -/// -/// [fn] should have the same signature as [Process.start], except that the -/// returned value may have any return type. -_doProcess(Function fn, String executable, List args, String workingDir, - Map environment) { - // TODO(rnystrom): Should dart:io just handle this? - // Spawning a process on Windows will not look for the executable in the - // system path. So, if executable looks like it needs that (i.e. it doesn't - // have any path separators in it), then spawn it through a shell. - if ((Platform.operatingSystem == "windows") && - (executable.indexOf('\\') == -1)) { - args = flatten(["/c", executable, args]); - executable = "cmd"; - } - - log.process(executable, args, workingDir == null ? '.' : workingDir); - - return fn( - executable, - args, - workingDirectory: workingDir, - environment: environment); -} - -/// Wraps [input], an asynchronous network operation to provide a timeout. -/// -/// If [input] completes before [milliseconds] have passed, then the return -/// value completes in the same way. However, if [milliseconds] pass before -/// [input] has completed, it completes with a [TimeoutException] with -/// [description] (which should be a fragment describing the action that timed -/// out). -/// -/// [url] is the URL being accessed asynchronously. -/// -/// Note that timing out will not cancel the asynchronous operation behind -/// [input]. -Future timeout(Future input, int milliseconds, Uri url, String description) { - // TODO(nwiez): Replace this with [Future.timeout]. - var completer = new Completer(); - var duration = new Duration(milliseconds: milliseconds); - var timer = new Timer(duration, () { - // Include the duration ourselves in the message instead of passing it to - // TimeoutException since we show nicer output. - var message = - 'Timed out after ${niceDuration(duration)} while ' '$description.'; - - if (url.host == "pub.dartlang.org" || - url.host == "storage.googleapis.com") { - message += "\nThis is likely a transient error. Please try again later."; - } - - completer.completeError(new TimeoutException(message), new Chain.current()); - }); - input.then((value) { - if (completer.isCompleted) return; - timer.cancel(); - completer.complete(value); - }).catchError((e, stackTrace) { - if (completer.isCompleted) return; - timer.cancel(); - completer.completeError(e, stackTrace); - }); - return completer.future; -} - -/// Creates a temporary directory and passes its path to [fn]. -/// -/// Once the [Future] returned by [fn] completes, the temporary directory and -/// all its contents are deleted. [fn] can also return `null`, in which case -/// the temporary directory is deleted immediately afterwards. -/// -/// Returns a future that completes to the value that the future returned from -/// [fn] completes to. -Future withTempDir(Future fn(String path)) { - return new Future.sync(() { - var tempDir = createSystemTempDir(); - return new Future.sync( - () => fn(tempDir)).whenComplete(() => deleteEntry(tempDir)); - }); -} - -/// Binds an [HttpServer] to [host] and [port]. -/// -/// If [host] is "localhost", this will automatically listen on both the IPv4 -/// and IPv6 loopback addresses. -Future bindServer(String host, int port) { - if (host == 'localhost') return HttpMultiServer.loopback(port); - return HttpServer.bind(host, port); -} - -/// Extracts a `.tar.gz` file from [stream] to [destination]. -/// -/// Returns whether or not the extraction was successful. -Future extractTarGz(Stream> stream, String destination) { - log.fine("Extracting .tar.gz stream to $destination."); - - if (Platform.operatingSystem == "windows") { - return _extractTarGzWindows(stream, destination); - } - - var args = ["--extract", "--gunzip", "--directory", destination]; - if (_noUnknownKeyword) { - // BSD tar (the default on OS X) can insert strange headers to a tarfile - // that GNU tar (the default on Linux) is unable to understand. This will - // cause GNU tar to emit a number of harmless but scary-looking warnings - // which are silenced by this flag. - args.insert(0, "--warning=no-unknown-keyword"); - } - - return startProcess("tar", args).then((process) { - // Ignore errors on process.std{out,err}. They'll be passed to - // process.exitCode, and we don't want them being top-levelled by - // std{out,err}Sink. - store(process.stdout.handleError((_) {}), stdout, closeSink: false); - store(process.stderr.handleError((_) {}), stderr, closeSink: false); - return Future.wait([store(stream, process.stdin), process.exitCode]); - }).then((results) { - var exitCode = results[1]; - if (exitCode != exit_codes.SUCCESS) { - throw new Exception( - "Failed to extract .tar.gz stream to $destination " "(exit code $exitCode)."); - } - log.fine("Extracted .tar.gz stream to $destination. Exit code $exitCode."); - }); -} - -/// Whether to include "--warning=no-unknown-keyword" when invoking tar. -/// -/// This flag quiets warnings that come from opening OS X-generated tarballs on -/// Linux, but only GNU tar >= 1.26 supports it. -final bool _noUnknownKeyword = _computeNoUnknownKeyword(); -bool _computeNoUnknownKeyword() { - if (!Platform.isLinux) return false; - var result = Process.runSync("tar", ["--version"]); - if (result.exitCode != 0) { - throw new ApplicationException( - "Failed to run tar (exit code ${result.exitCode}):\n${result.stderr}"); - } - - var match = - new RegExp(r"^tar \(GNU tar\) (\d+).(\d+)\n").firstMatch(result.stdout); - if (match == null) return false; - - var major = int.parse(match[1]); - var minor = int.parse(match[2]); - return major >= 2 || (major == 1 && minor >= 23); -} - -String get pathTo7zip { - if (runningFromSdk) return assetPath(path.join('7zip', '7za.exe')); - return path.join(repoRoot, 'third_party', '7zip', '7za.exe'); -} - -Future _extractTarGzWindows(Stream> stream, String destination) - { - // TODO(rnystrom): In the repo's history, there is an older implementation of - // this that does everything in memory by piping streams directly together - // instead of writing out temp files. The code is simpler, but unfortunately, - // 7zip seems to periodically fail when we invoke it from Dart and tell it to - // read from stdin instead of a file. Consider resurrecting that version if - // we can figure out why it fails. - - return withTempDir((tempDir) { - // Write the archive to a temp file. - var dataFile = path.join(tempDir, 'data.tar.gz'); - return createFileFromStream(stream, dataFile).then((_) { - // 7zip can't unarchive from gzip -> tar -> destination all in one step - // first we un-gzip it to a tar file. - // Note: Setting the working directory instead of passing in a full file - // path because 7zip says "A full path is not allowed here." - return runProcess(pathTo7zip, ['e', 'data.tar.gz'], workingDir: tempDir); - }).then((result) { - if (result.exitCode != exit_codes.SUCCESS) { - throw new Exception( - 'Could not un-gzip (exit code ${result.exitCode}). ' 'Error:\n' - '${result.stdout.join("\n")}\n' '${result.stderr.join("\n")}'); - } - - // Find the tar file we just created since we don't know its name. - var tarFile = listDir( - tempDir).firstWhere((file) => path.extension(file) == '.tar', orElse: () { - throw new FormatException('The gzip file did not contain a tar file.'); - }); - - // Untar the archive into the destination directory. - return runProcess(pathTo7zip, ['x', tarFile], workingDir: destination); - }).then((result) { - if (result.exitCode != exit_codes.SUCCESS) { - throw new Exception( - 'Could not un-tar (exit code ${result.exitCode}). ' 'Error:\n' - '${result.stdout.join("\n")}\n' '${result.stderr.join("\n")}'); - } - return true; - }); - }); -} - -/// Create a .tar.gz archive from a list of entries. -/// -/// Each entry can be a [String], [Directory], or [File] object. The root of -/// the archive is considered to be [baseDir], which defaults to the current -/// working directory. -/// -/// Returns a [ByteStream] that emits the contents of the archive. -ByteStream createTarGz(List contents, {baseDir}) { - return new ByteStream(futureStream(new Future.sync(() { - var buffer = new StringBuffer(); - buffer.write('Creating .tag.gz stream containing:\n'); - contents.forEach((file) => buffer.write('$file\n')); - log.fine(buffer.toString()); - - if (baseDir == null) baseDir = path.current; - baseDir = path.absolute(baseDir); - contents = contents.map((entry) { - entry = path.absolute(entry); - if (!path.isWithin(baseDir, entry)) { - throw new ArgumentError('Entry $entry is not inside $baseDir.'); - } - return path.relative(entry, from: baseDir); - }).toList(); - - if (Platform.operatingSystem != "windows") { - var args = ["--create", "--gzip", "--directory", baseDir]; - args.addAll(contents); - // TODO(nweiz): It's possible that enough command-line arguments will - // make the process choke, so at some point we should save the arguments - // to a file and pass them in via --files-from for tar and -i@filename - // for 7zip. - return startProcess("tar", args).then((process) => process.stdout); - } - - // Don't use [withTempDir] here because we don't want to delete the temp - // directory until the returned stream has closed. - var tempDir = createSystemTempDir(); - return new Future.sync(() { - // Create the tar file. - var tarFile = path.join(tempDir, "intermediate.tar"); - var args = ["a", "-w$baseDir", tarFile]; - args.addAll(contents.map((entry) => '-i!$entry')); - - // We're passing 'baseDir' both as '-w' and setting it as the working - // directory explicitly here intentionally. The former ensures that the - // files added to the archive have the correct relative path in the - // archive. The latter enables relative paths in the "-i" args to be - // resolved. - return runProcess(pathTo7zip, args, workingDir: baseDir).then((_) { - // GZIP it. 7zip doesn't support doing both as a single operation. - // Send the output to stdout. - args = ["a", "unused", "-tgzip", "-so", tarFile]; - return startProcess(pathTo7zip, args); - }).then((process) => process.stdout); - }).then((stream) { - return stream.transform(onDoneTransformer(() => deleteEntry(tempDir))); - }).catchError((e) { - deleteEntry(tempDir); - throw e; - }); - }))); -} - -/// Contains the results of invoking a [Process] and waiting for it to complete. -class PubProcessResult { - final List stdout; - final List stderr; - final int exitCode; - - PubProcessResult(String stdout, String stderr, this.exitCode) - : this.stdout = _toLines(stdout), - this.stderr = _toLines(stderr); - - // TODO(rnystrom): Remove this and change to returning one string. - static List _toLines(String output) { - var lines = splitLines(output); - if (!lines.isEmpty && lines.last == "") lines.removeLast(); - return lines; - } - - bool get success => exitCode == exit_codes.SUCCESS; -} - -/// Gets a [Uri] for [uri], which can either already be one, or be a [String]. -Uri _getUri(uri) { - if (uri is Uri) return uri; - return Uri.parse(uri); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/lock_file.dart b/sdk/lib/_internal/pub_generated/lib/src/lock_file.dart deleted file mode 100644 index fa964c70f80..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/lock_file.dart +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.lock_file; - -import 'package:path/path.dart' as p; -import 'package:pub_semver/pub_semver.dart'; -import 'package:source_span/source_span.dart'; -import 'package:yaml/yaml.dart'; - -import 'io.dart'; -import 'package.dart'; -import 'source_registry.dart'; -import 'utils.dart'; - -/// A parsed and validated `pubspec.lock` file. -class LockFile { - /// The packages this lockfile pins. - Map packages; - - /// Creates a new lockfile containing [ids]. - factory LockFile(List ids) { - var lockFile = new LockFile.empty(); - for (var id in ids) { - if (!id.isRoot) lockFile.packages[id.name] = id; - } - - return lockFile; - } - - LockFile._(this.packages); - - LockFile.empty() - : packages = {}; - - /// Loads a lockfile from [filePath]. - factory LockFile.load(String filePath, SourceRegistry sources) { - return LockFile._parse(filePath, readTextFile(filePath), sources); - } - - /// Parses a lockfile whose text is [contents]. - factory LockFile.parse(String contents, SourceRegistry sources) { - return LockFile._parse(null, contents, sources); - } - - /// Parses the lockfile whose text is [contents]. - /// - /// [filePath] is the system-native path to the lockfile on disc. It may be - /// `null`. - static LockFile _parse(String filePath, String contents, - SourceRegistry sources) { - var packages = {}; - - if (contents.trim() == '') return new LockFile.empty(); - - var sourceUrl; - if (filePath != null) sourceUrl = p.toUri(filePath); - var parsed = loadYamlNode(contents, sourceUrl: sourceUrl); - - _validate(parsed is Map, 'The lockfile must be a YAML mapping.', parsed); - - var packageEntries = parsed['packages']; - if (packageEntries != null) { - _validate( - packageEntries is Map, - 'The "packages" field must be a map.', - parsed.nodes['packages']); - - packageEntries.forEach((name, spec) { - // Parse the version. - _validate( - spec.containsKey('version'), - 'Package $name is missing a version.', - spec); - var version = new Version.parse(spec['version']); - - // Parse the source. - _validate( - spec.containsKey('source'), - 'Package $name is missing a source.', - spec); - var sourceName = spec['source']; - - _validate( - spec.containsKey('description'), - 'Package $name is missing a description.', - spec); - var description = spec['description']; - - // Let the source parse the description. - var source = sources[sourceName]; - try { - description = - source.parseDescription(filePath, description, fromLockFile: true); - } on FormatException catch (ex) { - throw new SourceSpanFormatException( - ex.message, - spec.nodes['source'].span); - } - - var id = new PackageId(name, sourceName, version, description); - - // Validate the name. - _validate( - name == id.name, - "Package name $name doesn't match ${id.name}.", - spec); - - packages[name] = id; - }); - } - - return new LockFile._(packages); - } - - /// If [condition] is `false` throws a format error with [message] for [node]. - static void _validate(bool condition, String message, YamlNode node) { - if (condition) return; - throw new SourceSpanFormatException(message, node.span); - } - - /// Returns the serialized YAML text of the lock file. - /// - /// [packageDir] is the containing directory of the root package, used to - /// properly serialize package descriptions. - String serialize(String packageDir, SourceRegistry sources) { - // Convert the dependencies to a simple object. - var data = {}; - packages.forEach((name, package) { - var description = - sources[package.source].serializeDescription(packageDir, package.description); - - data[name] = { - 'version': package.version.toString(), - 'source': package.source, - 'description': description - }; - }); - - return """ -# Generated by pub -# See http://pub.dartlang.org/doc/glossary.html#lockfile -${yamlToString({'packages': data})} -"""; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/log.dart b/sdk/lib/_internal/pub_generated/lib/src/log.dart deleted file mode 100644 index ecf67ed2c05..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/log.dart +++ /dev/null @@ -1,551 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Message logging. -library pub.log; - -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:args/command_runner.dart'; -import 'package:path/path.dart' as p; -import 'package:source_span/source_span.dart'; -import 'package:stack_trace/stack_trace.dart'; - -import 'exceptions.dart'; -import 'io.dart'; -import 'progress.dart'; -import 'transcript.dart'; -import 'utils.dart'; - -/// The singleton instance so that we can have a nice api like: -/// -/// log.json.error(...); -final json = new _JsonLogger(); - -/// The current logging verbosity. -Verbosity verbosity = Verbosity.NORMAL; - -/// Whether or not to log entries with prejudice. -bool withPrejudice = false; - -/// In cases where there's a ton of log spew, make sure we don't eat infinite -/// memory. -/// -/// This can occur when the backtracking solver stumbles into a pathological -/// dependency graph. It generally will find a solution, but it may log -/// thousands and thousands of entries to get there. -const _MAX_TRANSCRIPT = 10000; - -/// The list of recorded log messages. Will only be recorded if -/// [recordTranscript()] is called. -Transcript _transcript; - -/// The currently-animated progress indicator, if any. -/// -/// This will also be in [_progresses]. -Progress _animatedProgress; - -final _cyan = getSpecial('\u001b[36m'); -final _green = getSpecial('\u001b[32m'); -final _magenta = getSpecial('\u001b[35m'); -final _red = getSpecial('\u001b[31m'); -final _yellow = getSpecial('\u001b[33m'); -final _gray = getSpecial('\u001b[1;30m'); -final _none = getSpecial('\u001b[0m'); -final _noColor = getSpecial('\u001b[39m'); -final _bold = getSpecial('\u001b[1m'); - -/// An enum type for defining the different logging levels a given message can -/// be associated with. -/// -/// By default, [ERROR] and [WARNING] messages are printed to sterr. [MESSAGE] -/// messages are printed to stdout, and others are ignored. -class Level { - /// An error occurred and an operation could not be completed. - /// - /// Usually shown to the user on stderr. - static const ERROR = const Level._("ERR "); - - /// Something unexpected happened, but the program was able to continue, - /// though possibly in a degraded fashion. - static const WARNING = const Level._("WARN"); - - /// A message intended specifically to be shown to the user. - static const MESSAGE = const Level._("MSG "); - - /// Some interaction with the external world occurred, such as a network - /// operation, process spawning, or file IO. - static const IO = const Level._("IO "); - - /// Incremental output during pub's version constraint solver. - static const SOLVER = const Level._("SLVR"); - - /// Fine-grained and verbose additional information. - /// - /// Used to provide program state context for other logs (such as what pub - /// was doing when an IO operation occurred) or just more detail for an - /// operation. - static const FINE = const Level._("FINE"); - - const Level._(this.name); - final String name; - - String toString() => name; -} - -typedef _LogFn(Entry entry); - -/// An enum type to control which log levels are displayed and how they are -/// displayed. -class Verbosity { - /// Silence all logging. - static const NONE = const Verbosity._("none", const { - Level.ERROR: null, - Level.WARNING: null, - Level.MESSAGE: null, - Level.IO: null, - Level.SOLVER: null, - Level.FINE: null - }); - - /// Shows only errors and warnings. - static const WARNING = const Verbosity._("warning", const { - Level.ERROR: _logToStderr, - Level.WARNING: _logToStderr, - Level.MESSAGE: null, - Level.IO: null, - Level.SOLVER: null, - Level.FINE: null - }); - - /// The default verbosity which shows errors, warnings, and messages. - static const NORMAL = const Verbosity._("normal", const { - Level.ERROR: _logToStderr, - Level.WARNING: _logToStderr, - Level.MESSAGE: _logToStdout, - Level.IO: null, - Level.SOLVER: null, - Level.FINE: null - }); - - /// Shows errors, warnings, messages, and IO event logs. - static const IO = const Verbosity._("io", const { - Level.ERROR: _logToStderrWithLabel, - Level.WARNING: _logToStderrWithLabel, - Level.MESSAGE: _logToStdoutWithLabel, - Level.IO: _logToStderrWithLabel, - Level.SOLVER: null, - Level.FINE: null - }); - - /// Shows errors, warnings, messages, and version solver logs. - static const SOLVER = const Verbosity._("solver", const { - Level.ERROR: _logToStderr, - Level.WARNING: _logToStderr, - Level.MESSAGE: _logToStdout, - Level.IO: null, - Level.SOLVER: _logToStdout, - Level.FINE: null - }); - - /// Shows all logs. - static const ALL = const Verbosity._("all", const { - Level.ERROR: _logToStderrWithLabel, - Level.WARNING: _logToStderrWithLabel, - Level.MESSAGE: _logToStdoutWithLabel, - Level.IO: _logToStderrWithLabel, - Level.SOLVER: _logToStderrWithLabel, - Level.FINE: _logToStderrWithLabel - }); - - const Verbosity._(this.name, this._loggers); - final String name; - final Map _loggers; - - /// Returns whether or not logs at [level] will be printed. - bool isLevelVisible(Level level) => _loggers[level] != null; - - String toString() => name; -} - -/// A single log entry. -class Entry { - final Level level; - final List lines; - - Entry(this.level, this.lines); -} - -/// Logs [message] at [Level.ERROR]. -/// -/// If [error] is passed, it's appended to [message]. If [trace] is passed, it's -/// printed at log level fine. -void error(message, [error, StackTrace trace]) { - if (error != null) { - message = "$message: $error"; - if (error is Error && trace == null) trace = error.stackTrace; - } - write(Level.ERROR, message); - if (trace != null) write(Level.FINE, new Chain.forTrace(trace)); -} - -/// Logs [message] at [Level.WARNING]. -void warning(message) => write(Level.WARNING, message); - -/// Logs [message] at [Level.MESSAGE]. -void message(message) => write(Level.MESSAGE, message); - -/// Logs [message] at [Level.IO]. -void io(message) => write(Level.IO, message); - -/// Logs [message] at [Level.SOLVER]. -void solver(message) => write(Level.SOLVER, message); - -/// Logs [message] at [Level.FINE]. -void fine(message) => write(Level.FINE, message); - -/// Logs [message] at [level]. -void write(Level level, message) { - message = message.toString(); - var lines = splitLines(message); - - // Discard a trailing newline. This is useful since StringBuffers often end - // up with an extra newline at the end from using [writeln]. - if (lines.isNotEmpty && lines.last == "") { - lines.removeLast(); - } - - var entry = new Entry(level, lines.map(format).toList()); - - var logFn = verbosity._loggers[level]; - if (logFn != null) logFn(entry); - - if (_transcript != null) _transcript.add(entry); -} - -final _capitalizedAnsiEscape = new RegExp(r'\u001b\[\d+(;\d+)?M'); - -/// Returns [string] formatted as it would be if it were logged. -String format(String string) { - if (!withPrejudice) return string; - - // [toUpperCase] can corrupt terminal colorings, so fix them up using - // [replaceAllMapped]. - string = string.toUpperCase().replaceAllMapped( - _capitalizedAnsiEscape, - (match) => match[0].toLowerCase()); - - // Don't use [bold] because it's disabled under [withPrejudice]. - return "$_bold$string$_none"; -} - -/// Logs an asynchronous IO operation. -/// -/// Logs [startMessage] before the operation starts, then when [operation] -/// completes, invokes [endMessage] with the completion value and logs the -/// result of that. Returns a future that completes after the logging is done. -/// -/// If [endMessage] is omitted, then logs "Begin [startMessage]" before the -/// operation and "End [startMessage]" after it. -Future ioAsync(String startMessage, Future operation, [String - endMessage(value)]) { - if (endMessage == null) { - io("Begin $startMessage."); - } else { - io(startMessage); - } - - return operation.then((result) { - if (endMessage == null) { - io("End $startMessage."); - } else { - io(endMessage(result)); - } - return result; - }); -} - -/// Logs the spawning of an [executable] process with [arguments] at [IO] -/// level. -void process(String executable, List arguments, String workingDirectory) - { - io( - "Spawning \"$executable ${arguments.join(' ')}\" in " - "${p.absolute(workingDirectory)}"); -} - -/// Logs the results of running [executable]. -void processResult(String executable, PubProcessResult result) { - // Log it all as one message so that it shows up as a single unit in the logs. - var buffer = new StringBuffer(); - buffer.writeln("Finished $executable. Exit code ${result.exitCode}."); - - dumpOutput(String name, List output) { - if (output.length == 0) { - buffer.writeln("Nothing output on $name."); - } else { - buffer.writeln("$name:"); - var numLines = 0; - for (var line in output) { - if (++numLines > 1000) { - buffer.writeln( - '[${output.length - 1000}] more lines of output ' 'truncated...]'); - break; - } - - buffer.writeln("| $line"); - } - } - } - - dumpOutput("stdout", result.stdout); - dumpOutput("stderr", result.stderr); - - io(buffer.toString().trim()); -} - -/// Logs an exception. -void exception(exception, [StackTrace trace]) { - if (exception is SilentException) return; - - var chain = trace == null ? new Chain.current() : new Chain.forTrace(trace); - - // This is basically the top-level exception handler so that we don't - // spew a stack trace on our users. - if (exception is SourceSpanException) { - error(exception.toString(color: canUseSpecialChars)); - } else { - error(getErrorMessage(exception)); - } - fine("Exception type: ${exception.runtimeType}"); - - if (json.enabled) { - if (exception is UsageException) { - // Don't print usage info in JSON output. - json.error(exception.message); - } else { - json.error(exception); - } - } - - if (!isUserFacingException(exception)) { - error(chain.terse); - } else { - fine(chain.terse); - } - - if (exception is WrappedException && exception.innerError != null) { - var message = "Wrapped exception: ${exception.innerError}"; - if (exception.innerChain != null) { - message = "$message\n${exception.innerChain}"; - } - fine(message); - } -} - -/// Enables recording of log entries. -void recordTranscript() { - _transcript = new Transcript(_MAX_TRANSCRIPT); -} - -/// If [recordTranscript()] was called, then prints the previously recorded log -/// transcript to stderr. -void dumpTranscript() { - if (_transcript == null) return; - - stderr.writeln('---- Log transcript ----'); - _transcript.forEach((entry) { - _printToStream(stderr, entry, showLabel: true); - }, (discarded) { - stderr.writeln('---- ($discarded discarded) ----'); - }); - stderr.writeln('---- End log transcript ----'); -} - -/// Prints [message] then displays an updated elapsed time until the future -/// returned by [callback] completes. -/// -/// If anything else is logged during this (including another call to -/// [progress]) that cancels the progress animation, although the total time -/// will still be printed once it finishes. If [fine] is passed, the progress -/// information will only be visible at [Level.FINE]. -Future progress(String message, Future callback(), {bool fine: false}) { - _stopProgress(); - - var progress = new Progress(message, fine: fine); - _animatedProgress = progress; - return callback().whenComplete(progress.stop); -} - -/// Stops animating the running progress indicator, if currently running. -void _stopProgress() { - if (_animatedProgress != null) _animatedProgress.stopAnimating(); - _animatedProgress = null; -} - -/// The number of outstanding calls to [muteProgress] that have not been unmuted -/// yet. -int _numMutes = 0; - -/// Whether progress animation should be muted or not. -bool get isMuted => _numMutes > 0; - -/// Stops animating any ongoing progress. -/// -/// This is called before spawning Git since Git sometimes writes directly to -/// the terminal to ask for login credentials, which would then get overwritten -/// by the progress animation. -/// -/// Each call to this must be paired with a call to [unmuteProgress]. -void muteProgress() { - _numMutes++; -} - -/// Resumes animating any ongoing progress once all calls to [muteProgress] -/// have made their matching [unmuteProgress]. -void unmuteProgress() { - assert(_numMutes > 0); - _numMutes--; -} - -/// Wraps [text] in the ANSI escape codes to make it bold when on a platform -/// that supports that. -/// -/// Use this to highlight the most important piece of a long chunk of text. -/// -/// This is disabled under [withPrejudice] since all text is bold with -/// prejudice. -String bold(text) => withPrejudice ? text : "$_bold$text$_none"; - -/// Wraps [text] in the ANSI escape codes to make it gray when on a platform -/// that supports that. -/// -/// Use this for text that's less important than the text around it. -/// -/// The gray marker also enables bold, so it needs to be handled specially with -/// [withPrejudice] to avoid disabling bolding entirely. -String gray(text) => - withPrejudice ? "$_gray$text$_noColor" : "$_gray$text$_none"; - -/// Wraps [text] in the ANSI escape codes to color it cyan when on a platform -/// that supports that. -/// -/// Use this to highlight something interesting but neither good nor bad. -String cyan(text) => "$_cyan$text$_noColor"; - -/// Wraps [text] in the ANSI escape codes to color it green when on a platform -/// that supports that. -/// -/// Use this to highlight something successful or otherwise positive. -String green(text) => "$_green$text$_noColor"; - -/// Wraps [text] in the ANSI escape codes to color it magenta when on a -/// platform that supports that. -/// -/// Use this to highlight something risky that the user should be aware of but -/// may intend to do. -String magenta(text) => "$_magenta$text$_noColor"; - -/// Wraps [text] in the ANSI escape codes to color it red when on a platform -/// that supports that. -/// -/// Use this to highlight unequivocal errors, problems, or failures. -String red(text) => "$_red$text$_noColor"; - -/// Wraps [text] in the ANSI escape codes to color it yellow when on a platform -/// that supports that. -/// -/// Use this to highlight warnings, cautions or other things that are bad but -/// do not prevent the user's goal from being reached. -String yellow(text) => "$_yellow$text$_noColor"; - -/// Log function that prints the message to stdout. -void _logToStdout(Entry entry) { - _logToStream(stdout, entry, showLabel: false); -} - -/// Log function that prints the message to stdout with the level name. -void _logToStdoutWithLabel(Entry entry) { - _logToStream(stdout, entry, showLabel: true); -} - -/// Log function that prints the message to stderr. -void _logToStderr(Entry entry) { - _logToStream(stderr, entry, showLabel: false); -} - -/// Log function that prints the message to stderr with the level name. -void _logToStderrWithLabel(Entry entry) { - _logToStream(stderr, entry, showLabel: true); -} - -void _logToStream(IOSink sink, Entry entry, {bool showLabel}) { - if (json.enabled) return; - - _printToStream(sink, entry, showLabel: showLabel); -} - -void _printToStream(IOSink sink, Entry entry, {bool showLabel}) { - _stopProgress(); - - bool firstLine = true; - for (var line in entry.lines) { - if (showLabel) { - if (firstLine) { - sink.write('${entry.level.name}: '); - } else { - sink.write(' | '); - } - } - - sink.writeln(line); - - firstLine = false; - } -} - -/// Namespace-like class for collecting the methods for JSON logging. -class _JsonLogger { - /// Whether logging should use machine-friendly JSON output or human-friendly - /// text. - /// - /// If set to `true`, then no regular logging is printed. Logged messages - /// will still be recorded and displayed if the transcript is printed. - bool enabled = false; - - /// Creates an error JSON object for [error] and prints it if JSON output - /// is enabled. - /// - /// Always prints to stdout. - void error(error, [stackTrace]) { - var errorJson = { - "error": error.toString() - }; - - if (stackTrace == null && error is Error) stackTrace = error.stackTrace; - if (stackTrace != null) { - errorJson["stackTrace"] = new Chain.forTrace(stackTrace).toString(); - } - - // If the error came from a file, include the path. - if (error is SourceSpanException && error.span.sourceUrl != null) { - errorJson["path"] = p.fromUri(error.span.sourceUrl); - } - - if (error is FileException) { - errorJson["path"] = error.path; - } - - this.message(errorJson); - } - - /// Encodes [message] to JSON and prints it if JSON output is enabled. - void message(message) { - if (!enabled) return; - - print(JSON.encode(message)); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/oauth2.dart b/sdk/lib/_internal/pub_generated/lib/src/oauth2.dart deleted file mode 100644 index 6edac4b3596..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/oauth2.dart +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.oauth2; - -import 'dart:async'; -import 'dart:io'; - -import 'package:oauth2/oauth2.dart'; -import 'package:path/path.dart' as path; -import 'package:shelf/shelf.dart' as shelf; -import 'package:shelf/shelf_io.dart' as shelf_io; - -import 'http.dart'; -import 'io.dart'; -import 'log.dart' as log; -import 'system_cache.dart'; -import 'utils.dart'; - -export 'package:oauth2/oauth2.dart'; - -/// The pub client's OAuth2 identifier. -final _identifier = - '818368855108-8grd2eg9tj9f38os6f1urbcvsq399u8n.apps.' 'googleusercontent.com'; - -/// The pub client's OAuth2 secret. -/// -/// This isn't actually meant to be kept a secret. -final _secret = 'SWeqj8seoJW0w7_CpEPFLX0K'; - -/// The URL to which the user will be directed to authorize the pub client to -/// get an OAuth2 access token. -/// -/// `access_type=offline` and `approval_prompt=force` ensures that we always get -/// a refresh token from the server. See the [Google OAuth2 documentation][]. -/// -/// [Google OAuth2 documentation]: https://developers.google.com/accounts/docs/OAuth2WebServer#offline -final authorizationEndpoint = Uri.parse( - 'https://accounts.google.com/o/oauth2/auth?access_type=offline' - '&approval_prompt=force'); - -/// The URL from which the pub client will request an access token once it's -/// been authorized by the user. -/// -/// This can be controlled externally by setting the `_PUB_TEST_TOKEN_ENDPOINT` -/// environment variable. -Uri get tokenEndpoint { - var tokenEndpoint = Platform.environment['_PUB_TEST_TOKEN_ENDPOINT']; - if (tokenEndpoint != null) { - return Uri.parse(tokenEndpoint); - } else { - return _tokenEndpoint; - } -} - -final _tokenEndpoint = Uri.parse('https://accounts.google.com/o/oauth2/token'); - -/// The OAuth2 scopes that the pub client needs. -/// -/// Currently the client only needs the user's email so that the server can -/// verify their identity. -final _scopes = ['https://www.googleapis.com/auth/userinfo.email']; - -/// An in-memory cache of the user's OAuth2 credentials. -/// -/// This should always be the same as the credentials file stored in the system -/// cache. -Credentials _credentials; - -/// Delete the cached credentials, if they exist. -void clearCredentials(SystemCache cache) { - _credentials = null; - var credentialsFile = _credentialsFile(cache); - if (entryExists(credentialsFile)) deleteEntry(credentialsFile); -} - -/// Asynchronously passes an OAuth2 [Client] to [fn], and closes the client when -/// the [Future] returned by [fn] completes. -/// -/// This takes care of loading and saving the client's credentials, as well as -/// prompting the user for their authorization. It will also re-authorize and -/// re-run [fn] if a recoverable authorization error is detected. -Future withClient(SystemCache cache, Future fn(Client client)) { - return _getClient(cache).then((client) { - var completer = new Completer(); - return fn(client).whenComplete(() { - client.close(); - // Be sure to save the credentials even when an error happens. - _saveCredentials(cache, client.credentials); - }); - }).catchError((error) { - if (error is ExpirationException) { - log.error( - "Pub's authorization to upload packages has expired and " - "can't be automatically refreshed."); - return withClient(cache, fn); - } else if (error is AuthorizationException) { - var message = "OAuth2 authorization failed"; - if (error.description != null) { - message = "$message (${error.description})"; - } - log.error("$message."); - clearCredentials(cache); - return withClient(cache, fn); - } else { - throw error; - } - }); -} - -/// Gets a new OAuth2 client. -/// -/// If saved credentials are available, those are used; otherwise, the user is -/// prompted to authorize the pub client. -Future _getClient(SystemCache cache) { - return new Future.sync(() { - var credentials = _loadCredentials(cache); - if (credentials == null) return _authorize(); - - var client = - new Client(_identifier, _secret, credentials, httpClient: httpClient); - _saveCredentials(cache, client.credentials); - return client; - }); -} - -/// Loads the user's OAuth2 credentials from the in-memory cache or the -/// filesystem if possible. -/// -/// If the credentials can't be loaded for any reason, the returned [Future] -/// completes to `null`. -Credentials _loadCredentials(SystemCache cache) { - log.fine('Loading OAuth2 credentials.'); - - try { - if (_credentials != null) return _credentials; - - var path = _credentialsFile(cache); - if (!fileExists(path)) return null; - - var credentials = new Credentials.fromJson(readTextFile(path)); - if (credentials.isExpired && !credentials.canRefresh) { - log.error( - "Pub's authorization to upload packages has expired and " - "can't be automatically refreshed."); - return null; // null means re-authorize. - } - - return credentials; - } catch (e) { - log.error( - 'Warning: could not load the saved OAuth2 credentials: $e\n' - 'Obtaining new credentials...'); - return null; // null means re-authorize. - } -} - -/// Save the user's OAuth2 credentials to the in-memory cache and the -/// filesystem. -void _saveCredentials(SystemCache cache, Credentials credentials) { - log.fine('Saving OAuth2 credentials.'); - _credentials = credentials; - var credentialsPath = _credentialsFile(cache); - ensureDir(path.dirname(credentialsPath)); - writeTextFile(credentialsPath, credentials.toJson(), dontLogContents: true); -} - -/// The path to the file in which the user's OAuth2 credentials are stored. -String _credentialsFile(SystemCache cache) => - path.join(cache.rootDir, 'credentials.json'); - -/// Gets the user to authorize pub as a client of pub.dartlang.org via oauth2. -/// -/// Returns a Future that completes to a fully-authorized [Client]. -Future _authorize() { - var grant = new AuthorizationCodeGrant( - _identifier, - _secret, - authorizationEndpoint, - tokenEndpoint, - httpClient: httpClient); - - // Spin up a one-shot HTTP server to receive the authorization code from the - // Google OAuth2 server via redirect. This server will close itself as soon as - // the code is received. - var completer = new Completer(); - bindServer('localhost', 0).then((server) { - shelf_io.serveRequests(server, (request) { - if (request.url.path != "/") { - return new shelf.Response.notFound('Invalid URI.'); - } - - log.message('Authorization received, processing...'); - var queryString = request.url.query; - if (queryString == null) queryString = ''; - - // Closing the server here is safe, since it will wait until the response - // is sent to actually shut down. - server.close(); - chainToCompleter( - grant.handleAuthorizationResponse(queryToMap(queryString)), - completer); - - return new shelf.Response.found('http://pub.dartlang.org/authorized'); - }); - - var authUrl = grant.getAuthorizationUrl( - Uri.parse('http://localhost:${server.port}'), - scopes: _scopes); - - log.message( - 'Pub needs your authorization to upload packages on your behalf.\n' - 'In a web browser, go to $authUrl\n' 'Then click "Allow access".\n\n' - 'Waiting for your authorization...'); - }); - - return completer.future.then((client) { - log.message('Successfully authorized.\n'); - return client; - }); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/package.dart b/sdk/lib/_internal/pub_generated/lib/src/package.dart deleted file mode 100644 index e454d4b0b55..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/package.dart +++ /dev/null @@ -1,393 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.package; - -import 'dart:io'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; -import 'package:pub_semver/pub_semver.dart'; - -import 'barback/transformer_id.dart'; -import 'io.dart'; -import 'git.dart' as git; -import 'pubspec.dart'; -import 'source_registry.dart'; -import 'utils.dart'; - -final _README_REGEXP = new RegExp(r"^README($|\.)", caseSensitive: false); - -/// A named, versioned, unit of code and resource reuse. -class Package { - /// Compares [a] and [b] orders them by name then version number. - /// - /// This is normally used as a [Comparator] to pass to sort. This does not - /// take a package's description or root directory into account, so multiple - /// distinct packages may order the same. - static int orderByNameAndVersion(Package a, Package b) { - var name = a.name.compareTo(b.name); - if (name != 0) return name; - - return a.version.compareTo(b.version); - } - - /// The path to the directory containing the package. - final String dir; - - /// The name of the package. - String get name { - if (pubspec.name != null) return pubspec.name; - if (dir != null) return p.basename(dir); - return null; - } - - /// The package's version. - Version get version => pubspec.version; - - /// The parsed pubspec associated with this package. - final Pubspec pubspec; - - /// The immediate dependencies this package specifies in its pubspec. - List get dependencies => pubspec.dependencies; - - /// The immediate dev dependencies this package specifies in its pubspec. - List get devDependencies => pubspec.devDependencies; - - /// The dependency overrides this package specifies in its pubspec. - List get dependencyOverrides => pubspec.dependencyOverrides; - - /// All immediate dependencies this package specifies. - /// - /// This includes regular, dev dependencies, and overrides. - Set get immediateDependencies { - var deps = {}; - - addToMap(dep) { - deps[dep.name] = dep; - } - - dependencies.forEach(addToMap); - devDependencies.forEach(addToMap); - - // Make sure to add these last so they replace normal dependencies. - dependencyOverrides.forEach(addToMap); - - return deps.values.toSet(); - } - - /// Returns a list of asset ids for all Dart executables in this package's bin - /// directory. - List get executableIds { - return ordered( - listFiles( - beneath: "bin", - recursive: false)).where( - (executable) => p.extension(executable) == '.dart').map((executable) { - return new AssetId( - name, - p.toUri(p.relative(executable, from: dir)).toString()); - }).toList(); - } - - /// Returns the path to the README file at the root of the entrypoint, or null - /// if no README file is found. - /// - /// If multiple READMEs are found, this uses the same conventions as - /// pub.dartlang.org for choosing the primary one: the README with the fewest - /// extensions that is lexically ordered first is chosen. - String get readmePath { - var readmes = listFiles( - recursive: false).map( - p.basename).where((entry) => entry.contains(_README_REGEXP)); - if (readmes.isEmpty) return null; - - return p.join(dir, readmes.reduce((readme1, readme2) { - var extensions1 = ".".allMatches(readme1).length; - var extensions2 = ".".allMatches(readme2).length; - var comparison = extensions1.compareTo(extensions2); - if (comparison == 0) comparison = readme1.compareTo(readme2); - return (comparison <= 0) ? readme1 : readme2; - })); - } - - /// Loads the package whose root directory is [packageDir]. - /// - /// [name] is the expected name of that package (e.g. the name given in the - /// dependency), or `null` if the package being loaded is the entrypoint - /// package. - Package.load(String name, String packageDir, SourceRegistry sources) - : dir = packageDir, - pubspec = new Pubspec.load(packageDir, sources, expectedName: name); - - /// Constructs a package with the given pubspec. - /// - /// The package will have no directory associated with it. - Package.inMemory(this.pubspec) - : dir = null; - - /// Creates a package with [pubspec] located at [dir]. - Package(this.pubspec, this.dir); - - /// Given a relative path within this package, returns its absolute path. - /// - /// This is similar to `p.join(dir, part1, ...)`, except that subclasses may - /// override it to report that certain paths exist elsewhere than within - /// [dir]. For example, a [CachedPackage]'s `lib` directory is in the - /// `.pub/deps` directory. - String path(String part1, [String part2, String part3, String part4, - String part5, String part6, String part7]) { - if (dir == null) { - throw new StateError( - "Package $name is in-memory and doesn't have paths " "on disk."); - } - return p.join(dir, part1, part2, part3, part4, part5, part6, part7); - } - - /// Given an absolute path within this package (such as that returned by - /// [path] or [listFiles]), returns it relative to the package root. - String relative(String path) { - if (dir == null) { - throw new StateError( - "Package $name is in-memory and doesn't have paths " "on disk."); - } - return p.relative(path, from: dir); - } - - /// Returns the path to the library identified by [id] within [this]. - String transformerPath(TransformerId id) { - if (id.package != name) { - throw new ArgumentError("Transformer $id isn't in package $name."); - } - - if (id.path != null) return path('lib', p.fromUri('${id.path}.dart')); - - var transformerPath = path('lib/transformer.dart'); - if (fileExists(transformerPath)) return transformerPath; - return path('lib/$name.dart'); - } - - /// The basenames of files that are included in [list] despite being hidden. - static final _WHITELISTED_FILES = const ['.htaccess']; - - /// A set of patterns that match paths to blacklisted files. - static final _blacklistedFiles = createFileFilter(['pubspec.lock']); - - /// A set of patterns that match paths to blacklisted directories. - static final _blacklistedDirs = createDirectoryFilter(['packages']); - - /// Returns a list of files that are considered to be part of this package. - /// - /// If this is a Git repository, this will respect .gitignore; otherwise, it - /// will return all non-hidden, non-blacklisted files. - /// - /// If [beneath] is passed, this will only return files beneath that path, - /// which is expected to be relative to the package's root directory. If - /// [recursive] is true, this will return all files beneath that path; - /// otherwise, it will only return files one level beneath it. - /// - /// If [useGitIgnore] is passed, this will take the .gitignore rules into - /// account if the package's root directory is a Git repository. - /// - /// Note that the returned paths won't always be beneath [dir]. To safely - /// convert them to paths relative to the package root, use [relative]. - List listFiles({String beneath, bool recursive: true, - bool useGitIgnore: false}) { - if (beneath == null) { - beneath = dir; - } else { - beneath = p.join(dir, beneath); - } - - if (!dirExists(beneath)) return []; - - // This is used in some performance-sensitive paths and can list many, many - // files. As such, it leans more havily towards optimization as opposed to - // readability than most code in pub. In particular, it avoids using the - // path package, since re-parsing a path is very expensive relative to - // string operations. - var files; - if (useGitIgnore && git.isInstalled && dirExists(path('.git'))) { - // Later versions of git do not allow a path for ls-files that appears to - // be outside of the repo, so make sure we give it a relative path. - var relativeBeneath = p.relative(beneath, from: dir); - - // List all files that aren't gitignored, including those not checked in - // to Git. - files = git.runSync( - ["ls-files", "--cached", "--others", "--exclude-standard", relativeBeneath], - workingDir: dir); - - // If we're not listing recursively, strip out paths that contain - // separators. Since git always prints forward slashes, we always detect - // them. - if (!recursive) { - // If we're listing a subdirectory, we only want to look for slashes - // after the subdirectory prefix. - var relativeStart = - relativeBeneath == '.' ? 0 : relativeBeneath.length + 1; - files = files.where((file) => !file.contains('/', relativeStart)); - } - - // Git always prints files relative to the repository root, but we want - // them relative to the working directory. It also prints forward slashes - // on Windows which we normalize away for easier testing. - files = files.map((file) { - if (Platform.operatingSystem != 'windows') return "$dir/$file"; - return "$dir\\${file.replaceAll("/", "\\")}"; - }).where((file) { - // Filter out broken symlinks, since git doesn't do so automatically. - return fileExists(file); - }); - } else { - files = listDir( - beneath, - recursive: recursive, - includeDirs: false, - whitelist: _WHITELISTED_FILES); - } - - return files.where((file) { - // Using substring here is generally problematic in cases where dir has - // one or more trailing slashes. If you do listDir("foo"), you'll get back - // paths like "foo/bar". If you do listDir("foo/"), you'll get "foo/bar" - // (note the trailing slash was dropped. If you do listDir("foo//"), - // you'll get "foo//bar". - // - // This means if you strip off the prefix, the resulting string may have a - // leading separator (if the prefix did not have a trailing one) or it may - // not. However, since we are only using the results of that to call - // contains() on, the leading separator is harmless. - assert(file.startsWith(beneath)); - file = file.substring(beneath.length); - return !_blacklistedFiles.any(file.endsWith) && - !_blacklistedDirs.any(file.contains); - }).toList(); - } - - /// Returns a debug string for the package. - String toString() => '$name $version ($dir)'; -} - -/// This is the private base class of [PackageRef], [PackageID], and -/// [PackageDep]. -/// -/// It contains functionality and state that those classes share but is private -/// so that from outside of this library, there is no type relationship between -/// those three types. -class _PackageName { - _PackageName(this.name, this.source, this.description); - - /// The name of the package being identified. - final String name; - - /// The name of the [Source] used to look up this package given its - /// [description]. - /// - /// If this is a root package, this will be `null`. - final String source; - - /// The metadata used by the package's [source] to identify and locate it. - /// - /// It contains whatever [Source]-specific data it needs to be able to get - /// the package. For example, the description of a git sourced package might - /// by the URL "git://github.com/dart/uilib.git". - final description; - - /// Whether this package is the root package. - bool get isRoot => source == null; - - String toString() { - if (isRoot) return "$name (root)"; - return "$name from $source"; - } - - /// Returns a [PackageRef] with this one's [name], [source], and - /// [description]. - PackageRef toRef() => new PackageRef(name, source, description); - - /// Returns a [PackageId] for this package with the given concrete version. - PackageId atVersion(Version version) => - new PackageId(name, source, version, description); - - /// Returns a [PackageDep] for this package with the given version constraint. - PackageDep withConstraint(VersionConstraint constraint) => - new PackageDep(name, source, constraint, description); -} - -/// A reference to a [Package], but not any particular version(s) of it. -class PackageRef extends _PackageName { - PackageRef(String name, String source, description) - : super(name, source, description); - - int get hashCode => name.hashCode ^ source.hashCode; - - bool operator ==(other) { - // TODO(rnystrom): We're assuming here that we don't need to delve into the - // description. - return other is PackageRef && other.name == name && other.source == source; - } -} - -/// A reference to a specific version of a package. -/// -/// A package ID contains enough information to correctly get the package. -/// -/// Note that it's possible for multiple distinct package IDs to point to -/// different packages that have identical contents. For example, the same -/// package may be available from multiple sources. As far as Pub is concerned, -/// those packages are different. -class PackageId extends _PackageName { - /// The package's version. - final Version version; - - PackageId(String name, String source, this.version, description) - : super(name, source, description); - - /// Creates an ID for the given root package. - PackageId.root(Package package) - : version = package.version, - super(package.name, null, package.name); - - int get hashCode => name.hashCode ^ source.hashCode ^ version.hashCode; - - bool operator ==(other) { - // TODO(rnystrom): We're assuming here that we don't need to delve into the - // description. - return other is PackageId && - other.name == name && - other.source == source && - other.version == version; - } - - String toString() { - if (isRoot) return "$name $version (root)"; - return "$name $version from $source"; - } -} - -/// A reference to a constrained range of versions of one package. -class PackageDep extends _PackageName { - /// The allowed package versions. - final VersionConstraint constraint; - - PackageDep(String name, String source, this.constraint, description) - : super(name, source, description); - - String toString() { - if (isRoot) return "$name $constraint (root)"; - return "$name $constraint from $source ($description)"; - } - - int get hashCode => name.hashCode ^ source.hashCode; - - bool operator ==(other) { - // TODO(rnystrom): We're assuming here that we don't need to delve into the - // description. - return other is PackageDep && - other.name == name && - other.source == source && - other.constraint == constraint; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/package_graph.dart b/sdk/lib/_internal/pub_generated/lib/src/package_graph.dart deleted file mode 100644 index 739a7d74336..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/package_graph.dart +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.package_graph; - -import 'barback/transformer_cache.dart'; -import 'entrypoint.dart'; -import 'lock_file.dart'; -import 'package.dart'; -import 'source/cached.dart'; -import 'utils.dart'; - -/// A holistic view of the entire transitive dependency graph for an entrypoint. -/// -/// A package graph can be loaded using [Entrypoint.loadPackageGraph]. -class PackageGraph { - /// The entrypoint. - final Entrypoint entrypoint; - - /// The entrypoint's lockfile. - /// - /// This describes the sources and resolved descriptions of everything in - /// [packages]. - final LockFile lockFile; - - /// The transitive dependencies of the entrypoint (including itself). - /// - /// This may not include all transitive dependencies of the entrypoint if the - /// creator of the package graph knows only a subset of the packages are - /// relevant in the current context. - final Map packages; - - /// A map of transitive dependencies for each package. - Map> _transitiveDependencies; - - /// The transformer cache, if it's been loaded. - TransformerCache _transformerCache; - - PackageGraph(this.entrypoint, this.lockFile, this.packages); - - /// Loads the transformer cache for this graph. - /// - /// This may only be called if [entrypoint] represents a physical package. - /// This may modify the cache. - TransformerCache loadTransformerCache() { - if (_transformerCache == null) { - if (entrypoint.root.dir == null) { - throw new StateError( - "Can't load the transformer cache for virtual " - "entrypoint ${entrypoint.root.name}."); - } - _transformerCache = new TransformerCache.load(this); - } - return _transformerCache; - } - - /// Returns all transitive dependencies of [package]. - /// - /// For the entrypoint this returns all packages in [packages], which includes - /// dev and override. For any other package, it ignores dev and override - /// dependencies. - Set transitiveDependencies(String package) { - if (package == entrypoint.root.name) return packages.values.toSet(); - - if (_transitiveDependencies == null) { - var closure = transitiveClosure( - mapMap( - packages, - value: (_, package) => package.dependencies.map((dep) => dep.name))); - _transitiveDependencies = mapMap( - closure, - value: (_, names) => names.map((name) => packages[name]).toSet()); - } - - return _transitiveDependencies[package]; - } - - /// Returns whether [package] is mutable. - /// - /// A package is considered to be mutable if it or any of its dependencies - /// don't come from a cached source, since the user can change its contents - /// without modifying the pub cache. Information generated from mutable - /// packages is generally not safe to cache, since it may change frequently. - bool isPackageMutable(String package) { - var id = lockFile.packages[package]; - if (id == null) return true; - - var source = entrypoint.cache.sources[id.source]; - if (source is! CachedSource) return true; - - return transitiveDependencies(package).any((dep) { - var depId = lockFile.packages[dep.name]; - - // The entrypoint package doesn't have a lockfile entry. It's always - // mutable. - if (depId == null) return true; - - return entrypoint.cache.sources[depId.source] is! CachedSource; - }); - } - - /// Returns whether [package] is static. - /// - /// A package is considered to be static if it's not transformed and it came - /// from a cached source. Static packages don't need to be fully processed by - /// barback. - /// - /// Note that a static package isn't the same as an immutable package (see - /// [isPackageMutable]). - bool isPackageStatic(String package) { - var id = lockFile.packages[package]; - if (id == null) return false; - - var source = entrypoint.cache.sources[id.source]; - if (source is! CachedSource) return false; - - return packages[package].pubspec.transformers.isEmpty; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/preprocess.dart b/sdk/lib/_internal/pub_generated/lib/src/preprocess.dart deleted file mode 100644 index bf05f89fae1..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/preprocess.dart +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.preprocess; - -import 'package:pub_semver/pub_semver.dart'; -import 'package:string_scanner/string_scanner.dart'; - -/// Runs a simple preprocessor over [input] to remove sections that are -/// incompatible with the available barback version. -/// -/// [versions] are the available versions of each installed package, and -/// [sourceUrl] is a [String] or [Uri] indicating where [input] came from. It's -/// used for error reporting. -/// -/// For the most part, the preprocessor leaves text in the source document -/// alone. However, it handles two types of lines specially. Lines that begin -/// with `//>` are uncommented by the preprocessor, and lines that begin with -/// `//#` are operators. -/// -/// The preprocessor currently supports one top-level operator, "if": -/// -/// //# if barback >=0.14.1 -/// ... -/// //# else -/// ... -/// //# end -/// -/// If can check against any package installed in the current package. It can -/// check the version of the package, as above, or (if the version range is -/// omitted) whether the package exists at all. If the condition is true, -/// everything within the first block is included in the output and everything -/// within the second block is removed; otherwise, the first block is removed -/// and the second block is included. The `else` block is optional. -/// -/// It's important that the preprocessor syntax also be valid Dart code, because -/// pub loads the source files before preprocessing and runs them against the -/// version of barback that was compiled into pub. This is why the `//>` syntax -/// exists: so that code can be hidden from the running pub process but still be -/// visible to the barback isolate. For example: -/// -/// //# if barback >= 0.14.1 -/// ClassMirror get aggregateClass => reflectClass(AggregateTransformer); -/// //# else -/// //> ClassMirror get aggregateClass => null; -/// //# end -String preprocess(String input, Map versions, sourceUrl) { - // Short-circuit if there are no preprocessor directives in the file. - if (!input.contains(new RegExp(r"^//[>#]", multiLine: true))) return input; - return new _Preprocessor(input, versions, sourceUrl).run(); -} - -/// The preprocessor class. -class _Preprocessor { - /// The scanner over the input string. - final StringScanner _scanner; - - final Map _versions; - - /// The buffer to which the output is written. - final _buffer = new StringBuffer(); - - _Preprocessor(String input, this._versions, sourceUrl) - : _scanner = new StringScanner(input, sourceUrl: sourceUrl); - - /// Run the preprocessor and return the processed output. - String run() { - while (!_scanner.isDone) { - if (_scanner.scan(new RegExp(r"//#[ \t]*"))) { - _if(); - } else { - _emitText(); - } - } - - _scanner.expectDone(); - return _buffer.toString(); - } - - /// Emit lines of the input document directly until an operator is - /// encountered. - void _emitText() { - while (!_scanner.isDone && !_scanner.matches("//#")) { - if (_scanner.scan("//>")) { - if (!_scanner.matches("\n")) _scanner.expect(" "); - } - - _scanner.scan(new RegExp(r"[^\n]*\n?")); - _buffer.write(_scanner.lastMatch[0]); - } - } - - /// Move through lines of the input document without emitting them until an - /// operator is encountered. - void _ignoreText() { - while (!_scanner.isDone && !_scanner.matches("//#")) { - _scanner.scan(new RegExp(r"[^\n]*\n?")); - } - } - - /// Handle an `if` operator. - void _if() { - _scanner.expect(new RegExp(r"if[ \t]+"), name: "if statement"); - _scanner.expect(new RegExp(r"[a-zA-Z0-9_]+"), name: "package name"); - var package = _scanner.lastMatch[0]; - - _scanner.scan(new RegExp(r"[ \t]*")); - var constraint = VersionConstraint.any; - if (_scanner.scan(new RegExp(r"[^\n]+"))) { - try { - constraint = new VersionConstraint.parse(_scanner.lastMatch[0]); - } on FormatException catch (error) { - _scanner.error("Invalid version constraint: ${error.message}"); - } - } - _scanner.expect("\n"); - - var allowed = - _versions.containsKey(package) && - constraint.allows(_versions[package]); - if (allowed) { - _emitText(); - } else { - _ignoreText(); - } - - _scanner.expect("//#"); - _scanner.scan(new RegExp(r"[ \t]*")); - if (_scanner.scan("else")) { - _scanner.expect("\n"); - if (allowed) { - _ignoreText(); - } else { - _emitText(); - } - _scanner.expect("//#"); - _scanner.scan(new RegExp(r"[ \t]*")); - } - - _scanner.expect("end"); - if (!_scanner.isDone) _scanner.expect("\n"); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/progress.dart b/sdk/lib/_internal/pub_generated/lib/src/progress.dart deleted file mode 100644 index 483157d2f6a..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/progress.dart +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.progress; - -import 'dart:async'; -import 'dart:io'; - -import 'log.dart' as log; -import 'utils.dart'; - -/// A live-updating progress indicator for long-running log entries. -class Progress { - /// The timer used to write "..." during a progress log. - Timer _timer; - - /// The [Stopwatch] used to track how long a progress log has been running. - final _stopwatch = new Stopwatch(); - - /// The progress message as it's being incrementally appended. - /// - /// When the progress is done, a single entry will be added to the log for it. - final String _message; - - /// Gets the current progress time as a parenthesized, formatted string. - String get _time => "(${niceDuration(_stopwatch.elapsed)})"; - - /// Creates a new progress indicator. - /// - /// If [fine] is passed, this will log progress messages on [log.Level.FINE] - /// as opposed to [log.Level.MESSAGE]. - Progress(this._message, {bool fine: false}) { - _stopwatch.start(); - - var level = fine ? log.Level.FINE : log.Level.MESSAGE; - - // The animation is only shown when it would be meaningful to a human. - // That means we're writing a visible message to a TTY at normal log levels - // with non-JSON output. - if (stdioType(stdout) != StdioType.TERMINAL || - !log.verbosity.isLevelVisible(level) || - log.json.enabled || - fine || - log.verbosity.isLevelVisible(log.Level.FINE)) { - // Not animating, so just log the start and wait until the task is - // completed. - log.write(level, "$_message..."); - return; - } - - _timer = new Timer.periodic(new Duration(milliseconds: 100), (_) { - _update(); - }); - - _update(); - } - - /// Stops the progress indicator. - void stop() { - _stopwatch.stop(); - - // Always log the final time as [log.fine] because for the most part normal - // users don't care about the precise time information beyond what's shown - // in the animation. - log.fine("$_message finished $_time."); - - // If we were animating, print one final update to show the user the final - // time. - if (_timer == null) return; - _timer.cancel(); - _timer = null; - _update(); - stdout.writeln(); - } - - /// Stop animating the progress indicator. - /// - /// This will continue running the stopwatch so that the full time can be - /// logged in [stop]. - void stopAnimating() { - if (_timer == null) return; - - // Print a final message without a time indicator so that we don't leave a - // misleading half-complete time indicator on the console. - stdout.writeln(log.format("\r$_message...")); - _timer.cancel(); - _timer = null; - } - - /// Refreshes the progress line. - void _update() { - if (log.isMuted) return; - - stdout.write(log.format("\r$_message... ")); - - // Show the time only once it gets noticeably long. - if (_stopwatch.elapsed.inSeconds > 0) stdout.write("${log.gray(_time)} "); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/pubspec.dart b/sdk/lib/_internal/pub_generated/lib/src/pubspec.dart deleted file mode 100644 index 92c068a7b5f..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/pubspec.dart +++ /dev/null @@ -1,628 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.pubspec; - -import 'package:path/path.dart' as path; -import 'package:pub_semver/pub_semver.dart'; -import 'package:source_span/source_span.dart'; -import 'package:yaml/yaml.dart'; - -import 'barback/transformer_config.dart'; -import 'exceptions.dart'; -import 'io.dart'; -import 'package.dart'; -import 'source_registry.dart'; -import 'utils.dart'; - -/// The parsed contents of a pubspec file. -/// -/// The fields of a pubspec are, for the most part, validated when they're first -/// accessed. This allows a partially-invalid pubspec to be used if only the -/// valid portions are relevant. To get a list of all errors in the pubspec, use -/// [allErrors]. -class Pubspec { - // If a new lazily-initialized field is added to this class and the - // initialization can throw a [PubspecException], that error should also be - // exposed through [allErrors]. - - /// The registry of sources to use when parsing [dependencies] and - /// [devDependencies]. - /// - /// This will be null if this was created using [new Pubspec] or [new - /// Pubspec.empty]. - final SourceRegistry _sources; - - /// The location from which the pubspec was loaded. - /// - /// This can be null if the pubspec was created in-memory or if its location - /// is unknown. - Uri get _location => fields.span.sourceUrl; - - /// All pubspec fields. - /// - /// This includes the fields from which other properties are derived. - final YamlMap fields; - - /// The package's name. - String get name { - if (_name != null) return _name; - - var name = fields['name']; - if (name == null) { - throw new PubspecException( - 'Missing the required "name" field.', - fields.span); - } else if (name is! String) { - throw new PubspecException( - '"name" field must be a string.', - fields.nodes['name'].span); - } - - _name = name; - return _name; - } - String _name; - - /// The package's version. - Version get version { - if (_version != null) return _version; - - var version = fields['version']; - if (version == null) { - _version = Version.none; - return _version; - } - - var span = fields.nodes['version'].span; - if (version is num) { - var fixed = '$version.0'; - if (version is int) { - fixed = '$fixed.0'; - } - _error( - '"version" field must have three numeric components: major, ' - 'minor, and patch. Instead of "$version", consider "$fixed".', - span); - } - if (version is! String) { - _error('"version" field must be a string.', span); - } - - _version = - _wrapFormatException('version number', span, () => new Version.parse(version)); - return _version; - } - Version _version; - - /// The additional packages this package depends on. - List get dependencies { - if (_dependencies != null) return _dependencies; - _dependencies = _parseDependencies('dependencies'); - _checkDependencyOverlap(_dependencies, _devDependencies); - return _dependencies; - } - List _dependencies; - - /// The packages this package depends on when it is the root package. - List get devDependencies { - if (_devDependencies != null) return _devDependencies; - _devDependencies = _parseDependencies('dev_dependencies'); - _checkDependencyOverlap(_dependencies, _devDependencies); - return _devDependencies; - } - List _devDependencies; - - /// The dependency constraints that this package overrides when it is the - /// root package. - /// - /// Dependencies here will replace any dependency on a package with the same - /// name anywhere in the dependency graph. - List get dependencyOverrides { - if (_dependencyOverrides != null) return _dependencyOverrides; - _dependencyOverrides = _parseDependencies('dependency_overrides'); - return _dependencyOverrides; - } - List _dependencyOverrides; - - /// The configurations of the transformers to use for this package. - List> get transformers { - if (_transformers != null) return _transformers; - - var transformers = fields['transformers']; - if (transformers == null) { - _transformers = []; - return _transformers; - } - - if (transformers is! List) { - _error( - '"transformers" field must be a list.', - fields.nodes['transformers'].span); - } - - var i = 0; - _transformers = transformers.nodes.map((phase) { - var phaseNodes = phase is YamlList ? phase.nodes : [phase]; - return phaseNodes.map((transformerNode) { - var transformer = transformerNode.value; - if (transformer is! String && transformer is! Map) { - _error( - 'A transformer must be a string or map.', - transformerNode.span); - } - - var libraryNode; - var configurationNode; - if (transformer is String) { - libraryNode = transformerNode; - } else { - if (transformer.length != 1) { - _error( - 'A transformer map must have a single key: the transformer ' 'identifier.', - transformerNode.span); - } else if (transformer.keys.single is! String) { - _error( - 'A transformer identifier must be a string.', - transformer.nodes.keys.single.span); - } - - libraryNode = transformer.nodes.keys.single; - configurationNode = transformer.nodes.values.single; - if (configurationNode is! YamlMap) { - _error( - "A transformer's configuration must be a map.", - configurationNode.span); - } - } - - var config = _wrapSpanFormatException('transformer config', () { - return new TransformerConfig.parse( - libraryNode.value, - libraryNode.span, - configurationNode); - }); - - var package = config.id.package; - if (package != name && - !config.id.isBuiltInTransformer && - !dependencies.any((ref) => ref.name == package) && - !devDependencies.any((ref) => ref.name == package) && - !dependencyOverrides.any((ref) => ref.name == package)) { - _error('"$package" is not a dependency.', libraryNode.span); - } - - return config; - }).toSet(); - }).toList(); - - return _transformers; - } - List> _transformers; - - /// The environment-related metadata. - PubspecEnvironment get environment { - if (_environment != null) return _environment; - - var yaml = fields['environment']; - if (yaml == null) { - _environment = new PubspecEnvironment(VersionConstraint.any); - return _environment; - } - - if (yaml is! Map) { - _error( - '"environment" field must be a map.', - fields.nodes['environment'].span); - } - - _environment = - new PubspecEnvironment(_parseVersionConstraint(yaml.nodes['sdk'])); - return _environment; - } - PubspecEnvironment _environment; - - /// The URL of the server that the package should default to being published - /// to, "none" if the package should not be published, or `null` if it should - /// be published to the default server. - /// - /// If this does return a URL string, it will be a valid parseable URL. - String get publishTo { - if (_parsedPublishTo) return _publishTo; - - var publishTo = fields['publish_to']; - if (publishTo != null) { - var span = fields.nodes['publish_to'].span; - - if (publishTo is! String) { - _error('"publish_to" field must be a string.', span); - } - - // It must be "none" or a valid URL. - if (publishTo != "none") { - _wrapFormatException( - '"publish_to" field', - span, - () => Uri.parse(publishTo)); - } - } - - _parsedPublishTo = true; - _publishTo = publishTo; - return _publishTo; - } - bool _parsedPublishTo = false; - String _publishTo; - - /// The executables that should be placed on the user's PATH when this - /// package is globally activated. - /// - /// It is a map of strings to string. Each key is the name of the command - /// that will be placed on the user's PATH. The value is the name of the - /// .dart script (without extension) in the package's `bin` directory that - /// should be run for that command. Both key and value must be "simple" - /// strings: alphanumerics, underscores and hypens only. If a value is - /// omitted, it is inferred to use the same name as the key. - Map get executables { - if (_executables != null) return _executables; - - _executables = {}; - var yaml = fields['executables']; - if (yaml == null) return _executables; - - if (yaml is! Map) { - _error( - '"executables" field must be a map.', - fields.nodes['executables'].span); - } - - yaml.nodes.forEach((key, value) { - // Don't allow path separators or other stuff meaningful to the shell. - validateName(name, description) { - } - - if (key.value is! String) { - _error('"executables" keys must be strings.', key.span); - } - - final keyPattern = new RegExp(r"^[a-zA-Z0-9_-]+$"); - if (!keyPattern.hasMatch(key.value)) { - _error( - '"executables" keys may only contain letters, ' - 'numbers, hyphens and underscores.', - key.span); - } - - if (value.value == null) { - value = key; - } else if (value.value is! String) { - _error('"executables" values must be strings or null.', value.span); - } - - final valuePattern = new RegExp(r"[/\\]"); - if (valuePattern.hasMatch(value.value)) { - _error( - '"executables" values may not contain path separators.', - value.span); - } - - _executables[key.value] = value.value; - }); - - return _executables; - } - Map _executables; - - /// Whether the package is private and cannot be published. - /// - /// This is specified in the pubspec by setting "publish_to" to "none". - bool get isPrivate => publishTo == "none"; - - /// Whether or not the pubspec has no contents. - bool get isEmpty => - name == null && version == Version.none && dependencies.isEmpty; - - /// Loads the pubspec for a package located in [packageDir]. - /// - /// If [expectedName] is passed and the pubspec doesn't have a matching name - /// field, this will throw a [PubspecError]. - factory Pubspec.load(String packageDir, SourceRegistry sources, - {String expectedName}) { - var pubspecPath = path.join(packageDir, 'pubspec.yaml'); - var pubspecUri = path.toUri(pubspecPath); - if (!fileExists(pubspecPath)) { - throw new FileException( - 'Could not find a file named "pubspec.yaml" in "$packageDir".', - pubspecPath); - } - - return new Pubspec.parse( - readTextFile(pubspecPath), - sources, - expectedName: expectedName, - location: pubspecUri); - } - - Pubspec(this._name, {Version version, Iterable dependencies, - Iterable devDependencies, Iterable dependencyOverrides, - VersionConstraint sdkConstraint, - Iterable> transformers, Map fields, - SourceRegistry sources}) - : _version = version, - _dependencies = dependencies == null ? null : dependencies.toList(), - _devDependencies = devDependencies == null ? - null : - devDependencies.toList(), - _dependencyOverrides = dependencyOverrides == null ? - null : - dependencyOverrides.toList(), - _environment = new PubspecEnvironment(sdkConstraint), - _transformers = transformers == null ? - [] : - transformers.map((phase) => phase.toSet()).toList(), - fields = fields == null ? new YamlMap() : new YamlMap.wrap(fields), - _sources = sources; - - Pubspec.empty() - : _sources = null, - _name = null, - _version = Version.none, - _dependencies = [], - _devDependencies = [], - _environment = new PubspecEnvironment(), - _transformers = >[], - fields = new YamlMap(); - - /// Returns a Pubspec object for an already-parsed map representing its - /// contents. - /// - /// If [expectedName] is passed and the pubspec doesn't have a matching name - /// field, this will throw a [PubspecError]. - /// - /// [location] is the location from which this pubspec was loaded. - Pubspec.fromMap(Map fields, this._sources, {String expectedName, - Uri location}) - : fields = fields is YamlMap ? - fields : - new YamlMap.wrap(fields, sourceUrl: location) { - // If [expectedName] is passed, ensure that the actual 'name' field exists - // and matches the expectation. - if (expectedName == null) return; - if (name == expectedName) return; - - throw new PubspecException( - '"name" field doesn\'t match expected name ' '"$expectedName".', - this.fields.nodes["name"].span); - } - - /// Parses the pubspec stored at [filePath] whose text is [contents]. - /// - /// If the pubspec doesn't define a version for itself, it defaults to - /// [Version.none]. - factory Pubspec.parse(String contents, SourceRegistry sources, - {String expectedName, Uri location}) { - var pubspecNode = loadYamlNode(contents, sourceUrl: location); - if (pubspecNode is YamlScalar && pubspecNode.value == null) { - pubspecNode = new YamlMap(sourceUrl: location); - } else if (pubspecNode is! YamlMap) { - throw new PubspecException( - 'The pubspec must be a YAML mapping.', - pubspecNode.span); - } - - return new Pubspec.fromMap( - pubspecNode, - sources, - expectedName: expectedName, - location: location); - } - - /// Returns a list of most errors in this pubspec. - /// - /// This will return at most one error for each field. - List get allErrors { - var errors = []; - _getError(fn()) { - try { - fn(); - } on PubspecException catch (e) { - errors.add(e); - } - } - - _getError(() => this.name); - _getError(() => this.version); - _getError(() => this.dependencies); - _getError(() => this.devDependencies); - _getError(() => this.transformers); - _getError(() => this.environment); - _getError(() => this.publishTo); - return errors; - } - - /// Parses the dependency field named [field], and returns the corresponding - /// list of dependencies. - List _parseDependencies(String field) { - var dependencies = []; - - var yaml = fields[field]; - // Allow an empty dependencies key. - if (yaml == null) return dependencies; - - if (yaml is! Map) { - _error('"$field" field must be a map.', fields.nodes[field].span); - } - - var nonStringNode = - yaml.nodes.keys.firstWhere((e) => e.value is! String, orElse: () => null); - if (nonStringNode != null) { - _error('A dependency name must be a string.', nonStringNode.span); - } - - yaml.nodes.forEach((nameNode, specNode) { - var name = nameNode.value; - var spec = specNode.value; - if (fields['name'] != null && name == this.name) { - _error('A package may not list itself as a dependency.', nameNode.span); - } - - var descriptionNode; - var sourceName; - - var versionConstraint = new VersionRange(); - if (spec == null) { - descriptionNode = nameNode; - sourceName = _sources.defaultSource.name; - } else if (spec is String) { - descriptionNode = nameNode; - sourceName = _sources.defaultSource.name; - versionConstraint = _parseVersionConstraint(specNode); - } else if (spec is Map) { - // Don't write to the immutable YAML map. - spec = new Map.from(spec); - - if (spec.containsKey('version')) { - spec.remove('version'); - versionConstraint = - _parseVersionConstraint(specNode.nodes['version']); - } - - var sourceNames = spec.keys.toList(); - if (sourceNames.length > 1) { - _error('A dependency may only have one source.', specNode.span); - } - - sourceName = sourceNames.single; - if (sourceName is! String) { - _error( - 'A source name must be a string.', - specNode.nodes.keys.single.span); - } - - descriptionNode = specNode.nodes[sourceName]; - } else { - _error( - 'A dependency specification must be a string or a mapping.', - specNode.span); - } - - // Let the source validate the description. - var description = - _wrapFormatException('description', descriptionNode.span, () { - var pubspecPath; - if (_location != null && _isFileUri(_location)) { - pubspecPath = path.fromUri(_location); - } - - return _sources[sourceName].parseDescription( - pubspecPath, - descriptionNode.value, - fromLockFile: false); - }); - - dependencies.add( - new PackageDep(name, sourceName, versionConstraint, description)); - }); - - return dependencies; - } - - /// Parses [node] to a [VersionConstraint]. - VersionConstraint _parseVersionConstraint(YamlNode node) { - if (node.value == null) return VersionConstraint.any; - if (node.value is! String) { - _error('A version constraint must be a string.', node.span); - } - - return _wrapFormatException( - 'version constraint', - node.span, - () => new VersionConstraint.parse(node.value)); - } - - /// Makes sure the same package doesn't appear as both a regular and dev - /// dependency. - void _checkDependencyOverlap(List dependencies, - List devDependencies) { - if (dependencies == null) return; - if (devDependencies == null) return; - - var dependencyNames = dependencies.map((dep) => dep.name).toSet(); - var collisions = - dependencyNames.intersection(devDependencies.map((dep) => dep.name).toSet()); - if (collisions.isEmpty) return; - - var span = fields["dependencies"].nodes.keys.firstWhere( - (key) => collisions.contains(key.value)).span; - - // TODO(nweiz): associate source range info with PackageDeps and use it - // here. - _error( - '${pluralize('Package', collisions.length)} ' - '${toSentence(collisions.map((package) => '"$package"'))} cannot ' - 'appear in both "dependencies" and "dev_dependencies".', - span); - } - - /// Runs [fn] and wraps any [FormatException] it throws in a - /// [PubspecException]. - /// - /// [description] should be a noun phrase that describes whatever's being - /// parsed or processed by [fn]. [span] should be the location of whatever's - /// being processed within the pubspec. - _wrapFormatException(String description, SourceSpan span, fn()) { - try { - return fn(); - } on FormatException catch (e) { - _error('Invalid $description: ${e.message}', span); - } - } - - _wrapSpanFormatException(String description, fn()) { - try { - return fn(); - } on SourceSpanFormatException catch (e) { - _error('Invalid $description: ${e.message}', e.span); - } - } - - /// Throws a [PubspecException] with the given message. - void _error(String message, SourceSpan span) { - var name; - try { - name = this.name; - } on PubspecException catch (_) { - // [name] is null. - } - - throw new PubspecException(message, span); - } -} - -/// The environment-related metadata in the pubspec. -/// -/// Corresponds to the data under the "environment:" key in the pubspec. -class PubspecEnvironment { - /// The version constraint specifying which SDK versions this package works - /// with. - final VersionConstraint sdkVersion; - - PubspecEnvironment([VersionConstraint sdk]) - : sdkVersion = sdk != null ? sdk : VersionConstraint.any; -} - -/// An exception thrown when parsing a pubspec. -/// -/// These exceptions are often thrown lazily while accessing pubspec properties. -class PubspecException extends SourceSpanFormatException implements - ApplicationException { - PubspecException(String message, SourceSpan span) - : super(message, span); -} - -/// Returns whether [uri] is a file URI. -/// -/// This is slightly more complicated than just checking if the scheme is -/// 'file', since relative URIs also refer to the filesystem on the VM. -bool _isFileUri(Uri uri) => uri.scheme == 'file' || uri.scheme == ''; diff --git a/sdk/lib/_internal/pub_generated/lib/src/sdk.dart b/sdk/lib/_internal/pub_generated/lib/src/sdk.dart deleted file mode 100644 index 2750821dea8..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/sdk.dart +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Operations relative to the user's installed Dart SDK. -library pub.sdk; - -import 'dart:io'; - -import 'package:path/path.dart' as path; -import 'package:pub_semver/pub_semver.dart'; - -import 'io.dart'; - -/// Gets the path to the root directory of the SDK. -/// -/// When running from the actual built SDK, this will be the SDK that contains -/// the running Dart executable. When running from the repo, it will be the -/// "sdk" directory in the Dart repository itself. -final String rootDirectory = - runningFromSdk ? _rootDirectory : path.join(repoRoot, "sdk"); - -/// Gets the path to the root directory of the SDK, assuming that the currently -/// running Dart executable is within it. -final String _rootDirectory = path.dirname(path.dirname(Platform.executable)); - -/// The SDK's revision number formatted to be a semantic version. -/// -/// This can be set so that the version solver tests can artificially select -/// different SDK versions. -Version version = _getVersion(); - -/// Determine the SDK's version number. -Version _getVersion() { - // Some of the pub integration tests require an SDK version number, but the - // tests on the bots are not run from a built SDK so this lets us avoid - // parsing the missing version file. - var sdkVersion = Platform.environment["_PUB_TEST_SDK_VERSION"]; - if (sdkVersion != null) return new Version.parse(sdkVersion); - - if (runningFromSdk) { - // Read the "version" file. - var version = readTextFile(path.join(_rootDirectory, "version")).trim(); - return new Version.parse(version); - } - - // When running from the repo, read the canonical VERSION file in tools/. - // This makes it possible to run pub without having built the SDK first. - var contents = readTextFile(path.join(repoRoot, "tools/VERSION")); - - parseField(name) { - var pattern = new RegExp("^$name ([a-z0-9]+)", multiLine: true); - var match = pattern.firstMatch(contents); - return match[1]; - } - - var channel = parseField("CHANNEL"); - var major = parseField("MAJOR"); - var minor = parseField("MINOR"); - var patch = parseField("PATCH"); - var prerelease = parseField("PRERELEASE"); - var prereleasePatch = parseField("PRERELEASE_PATCH"); - - var version = "$major.$minor.$patch"; - if (channel == "be") { - // TODO(rnystrom): tools/utils.py includes the svn commit here. Should we? - version += "-edge"; - } else if (channel == "dev") { - version += "-dev.$prerelease.$prereleasePatch"; - } - - return new Version.parse(version); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/backtracking_solver.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/backtracking_solver.dart deleted file mode 100644 index a5bac0f8ef6..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/solver/backtracking_solver.dart +++ /dev/null @@ -1,810 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// A back-tracking depth-first solver. -/// -/// Attempts to find the best solution for a root package's transitive -/// dependency graph, where a "solution" is a set of concrete package versions. -/// A valid solution will select concrete versions for every package reached -/// from the root package's dependency graph, and each of those packages will -/// fit the version constraints placed on it. -/// -/// The solver builds up a solution incrementally by traversing the dependency -/// graph starting at the root package. When it reaches a new package, it gets -/// the set of versions that meet the current constraint placed on it. It -/// *speculatively* selects one version from that set and adds it to the -/// current solution and then proceeds. If it fully traverses the dependency -/// graph, the solution is valid and it stops. -/// -/// If it reaches an error because: -/// -/// - A new dependency is placed on a package that's already been selected in -/// the solution and the selected version doesn't match the new constraint. -/// -/// - There are no versions available that meet the constraint placed on a -/// package. -/// -/// - etc. -/// -/// then the current solution is invalid. It will then backtrack to the most -/// recent speculative version choice and try the next one. That becomes the -/// new in-progress solution and it tries to proceed from there. It will keep -/// doing this, traversing and then backtracking when it meets a failure until -/// a valid solution has been found or until all possible options for all -/// speculative choices have been exhausted. -library pub.solver.backtracking_solver; - -import 'dart:async'; -import 'dart:collection' show Queue; - -import 'package:pub_semver/pub_semver.dart'; - -import '../barback.dart' as barback; -import '../exceptions.dart'; -import '../lock_file.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../pubspec.dart'; -import '../sdk.dart' as sdk; -import '../source_registry.dart'; -import '../source/unknown.dart'; -import '../utils.dart'; -import 'dependency_queue.dart'; -import 'version_queue.dart'; -import 'version_solver.dart'; - -/// The top-level solver. -/// -/// Keeps track of the current potential solution, and the other possible -/// versions for speculative package selections. Backtracks and advances to the -/// next potential solution in the case of a failure. -class BacktrackingSolver { - final SolveType type; - final SourceRegistry sources; - final Package root; - - /// The lockfile that was present before solving. - final LockFile lockFile; - - final PubspecCache cache; - - /// The set of packages that are being explicitly upgraded. - /// - /// The solver will only allow the very latest version for each of these - /// packages. - final _forceLatest = new Set(); - - /// The set of packages whose dependecy is being overridden by the root - /// package, keyed by the name of the package. - /// - /// Any dependency on a package that appears in this map will be overriden - /// to use the one here. - final _overrides = new Map(); - - /// The package versions currently selected by the solver, along with the - /// versions which are remaining to be tried. - /// - /// Every time a package is encountered when traversing the dependency graph, - /// the solver must select a version for it, sometimes when multiple versions - /// are valid. This keeps track of which versions have been selected so far - /// and which remain to be tried. - /// - /// Each entry in the list is a [VersionQueue], which is an ordered queue of - /// versions to try for a single package. It maintains the currently selected - /// version for that package. When a new dependency is encountered, a queue - /// of versions of that dependency is pushed onto the end of the list. A - /// queue is removed from the list once it's empty, indicating that none of - /// the versions provided a solution. - /// - /// The solver tries versions in depth-first order, so only the last queue in - /// the list will have items removed from it. When a new constraint is placed - /// on an already-selected package, and that constraint doesn't match the - /// selected version, that will cause the current solution to fail and - /// trigger backtracking. - final _selected = []; - - /// The number of solutions the solver has tried so far. - int get attemptedSolutions => _attemptedSolutions; - var _attemptedSolutions = 1; - - BacktrackingSolver(SolveType type, SourceRegistry sources, this.root, - this.lockFile, List useLatest) - : type = type, - sources = sources, - cache = new PubspecCache(type, sources) { - for (var package in useLatest) { - _forceLatest.add(package); - } - - for (var override in root.dependencyOverrides) { - _overrides[override.name] = override; - } - } - - /// Run the solver. - /// - /// Completes with a list of specific package versions if successful or an - /// error if it failed to find a solution. - Future solve() { - var stopwatch = new Stopwatch(); - - _logParameters(); - - // Sort the overrides by package name to make sure they're deterministic. - var overrides = _overrides.values.toList(); - overrides.sort((a, b) => a.name.compareTo(b.name)); - - // TODO(nweiz): Use async/await here once - // https://github.com/dart-lang/async_await/issues/79 is fixed. - return new Future.sync(() { - stopwatch.start(); - - // Pre-cache the root package's known pubspec. - cache.cache(new PackageId.root(root), root.pubspec); - - _validateSdkConstraint(root.pubspec); - return _traverseSolution(); - }).then((packages) { - var pubspecs = new Map.fromIterable( - packages, - key: (id) => id.name, - value: (id) => cache.getCachedPubspec(id)); - - return Future.wait( - packages.map((id) => sources[id.source].resolveId(id))).then((packages) { - return new SolveResult.success( - sources, - root, - lockFile, - packages, - overrides, - pubspecs, - _getAvailableVersions(packages), - attemptedSolutions); - }); - }).catchError((error) { - if (error is! SolveFailure) throw error; - // Wrap a failure in a result so we can attach some other data. - return new SolveResult.failure( - sources, - root, - lockFile, - overrides, - error, - attemptedSolutions); - }).whenComplete(() { - // Gather some solving metrics. - var buffer = new StringBuffer(); - buffer.writeln('${runtimeType} took ${stopwatch.elapsed} seconds.'); - buffer.writeln(cache.describeResults()); - log.solver(buffer); - }); - } - - /// Generates a map containing all of the known available versions for each - /// package in [packages]. - /// - /// The version list may not always be complete. The the package is the root - /// root package, or its a package that we didn't unlock while solving - /// because we weren't trying to upgrade it, we will just know the current - /// version. - Map> _getAvailableVersions(List packages) { - var availableVersions = new Map>(); - for (var package in packages) { - var cached = cache.getCachedVersions(package.toRef()); - var versions; - if (cached != null) { - versions = cached.map((id) => id.version).toList(); - } else { - // If the version list was never requested, just use the one known - // version. - versions = [package.version]; - } - - availableVersions[package.name] = versions; - } - - return availableVersions; - } - - /// Adds [versions], which is the list of all allowed versions of a given - /// package, to the set of versions to consider for solutions. - /// - /// The first item in the list will be the currently selected version of that - /// package. Subsequent items will be tried if it the current selection fails. - /// Returns the first selected version. - PackageId select(VersionQueue versions) { - _selected.add(versions); - logSolve(); - return versions.current; - } - - /// Returns the the currently selected id for the package [name] or `null` if - /// no concrete version has been selected for that package yet. - PackageId getSelected(String name) { - // Always prefer the root package. - if (root.name == name) return new PackageId.root(root); - - // Look through the current selections. - for (var i = _selected.length - 1; i >= 0; i--) { - if (_selected[i].current.name == name) return _selected[i].current; - } - - return null; - } - - /// Gets the version of [package] currently locked in the lock file. - /// - /// Returns `null` if it isn't in the lockfile (or has been unlocked). - PackageId getLocked(String package) { - if (type == SolveType.GET) return lockFile.packages[package]; - - // When downgrading, we don't want to force the latest versions of - // non-hosted packages, since they don't support multiple versions and thus - // can't be downgraded. - if (type == SolveType.DOWNGRADE) { - var locked = lockFile.packages[package]; - if (locked != null && !sources[locked.source].hasMultipleVersions) { - return locked; - } - } - - if (_forceLatest.isEmpty || _forceLatest.contains(package)) return null; - return lockFile.packages[package]; - } - - /// Traverses the root package's dependency graph using the current potential - /// solution. - /// - /// If successful, completes to the solution. If not, backtracks to the most - /// recently selected version of a package and tries the next version of it. - /// If there are no more versions, continues to backtrack to previous - /// selections, and so on. If there is nothing left to backtrack to, - /// completes to the last failure that occurred. - Future> _traverseSolution() => resetStack(() { - return new Traverser(this).traverse().catchError((error) { - if (error is! SolveFailure) throw error; - - return _backtrack(error).then((canTry) { - if (canTry) { - _attemptedSolutions++; - return _traverseSolution(); - } - - // All out of solutions, so fail. - throw error; - }); - }); - }); - - /// Backtracks from the current failed solution and determines the next - /// solution to try. - /// - /// If possible, it will backjump based on the cause of the [failure] to - /// minize backtracking. Otherwise, it will simply backtrack to the next - /// possible solution. - /// - /// Returns `true` if there is a new solution to try. - Future _backtrack(SolveFailure failure) { - // Bail if there is nothing to backtrack to. - if (_selected.isEmpty) return new Future.value(false); - - // Mark any packages that may have led to this failure so that we know to - // consider them when backtracking. - var dependers = _getTransitiveDependers(failure.package); - - for (var selected in _selected) { - if (dependers.contains(selected.current.name)) { - selected.fail(); - } - } - - // Advance past the current version of the leaf-most package. - advanceVersion() { - _backjump(failure); - var previous = _selected.last.current; - return _selected.last.advance().then((success) { - if (success) { - logSolve(); - return true; - } - - logSolve('$previous is last version, backtracking'); - - // That package has no more versions, so pop it and try the next one. - _selected.removeLast(); - if (_selected.isEmpty) return false; - - // If we got here, the leafmost package was discarded so we need to - // advance the next one. - return advanceVersion(); - }); - } - - return advanceVersion(); - } - - /// Walks the selected packages from most to least recent to determine which - /// ones can be ignored and jumped over by the backtracker. - /// - /// The only packages we need to backtrack to are ones that led (possibly - /// indirectly) to the failure. Everything else can be skipped. - void _backjump(SolveFailure failure) { - for (var i = _selected.length - 1; i >= 0; i--) { - // Each queue will never be empty since it gets discarded by _backtrack() - // when that happens. - var selected = _selected[i].current; - - // If the failure is a disjoint version range, then no possible versions - // for that package can match and there's no reason to try them. Instead, - // just backjump past it. - if (failure is DisjointConstraintException && - selected.name == failure.package) { - logSolve("skipping past disjoint selected ${selected.name}"); - continue; - } - - if (_selected[i].hasFailed) { - logSolve('backjump to ${selected.name}'); - _selected.removeRange(i + 1, _selected.length); - return; - } - } - - // If we got here, we walked the entire list without finding a package that - // could lead to another solution, so discard everything. This will happen - // if every package that led to the failure has no other versions that it - // can try to select. - _selected.removeRange(1, _selected.length); - } - - /// Gets the set of currently selected packages that depend on [dependency] - /// either directly or indirectly. - /// - /// When backtracking, it's only useful to consider changing the version of - /// packages who have a dependency on the failed package that triggered - /// backtracking. This is used to determine those packages. - /// - /// We calculate the full set up front before backtracking because during - /// backtracking, we will unselect packages and start to lose this - /// information in the middle of the process. - /// - /// For example, consider dependencies A -> B -> C. We've selected A and B - /// then encounter a problem with C. We start backtracking. B has no more - /// versions so we discard it and keep backtracking to A. When we get there, - /// since we've unselected B, we no longer realize that A had a transitive - /// dependency on C. We would end up backjumping over A and failing. - /// - /// Calculating the dependency set up front before we start backtracking - /// solves that. - Set _getTransitiveDependers(String dependency) { - // Generate a reverse dependency graph. For each package, create edges to - // each package that depends on it. - var dependers = new Map>(); - - addDependencies(name, deps) { - dependers.putIfAbsent(name, () => new Set()); - for (var dep in deps) { - dependers.putIfAbsent(dep.name, () => new Set()).add(name); - } - } - - for (var i = 0; i < _selected.length; i++) { - var id = _selected[i].current; - var pubspec = cache.getCachedPubspec(id); - if (pubspec != null) addDependencies(id.name, pubspec.dependencies); - } - - // Include the root package's dependencies. - addDependencies(root.name, root.immediateDependencies); - - // Now walk the depending graph to see which packages transitively depend - // on [dependency]. - var visited = new Set(); - walk(String package) { - // Don't get stuck in cycles. - if (visited.contains(package)) return; - visited.add(package); - var depender = dependers[package].forEach(walk); - } - - walk(dependency); - return visited; - } - - /// Logs the initial parameters to the solver. - void _logParameters() { - var buffer = new StringBuffer(); - buffer.writeln("Solving dependencies:"); - for (var package in root.dependencies) { - buffer.write("- $package"); - var locked = getLocked(package.name); - if (_forceLatest.contains(package.name)) { - buffer.write(" (use latest)"); - } else if (locked != null) { - var version = locked.version; - buffer.write(" (locked to $version)"); - } - buffer.writeln(); - } - log.solver(buffer.toString().trim()); - } - - /// Logs [message] in the context of the current selected packages. - /// - /// If [message] is omitted, just logs a description of leaf-most selection. - void logSolve([String message]) { - if (message == null) { - if (_selected.isEmpty) { - message = "* start at root"; - } else { - message = "* select ${_selected.last.current}"; - } - } else { - // Otherwise, indent it under the current selected package. - message = prefixLines(message); - } - - // Indent for the previous selections. - var prefix = _selected.skip(1).map((_) => '| ').join(); - log.solver(prefixLines(message, prefix: prefix)); - } -} - -/// Given the solver's current set of selected package versions, this tries to -/// traverse the dependency graph and see if a complete set of valid versions -/// has been chosen. -/// -/// If it reaches a conflict, it fails and stops traversing. If it reaches a -/// package that isn't selected, it refines the solution by adding that -/// package's set of allowed versions to the solver and then select the best -/// one and continuing. -class Traverser { - final BacktrackingSolver _solver; - - /// The queue of packages left to traverse. - /// - /// We do a breadth-first traversal using an explicit queue just to avoid the - /// code complexity of a recursive asynchronous traversal. - final _packages = new Queue(); - - /// The packages we have already traversed. - /// - /// Used to avoid traversing the same package multiple times, and to build - /// the complete solution results. - final _visited = new Set(); - - /// The dependencies visited so far in the traversal. - /// - /// For each package name (the map key) we track the list of dependencies - /// that other packages have placed on it so that we can calculate the - /// complete constraint for shared dependencies. - final _dependencies = >{}; - - Traverser(this._solver); - - /// Walks the dependency graph starting at the root package and validates - /// that each reached package has a valid version selected. - Future> traverse() { - // Start at the root. - _packages.add(new PackageId.root(_solver.root)); - return _traversePackage(); - } - - /// Traverses the next package in the queue. - /// - /// Completes to a list of package IDs if the traversal completed - /// successfully and found a solution. Completes to an error if the traversal - /// failed. Otherwise, recurses to the next package in the queue, etc. - Future> _traversePackage() { - if (_packages.isEmpty) { - // We traversed the whole graph. If we got here, we successfully found - // a solution. - return new Future>.value(_visited.toList()); - } - - var id = _packages.removeFirst(); - - // Don't visit the same package twice. - if (_visited.contains(id)) { - return _traversePackage(); - } - _visited.add(id); - - return _solver.cache.getPubspec(id).then((pubspec) { - _validateSdkConstraint(pubspec); - - var deps = pubspec.dependencies.toSet(); - - if (id.isRoot) { - // Include dev dependencies of the root package. - deps.addAll(pubspec.devDependencies); - - // Add all overrides. This ensures a dependency only present as an - // override is still included. - deps.addAll(_solver._overrides.values); - } - - // Replace any overridden dependencies. - deps = deps.map((dep) { - var override = _solver._overrides[dep.name]; - if (override != null) return override; - - // Not overridden. - return dep; - }).toSet(); - - // Make sure the package doesn't have any bad dependencies. - for (var dep in deps) { - if (!dep.isRoot && _solver.sources[dep.source] is UnknownSource) { - throw new UnknownSourceException( - id.name, - [new Dependency(id.name, id.version, dep)]); - } - } - - return _traverseDeps(id, new DependencyQueue(_solver, deps)); - }).catchError((error) { - if (error is! PackageNotFoundException) throw error; - - // We can only get here if the lockfile refers to a specific package - // version that doesn't exist (probably because it was yanked). - throw new NoVersionException(id.name, null, id.version, []); - }); - } - - /// Traverses the references that [depender] depends on, stored in [deps]. - /// - /// Desctructively modifies [deps]. Completes to a list of packages if the - /// traversal is complete. Completes it to an error if a failure occurred. - /// Otherwise, recurses. - Future> _traverseDeps(PackageId depender, - DependencyQueue deps) { - // Move onto the next package if we've traversed all of these references. - if (deps.isEmpty) return _traversePackage(); - - return resetStack(() { - return deps.advance().then((dep) { - var dependency = new Dependency(depender.name, depender.version, dep); - return _registerDependency(dependency).then((_) { - if (dep.name == "barback") return _addImplicitDependencies(); - }); - }).then((_) => _traverseDeps(depender, deps)); - }); - } - - /// Register [dependency]'s constraints on the package it depends on and - /// enqueues the package for processing if necessary. - Future _registerDependency(Dependency dependency) { - return new Future.sync(() { - _validateDependency(dependency); - - var dep = dependency.dep; - var dependencies = _getDependencies(dep.name); - dependencies.add(dependency); - - var constraint = _getConstraint(dep.name); - - // See if it's possible for a package to match that constraint. - if (constraint.isEmpty) { - var constraints = dependencies.map( - (dep) => " ${dep.dep.constraint} from ${dep.depender}").join('\n'); - _solver.logSolve('disjoint constraints on ${dep.name}:\n$constraints'); - throw new DisjointConstraintException(dep.name, dependencies); - } - - var selected = _validateSelected(dep, constraint); - if (selected != null) { - // The selected package version is good, so enqueue it to traverse - // into it. - _packages.add(selected); - return null; - } - - // We haven't selected a version. Try all of the versions that match - // the constraints we currently have for this package. - var locked = _getValidLocked(dep.name); - - return VersionQueue.create(locked, () { - return _getAllowedVersions(dep); - }).then((versions) => _packages.add(_solver.select(versions))); - }); - } - - /// Gets all versions of [dep] that match the current constraints placed on - /// it. - Future> _getAllowedVersions(PackageDep dep) { - var constraint = _getConstraint(dep.name); - return _solver.cache.getVersions(dep.toRef()).then((versions) { - var allowed = versions.where((id) => constraint.allows(id.version)); - - if (allowed.isEmpty) { - _solver.logSolve('no versions for ${dep.name} match $constraint'); - throw new NoVersionException( - dep.name, - null, - constraint, - _getDependencies(dep.name)); - } - - // If we're doing an upgrade on this package, only allow the latest - // version. - if (_solver._forceLatest.contains(dep.name)) allowed = [allowed.first]; - - // Remove the locked version, if any, since that was already handled. - var locked = _getValidLocked(dep.name); - if (locked != null) { - allowed = allowed.where((dep) => dep.version != locked.version); - } - - return allowed; - }).catchError((error, stackTrace) { - if (error is PackageNotFoundException) { - // Show the user why the package was being requested. - throw new DependencyNotFoundException( - dep.name, - error, - _getDependencies(dep.name)); - } - - throw error; - }); - } - - /// Ensures that dependency [dep] from [depender] is consistent with the - /// other dependencies on the same package. - /// - /// Throws a [SolveFailure] exception if not. Only validates sources and - /// descriptions, not the version. - void _validateDependency(Dependency dependency) { - var dep = dependency.dep; - - // Make sure the dependencies agree on source and description. - var required = _getRequired(dep.name); - if (required == null) return; - - // Make sure all of the existing sources match the new reference. - if (required.dep.source != dep.source) { - _solver.logSolve( - 'source mismatch on ${dep.name}: ${required.dep.source} ' '!= ${dep.source}'); - throw new SourceMismatchException(dep.name, [required, dependency]); - } - - // Make sure all of the existing descriptions match the new reference. - var source = _solver.sources[dep.source]; - if (!source.descriptionsEqual(dep.description, required.dep.description)) { - _solver.logSolve( - 'description mismatch on ${dep.name}: ' - '${required.dep.description} != ${dep.description}'); - throw new DescriptionMismatchException(dep.name, [required, dependency]); - } - } - - /// Validates the currently selected package against the new dependency that - /// [dep] and [constraint] place on it. - /// - /// Returns `null` if there is no currently selected package, throws a - /// [SolveFailure] if the new reference it not does not allow the previously - /// selected version, or returns the selected package if successful. - PackageId _validateSelected(PackageDep dep, VersionConstraint constraint) { - var selected = _solver.getSelected(dep.name); - if (selected == null) return null; - - // Make sure it meets the constraint. - if (!dep.constraint.allows(selected.version)) { - _solver.logSolve('selection $selected does not match $constraint'); - throw new NoVersionException( - dep.name, - selected.version, - constraint, - _getDependencies(dep.name)); - } - - return selected; - } - - /// Register pub's implicit dependencies. - /// - /// Pub has an implicit version constraint on barback and various other - /// packages used in barback's plugin isolate. - Future _addImplicitDependencies() { - /// Ensure we only add the barback dependency once. - if (_getDependencies("barback").length != 1) return new Future.value(); - - return Future.wait(barback.pubConstraints.keys.map((depName) { - var constraint = barback.pubConstraints[depName]; - _solver.logSolve( - 'add implicit $constraint pub dependency on ' '$depName'); - - var override = _solver._overrides[depName]; - - // Use the same source and description as the dependency override if one - // exists. This is mainly used by the pkgbuild tests, which use dependency - // overrides for all repo packages. - var pubDep = override == null ? - new PackageDep(depName, "hosted", constraint, depName) : - override.withConstraint(constraint); - return _registerDependency( - new Dependency("pub itself", Version.none, pubDep)); - })); - } - - /// Gets the list of dependencies for package [name]. - /// - /// Creates an empty list if needed. - List _getDependencies(String name) { - return _dependencies.putIfAbsent(name, () => []); - } - - /// Gets a "required" reference to the package [name]. - /// - /// This is the first non-root dependency on that package. All dependencies - /// on a package must agree on source and description, except for references - /// to the root package. This will return a reference to that "canonical" - /// source and description, or `null` if there is no required reference yet. - /// - /// This is required because you may have a circular dependency back onto the - /// root package. That second dependency won't be a root dependency and it's - /// *that* one that other dependencies need to agree on. In other words, you - /// can have a bunch of dependencies back onto the root package as long as - /// they all agree with each other. - Dependency _getRequired(String name) { - return _getDependencies( - name).firstWhere((dep) => !dep.dep.isRoot, orElse: () => null); - } - - /// Gets the combined [VersionConstraint] currently being placed on package - /// [name]. - VersionConstraint _getConstraint(String name) { - var constraint = _getDependencies( - name).map( - (dep) => - dep.dep.constraint).fold(VersionConstraint.any, (a, b) => a.intersect(b)); - - return constraint; - } - - /// Gets the package [name] that's currently contained in the lockfile if it - /// meets [constraint] and has the same source and description as other - /// references to that package. - /// - /// Returns `null` otherwise. - PackageId _getValidLocked(String name) { - var package = _solver.getLocked(name); - if (package == null) return null; - - var constraint = _getConstraint(name); - if (!constraint.allows(package.version)) { - _solver.logSolve('$package is locked but does not match $constraint'); - return null; - } else { - _solver.logSolve('$package is locked'); - } - - var required = _getRequired(name); - if (required != null) { - if (package.source != required.dep.source) return null; - - var source = _solver.sources[package.source]; - if (!source.descriptionsEqual( - package.description, - required.dep.description)) return null; - } - - return package; - } -} - -/// Ensures that if [pubspec] has an SDK constraint, then it is compatible -/// with the current SDK. -/// -/// Throws a [SolveFailure] if not. -void _validateSdkConstraint(Pubspec pubspec) { - if (pubspec.environment.sdkVersion.allows(sdk.version)) return; - - throw new BadSdkVersionException( - pubspec.name, - 'Package ${pubspec.name} requires SDK version ' - '${pubspec.environment.sdkVersion} but the current SDK is ' '${sdk.version}.'); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/dependency_queue.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/dependency_queue.dart deleted file mode 100644 index 07fdbc45c37..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/solver/dependency_queue.dart +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.solver.dependency_queue; - -import 'dart:async'; -import 'dart:collection' show Queue; - -import '../log.dart' as log; -import '../package.dart'; -import 'backtracking_solver.dart'; - -/// A queue of one package's dependencies, ordered by how the solver should -/// traverse them. -/// -/// It prefers locked versions so that they stay locked if possible. Then it -/// prefers a currently selected package so that it only has to consider a -/// single version. -/// -/// After that, it orders the remaining packages by the number of versions they -/// have so that packages with fewer versions are solved first. (If two -/// packages have the same number of versions, they are sorted alphabetically -/// just to be deterministic.) -/// -/// Critically, this queue will *not* sort the dependencies by number of -/// versions until actually needed. This ensures we don't do any network -/// requests until we actually need to. In particular, it means that solving -/// a package graph with an already up-to-date lockfile will do no network -/// requests. -class DependencyQueue { - final BacktrackingSolver _solver; - - /// The dependencies for packages that have already been selected. - final Queue _presorted; - - /// The dependencies on the remaining packages. - /// - /// This is lazily sorted right before the first item is requested. - final List _remaining; - - bool _isSorted = false; - - /// Gets whether there are any dependencies left to iterate over. - bool get isEmpty => _presorted.isEmpty && _remaining.isEmpty; - - /// The pending [Future] while the remaining dependencies are being sorted. - /// - /// This will only be non-null while a sort is in progress. - Future _sortFuture; - - factory DependencyQueue(BacktrackingSolver solver, Iterable deps) - { - // Separate out the presorted ones. - var presorted = []; - var remaining = []; - - for (var dep in deps) { - // Selected or locked packages come first. - if (solver.getSelected(dep.name) != null || - solver.getLocked(dep.name) != null) { - presorted.add(dep); - } else { - remaining.add(dep); - } - } - - // Sort the selected/locked packages by name just to ensure the solver is - // deterministic. - presorted.sort((a, b) => a.name.compareTo(b.name)); - - return new DependencyQueue._( - solver, - new Queue.from(presorted), - remaining); - } - - DependencyQueue._(this._solver, this._presorted, this._remaining); - - /// Emits the next dependency in priority order. - /// - /// It is an error to call this if [isEmpty] returns `true`. Note that this - /// function is *not* re-entrant. You should only advance after the previous - /// advance has completed. - Future advance() { - // Emit the sorted ones first. - if (_presorted.isNotEmpty) { - return new Future.value(_presorted.removeFirst()); - } - - // Sort the remaining packages when we need the first one. - if (!_isSorted) return _sort().then((_) => _remaining.removeAt(0)); - - return new Future.value(_remaining.removeAt(0)); - } - - /// Sorts the unselected packages by number of versions and name. - Future _sort() { - // Sorting is not re-entrant. - assert(_sortFuture == null); - - _sortFuture = Future.wait(_remaining.map(_getNumVersions)).then((versions) { - _sortFuture = null; - - // Map deps to the number of versions they have. - var versionMap = new Map.fromIterables(_remaining, versions); - - // Sort in best-first order to minimize backtracking. - _remaining.sort((a, b) { - // Traverse into packages with fewer versions since they will lead to - // less backtracking. - if (versionMap[a] != versionMap[b]) { - return versionMap[a].compareTo(versionMap[b]); - } - - // Otherwise, just sort by name so that it's deterministic. - return a.name.compareTo(b.name); - }); - - _isSorted = true; - }); - - return _sortFuture; - } - - /// Given a dependency, returns a future that completes to the number of - /// versions available for it. - Future _getNumVersions(PackageDep dep) { - // There is only ever one version of the root package. - if (dep.isRoot) { - return new Future.value(1); - } - - return _solver.cache.getVersions(dep.toRef()).then((versions) { - // If the root package depends on this one, ignore versions that don't - // match that constraint. Since the root package's dependency constraints - // won't change during solving, we can safely filter out packages that - // don't meet it. - for (var rootDep in _solver.root.immediateDependencies) { - if (rootDep.name == dep.name) { - versions = - versions.where((id) => rootDep.constraint.allows(id.version)); - break; - } - } - - return versions.length; - }).catchError((error, trace) { - // If it fails for any reason, just treat that as no versions. This - // will sort this reference higher so that we can traverse into it - // and report the error more properly. - log.solver("Could not get versions for $dep:\n$error\n\n$trace"); - return 0; - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/solve_report.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/solve_report.dart deleted file mode 100644 index 4e6cfa60335..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/solver/solve_report.dart +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.solver.solve_report; - -import 'package:pub_semver/pub_semver.dart'; - -import '../lock_file.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../source_registry.dart'; -import '../utils.dart'; -import 'version_solver.dart'; - -/// Unlike [SolveResult], which is the static data describing a resolution, -/// this class contains the mutable state used while generating the report -/// itself. -/// -/// It's a report builder. -class SolveReport { - final SolveType _type; - final SourceRegistry _sources; - final Package _root; - final LockFile _previousLockFile; - final SolveResult _result; - - /// The dependencies in [_result], keyed by package name. - final _dependencies = new Map(); - - final _output = new StringBuffer(); - - SolveReport(this._type, this._sources, this._root, this._previousLockFile, - this._result) { - // Fill the map so we can use it later. - for (var id in _result.packages) { - _dependencies[id.name] = id; - } - } - - /// Displays a report of the results of the version resolution relative to - /// the previous lock file. - void show() { - _reportChanges(); - _reportOverrides(); - } - - /// Displays a one-line message summarizing what changes were made (or would - /// be made) to the lockfile. - /// - /// If [dryRun] is true, describes it in terms of what would be done. - void summarize({bool dryRun: false}) { - // Count how many dependencies actually changed. - var dependencies = _dependencies.keys.toSet(); - dependencies.addAll(_previousLockFile.packages.keys); - dependencies.remove(_root.name); - - var numChanged = dependencies.where((name) { - var oldId = _previousLockFile.packages[name]; - var newId = _dependencies[name]; - - // Added or removed dependencies count. - if (oldId == null) return true; - if (newId == null) return true; - - // The dependency existed before, so see if it was modified. - return !_sources.idsEqual(oldId, newId); - }).length; - - if (dryRun) { - if (numChanged == 0) { - log.message("No dependencies would change."); - } else if (numChanged == 1) { - log.message("Would change $numChanged dependency."); - } else { - log.message("Would change $numChanged dependencies."); - } - } else { - if (numChanged == 0) { - if (_type == SolveType.GET) { - log.message("Got dependencies!"); - } else { - log.message("No dependencies changed."); - } - } else if (numChanged == 1) { - log.message("Changed $numChanged dependency!"); - } else { - log.message("Changed $numChanged dependencies!"); - } - } - } - - /// Displays a report of all of the previous and current dependencies and - /// how they have changed. - void _reportChanges() { - _output.clear(); - - // Show the new set of dependencies ordered by name. - var names = _result.packages.map((id) => id.name).toList(); - names.remove(_root.name); - names.sort(); - names.forEach(_reportPackage); - - // Show any removed ones. - var removed = _previousLockFile.packages.keys.toSet(); - removed.removeAll(names); - if (removed.isNotEmpty) { - _output.writeln("These packages are no longer being depended on:"); - removed = removed.toList(); - removed.sort(); - removed.forEach((name) => _reportPackage(name, alwaysShow: true)); - } - - log.message(_output); - } - - /// Displays a warning about the overrides currently in effect. - void _reportOverrides() { - _output.clear(); - - if (_result.overrides.isNotEmpty) { - _output.writeln("Warning: You are using these overridden dependencies:"); - var overrides = _result.overrides.map((dep) => dep.name).toList(); - overrides.sort((a, b) => a.compareTo(b)); - - overrides.forEach( - (name) => _reportPackage(name, alwaysShow: true, highlightOverride: false)); - - log.warning(_output); - } - } - - /// Reports the results of the upgrade on the package named [name]. - /// - /// If [alwaysShow] is true, the package is reported even if it didn't change, - /// regardless of [_type]. If [highlightOverride] is true (or absent), writes - /// "(override)" next to overridden packages. - void _reportPackage(String name, {bool alwaysShow: false, - bool highlightOverride: true}) { - var newId = _dependencies[name]; - var oldId = _previousLockFile.packages[name]; - var id = newId != null ? newId : oldId; - - var isOverridden = - _result.overrides.map((dep) => dep.name).contains(id.name); - - // If the package was previously a dependency but the dependency has - // changed in some way. - var changed = false; - - // If the dependency was added or removed. - var addedOrRemoved = false; - - // Show a one-character "icon" describing the change. They are: - // - // ! The package is being overridden. - // - The package was removed. - // + The package was added. - // > The package was upgraded from a lower version. - // < The package was downgraded from a higher version. - // * Any other change between the old and new package. - var icon; - if (isOverridden) { - icon = log.magenta("! "); - } else if (newId == null) { - icon = log.red("- "); - addedOrRemoved = true; - } else if (oldId == null) { - icon = log.green("+ "); - addedOrRemoved = true; - } else if (!_sources.idDescriptionsEqual(oldId, newId)) { - icon = log.cyan("* "); - changed = true; - } else if (oldId.version < newId.version) { - icon = log.green("> "); - changed = true; - } else if (oldId.version > newId.version) { - icon = log.cyan("< "); - changed = true; - } else { - // Unchanged. - icon = " "; - } - - if (_type == SolveType.GET && !(alwaysShow || changed || addedOrRemoved)) { - return; - } - - _output.write(icon); - _output.write(log.bold(id.name)); - _output.write(" "); - _writeId(id); - - // If the package was upgraded, show what it was upgraded from. - if (changed) { - _output.write(" (was "); - _writeId(oldId); - _output.write(")"); - } - - // Highlight overridden packages. - if (isOverridden && highlightOverride) { - _output.write(" ${log.magenta('(overridden)')}"); - } - - // See if there are any newer versions of the package that we were - // unable to upgrade to. - if (newId != null && _type != SolveType.DOWNGRADE) { - var versions = _result.availableVersions[newId.name]; - - var newerStable = false; - var newerUnstable = false; - - for (var version in versions) { - if (version > newId.version) { - if (version.isPreRelease) { - newerUnstable = true; - } else { - newerStable = true; - } - } - } - - // If there are newer stable versions, only show those. - var message; - if (newerStable) { - message = "(${maxAll(versions, Version.prioritize)} available)"; - } else if (newerUnstable) { - message = "(${maxAll(versions)} available)"; - } - - if (message != null) _output.write(" ${log.cyan(message)}"); - } - - _output.writeln(); - } - - /// Writes a terse description of [id] (not including its name) to the output. - void _writeId(PackageId id) { - _output.write(id.version); - - var source = _sources[id.source]; - if (source != _sources.defaultSource) { - var description = source.formatDescription(_root.dir, id.description); - _output.write(" from ${id.source} $description"); - } - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/version_queue.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/version_queue.dart deleted file mode 100644 index 86c6e987128..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/solver/version_queue.dart +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.solver.version_queue; - -import 'dart:async'; -import 'dart:collection' show Queue; - -import '../package.dart'; - -/// A function that asynchronously returns a sequence of package IDs. -typedef Future> PackageIdGenerator(); - -/// A prioritized, asynchronous queue of the possible versions that can be -/// selected for one package. -/// -/// If there is a locked version, that comes first, followed by other versions -/// in descending order. This avoids requesting the list of versions until -/// needed (i.e. after any locked version has been consumed) to avoid unneeded -/// network requests. -class VersionQueue { - /// The set of allowed versions that match [_constraint]. - /// - /// If [_locked] is not `null`, this will initially be `null` until we - /// advance past the locked version. - Queue _allowed; - - /// The callback that will generate the sequence of packages. This will be - /// called as lazily as possible. - final PackageIdGenerator _allowedGenerator; - - /// The currently locked version of the package, or `null` if there is none, - /// or we have advanced past it. - PackageId _locked; - - /// Gets the currently selected version. - PackageId get current { - if (_locked != null) return _locked; - return _allowed.first; - } - - /// Whether the currently selected version has been responsible for a solve - /// failure, or depends on a package that has. - /// - /// The solver uses this to determine which packages to backtrack to after a - /// failure occurs. Any selected package that did *not* cause the failure can - /// be skipped by the backtracker. - bool get hasFailed => _hasFailed; - bool _hasFailed = false; - - /// Creates a new [VersionQueue] queue for starting with the optional - /// [locked] package followed by the results of calling [allowedGenerator]. - /// - /// This is asynchronous so that [current] can always be accessed - /// synchronously. If there is no locked version, we need to get the list of - /// versions asynchronously before we can determine what the first one is. - static Future create(PackageId locked, - PackageIdGenerator allowedGenerator) { - var versions = new VersionQueue._(locked, allowedGenerator); - - // If there is a locked version, it's the current one so it's synchronously - // available now. - if (locked != null) return new Future.value(versions); - - // Otherwise, the current version needs to be calculated before we can - // return. - return versions._calculateAllowed().then((_) => versions); - } - - VersionQueue._(this._locked, this._allowedGenerator); - - /// Tries to advance to the next possible version. - /// - /// Returns `true` if it moved to a new version (which can be accessed from - /// [current]. Returns `false` if there are no more versions. - Future advance() { - // Any failure was the fault of the previous version, not necessarily the - // new one. - _hasFailed = false; - - // If we have a locked version, consume it first. - if (_locked != null) { - // Advancing past the locked version, so need to load the others now - // so that [current] is available. - return _calculateAllowed().then((_) { - _locked = null; - return _allowed.isNotEmpty; - }); - } - - // Move to the next allowed version. - _allowed.removeFirst(); - return new Future.value(_allowed.isNotEmpty); - } - - /// Marks the selected version as being directly or indirectly responsible - /// for a solve failure. - void fail() { - _hasFailed = true; - } - - /// Determines the list of allowed versions matching its constraint and places - /// them in [_allowed]. - Future _calculateAllowed() { - return _allowedGenerator().then((allowed) { - _allowed = new Queue.from(allowed); - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/solver/version_solver.dart b/sdk/lib/_internal/pub_generated/lib/src/solver/version_solver.dart deleted file mode 100644 index d22ace779d7..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/solver/version_solver.dart +++ /dev/null @@ -1,510 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.solver.version_solver; - -import 'dart:async'; -import "dart:convert"; - -import 'package:pub_semver/pub_semver.dart'; -import 'package:stack_trace/stack_trace.dart'; - -import '../exceptions.dart'; -import '../lock_file.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../pubspec.dart'; -import '../source_registry.dart'; -import '../utils.dart'; -import 'backtracking_solver.dart'; -import 'solve_report.dart'; - -/// Attempts to select the best concrete versions for all of the transitive -/// dependencies of [root] taking into account all of the [VersionConstraint]s -/// that those dependencies place on each other and the requirements imposed by -/// [lockFile]. -/// -/// If [useLatest] is given, then only the latest versions of the referenced -/// packages will be used. This is for forcing an upgrade to one or more -/// packages. -/// -/// If [upgradeAll] is true, the contents of [lockFile] are ignored. -Future resolveVersions(SolveType type, SourceRegistry sources, - Package root, {LockFile lockFile, List useLatest}) { - if (lockFile == null) lockFile = new LockFile.empty(); - if (useLatest == null) useLatest = []; - - return log.progress('Resolving dependencies', () { - return new BacktrackingSolver( - type, - sources, - root, - lockFile, - useLatest).solve(); - }); -} - -/// The result of a version resolution. -class SolveResult { - /// Whether the solver found a complete solution or failed. - bool get succeeded => error == null; - - /// The list of concrete package versions that were selected for each package - /// reachable from the root, or `null` if the solver failed. - final List packages; - - /// The dependency overrides that were used in the solution. - final List overrides; - - /// A map from package names to the pubspecs for the versions of those - /// packages that were installed, or `null` if the solver failed. - final Map pubspecs; - - /// The available versions of all selected packages from their source. - /// - /// Will be empty if the solve failed. An entry here may not include the full - /// list of versions available if the given package was locked and did not - /// need to be unlocked during the solve. - final Map> availableVersions; - - /// The error that prevented the solver from finding a solution or `null` if - /// it was successful. - final SolveFailure error; - - /// The number of solutions that were attempted before either finding a - /// successful solution or exhausting all options. - /// - /// In other words, one more than the number of times it had to backtrack - /// because it found an invalid solution. - final int attemptedSolutions; - - final SourceRegistry _sources; - final Package _root; - final LockFile _previousLockFile; - - /// Returns the names of all packages that were changed. - /// - /// This includes packages that were added or removed. - Set get changedPackages { - if (packages == null) return null; - - var changed = packages.where( - (id) => - !_sources.idsEqual( - _previousLockFile.packages[id.name], - id)).map((id) => id.name).toSet(); - - return changed.union( - _previousLockFile.packages.keys.where( - (package) => !availableVersions.containsKey(package)).toSet()); - } - - SolveResult.success(this._sources, this._root, this._previousLockFile, - this.packages, this.overrides, this.pubspecs, this.availableVersions, - this.attemptedSolutions) - : error = null; - - SolveResult.failure(this._sources, this._root, this._previousLockFile, - this.overrides, this.error, this.attemptedSolutions) - : this.packages = null, - this.pubspecs = null, - this.availableVersions = {}; - - /// Displays a report of what changes were made to the lockfile. - /// - /// [type] is the type of version resolution that was run. - void showReport(SolveType type) { - new SolveReport(type, _sources, _root, _previousLockFile, this).show(); - } - - /// Displays a one-line message summarizing what changes were made (or would - /// be made) to the lockfile. - /// - /// [type] is the type of version resolution that was run. - void summarizeChanges(SolveType type, {bool dryRun: false}) { - new SolveReport( - type, - _sources, - _root, - _previousLockFile, - this).summarize(dryRun: dryRun); - } - - String toString() { - if (!succeeded) { - return 'Failed to solve after $attemptedSolutions attempts:\n' '$error'; - } - - return 'Took $attemptedSolutions tries to resolve to\n' - '- ${packages.join("\n- ")}'; - } -} - -/// Maintains a cache of previously-requested data: pubspecs and version lists. -/// -/// Used to avoid requesting the same pubspec from the server repeatedly. -class PubspecCache { - final SourceRegistry _sources; - - /// The already-requested cached version lists. - final _versions = new Map>(); - - /// The errors from failed version list requests. - final _versionErrors = new Map>(); - - /// The already-requested cached pubspecs. - final _pubspecs = new Map(); - - /// The type of version resolution that was run. - final SolveType _type; - - /// The number of times a version list was requested and it wasn't cached and - /// had to be requested from the source. - int _versionCacheMisses = 0; - - /// The number of times a version list was requested and the cached version - /// was returned. - int _versionCacheHits = 0; - - /// The number of times a pubspec was requested and it wasn't cached and had - /// to be requested from the source. - int _pubspecCacheMisses = 0; - - /// The number of times a pubspec was requested and the cached version was - /// returned. - int _pubspecCacheHits = 0; - - PubspecCache(this._type, this._sources); - - /// Caches [pubspec] as the [Pubspec] for the package identified by [id]. - void cache(PackageId id, Pubspec pubspec) { - _pubspecs[id] = pubspec; - } - - /// Loads the pubspec for the package identified by [id]. - Future getPubspec(PackageId id) { - // Complete immediately if it's already cached. - if (_pubspecs.containsKey(id)) { - _pubspecCacheHits++; - return new Future.value(_pubspecs[id]); - } - - _pubspecCacheMisses++; - - var source = _sources[id.source]; - return source.describe(id).then((pubspec) { - _pubspecs[id] = pubspec; - return pubspec; - }); - } - - /// Returns the previously cached pubspec for the package identified by [id] - /// or returns `null` if not in the cache. - Pubspec getCachedPubspec(PackageId id) => _pubspecs[id]; - - /// Gets the list of versions for [package]. - /// - /// Packages are sorted in descending version order with all "stable" - /// versions (i.e. ones without a prerelease suffix) before pre-release - /// versions. This ensures that the solver prefers stable packages over - /// unstable ones. - Future> getVersions(PackageRef package) { - if (package.isRoot) { - throw new StateError("Cannot get versions for root package $package."); - } - - // See if we have it cached. - var versions = _versions[package]; - if (versions != null) { - _versionCacheHits++; - return new Future.value(versions); - } - - // See if we cached a failure. - var error = _versionErrors[package]; - if (error != null) { - _versionCacheHits++; - return new Future.error(error.first, error.last); - } - - _versionCacheMisses++; - - var source = _sources[package.source]; - return source.getVersions( - package.name, - package.description).then((versions) { - // Sort by priority so we try preferred versions first. - versions.sort( - _type == SolveType.DOWNGRADE ? Version.antiprioritize : Version.prioritize); - - var ids = - versions.reversed.map((version) => package.atVersion(version)).toList(); - _versions[package] = ids; - return ids; - }).catchError((error, trace) { - // If an error occurs, cache that too. We only want to do one request - // for any given package, successful or not. - log.solver("Could not get versions for $package:\n$error\n\n$trace"); - _versionErrors[package] = new Pair(error, new Chain.forTrace(trace)); - throw error; - }); - } - - /// Returns the previously cached list of versions for the package identified - /// by [package] or returns `null` if not in the cache. - List getCachedVersions(PackageRef package) => _versions[package]; - - /// Returns a user-friendly output string describing metrics of the solve. - String describeResults() { - var results = '''- Requested $_versionCacheMisses version lists -- Looked up $_versionCacheHits cached version lists -- Requested $_pubspecCacheMisses pubspecs -- Looked up $_pubspecCacheHits cached pubspecs -'''; - - // Uncomment this to dump the visited package graph to JSON. - //results += _debugWritePackageGraph(); - - return results; - } - - /// This dumps the set of packages that were looked at by the solver to a - /// JSON map whose format matches the map passed to [testResolve] in the - /// version solver unit tests. - /// - /// If a real-world version solve is failing, this can be used to mirror that - /// data to build a regression test using mock packages. - String _debugDescribePackageGraph() { - var packages = {}; - _pubspecs.forEach((id, pubspec) { - var deps = {}; - packages["${id.name} ${id.version}"] = deps; - - for (var dep in pubspec.dependencies) { - deps[dep.name] = dep.constraint.toString(); - } - }); - - // Add in the packages that we know of but didn't need their pubspecs. - _versions.forEach((ref, versions) { - for (var id in versions) { - packages.putIfAbsent("${id.name} ${id.version}", () => {}); - } - }); - - // TODO(rnystrom): Include dev dependencies and dependency overrides. - - return JSON.encode(packages); - } -} - -/// A reference from a depending package to a package that it depends on. -class Dependency { - /// The name of the package that has this dependency. - final String depender; - - /// The version of the depender that has this dependency. - final Version dependerVersion; - - /// The package being depended on. - final PackageDep dep; - - /// Whether [depender] is a magic dependency (e.g. "pub itself" or "pub global - /// activate"). - bool get isMagic => depender.contains(" "); - - - Dependency(this.depender, this.dependerVersion, this.dep); - - String toString() => '$depender $dependerVersion -> $dep'; -} - -/// An enum for types of version resolution. -class SolveType { - /// As few changes to the lockfile as possible to be consistent with the - /// pubspec. - static const GET = const SolveType._("get"); - - /// Upgrade all packages or specific packages to the highest versions - /// possible, regardless of the lockfile. - static const UPGRADE = const SolveType._("upgrade"); - - /// Downgrade all packages or specific packages to the lowest versions - /// possible, regardless of the lockfile. - static const DOWNGRADE = const SolveType._("downgrade"); - - final String _name; - - const SolveType._(this._name); - - String toString() => _name; -} - -/// Base class for all failures that can occur while trying to resolve versions. -abstract class SolveFailure implements ApplicationException { - /// The name of the package whose version could not be solved. - /// - /// Will be `null` if the failure is not specific to one package. - final String package; - - /// The known dependencies on [package] at the time of the failure. - /// - /// Will be an empty collection if the failure is not specific to one package. - final Iterable dependencies; - - String get message => toString(); - - /// A message describing the specific kind of solve failure. - String get _message { - throw new UnimplementedError("Must override _message or toString()."); - } - - SolveFailure(this.package, Iterable dependencies) - : dependencies = dependencies != null ? dependencies : []; - - String toString() { - if (dependencies.isEmpty) return _message; - - var buffer = new StringBuffer(); - buffer.write("$_message:"); - - var sorted = dependencies.toList(); - sorted.sort((a, b) => a.depender.compareTo(b.depender)); - - for (var dep in sorted) { - buffer.writeln(); - buffer.write("- ${log.bold(dep.depender)}"); - if (!dep.isMagic) buffer.write(" ${dep.dependerVersion}"); - buffer.write(" ${_describeDependency(dep.dep)}"); - } - - return buffer.toString(); - } - - /// Describes a dependency's reference in the output message. - /// - /// Override this to highlight which aspect of [dep] led to the failure. - String _describeDependency(PackageDep dep) => - "depends on version ${dep.constraint}"; -} - -/// Exception thrown when the current SDK's version does not match a package's -/// constraint on it. -class BadSdkVersionException extends SolveFailure { - final String _message; - - BadSdkVersionException(String package, String message) - : super(package, null), - _message = message; -} - -/// Exception thrown when the [VersionConstraint] used to match a package is -/// valid (i.e. non-empty), but there are no available versions of the package -/// that fit that constraint. -class NoVersionException extends SolveFailure { - final VersionConstraint constraint; - - /// The last selected version of the package that failed to meet the new - /// constraint. - /// - /// This will be `null` when the failure occurred because there are no - /// versions of the package *at all* that match the constraint. It will be - /// non-`null` when a version was selected, but then the solver tightened a - /// constraint such that that version was no longer allowed. - final Version version; - - NoVersionException(String package, this.version, this.constraint, - Iterable dependencies) - : super(package, dependencies); - - String get _message { - if (version == null) { - return "Package $package has no versions that match $constraint derived " - "from"; - } - - return "Package $package $version does not match $constraint derived from"; - } -} - -// TODO(rnystrom): Report the list of depending packages and their constraints. -/// Exception thrown when the most recent version of [package] must be selected, -/// but doesn't match the [VersionConstraint] imposed on the package. -class CouldNotUpgradeException extends SolveFailure { - final VersionConstraint constraint; - final Version best; - - CouldNotUpgradeException(String package, this.constraint, this.best) - : super(package, null); - - String get _message => - "The latest version of $package, $best, does not match $constraint."; -} - -/// Exception thrown when the [VersionConstraint] used to match a package is -/// the empty set: in other words, multiple packages depend on it and have -/// conflicting constraints that have no overlap. -class DisjointConstraintException extends SolveFailure { - DisjointConstraintException(String package, Iterable dependencies) - : super(package, dependencies); - - String get _message => "Incompatible version constraints on $package"; -} - -/// Exception thrown when two packages with the same name but different sources -/// are depended upon. -class SourceMismatchException extends SolveFailure { - String get _message => "Incompatible dependencies on $package"; - - SourceMismatchException(String package, Iterable dependencies) - : super(package, dependencies); - - String _describeDependency(PackageDep dep) => - "depends on it from source ${dep.source}"; -} - -/// Exception thrown when a dependency on an unknown source name is found. -class UnknownSourceException extends SolveFailure { - UnknownSourceException(String package, Iterable dependencies) - : super(package, dependencies); - - String toString() { - var dep = dependencies.single; - return 'Package ${dep.depender} depends on ${dep.dep.name} from unknown ' - 'source "${dep.dep.source}".'; - } -} - -/// Exception thrown when two packages with the same name and source but -/// different descriptions are depended upon. -class DescriptionMismatchException extends SolveFailure { - String get _message => "Incompatible dependencies on $package"; - - DescriptionMismatchException(String package, - Iterable dependencies) - : super(package, dependencies); - - String _describeDependency(PackageDep dep) { - // TODO(nweiz): Dump descriptions to YAML when that's supported. - return "depends on it with description ${JSON.encode(dep.description)}"; - } -} - -/// Exception thrown when a dependency could not be found in its source. -/// -/// Unlike [PackageNotFoundException], this includes information about the -/// dependent packages requesting the missing one. -class DependencyNotFoundException extends SolveFailure { - final PackageNotFoundException _innerException; - String get _message => "${_innerException.message}\nDepended on by"; - - DependencyNotFoundException(String package, this._innerException, - Iterable dependencies) - : super(package, dependencies); - - /// The failure isn't because of the version of description of the package, - /// it's the package itself that can't be found, so just show the name and no - /// descriptive details. - String _describeDependency(PackageDep dep) => ""; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/source.dart b/sdk/lib/_internal/pub_generated/lib/src/source.dart deleted file mode 100644 index d7b00f1adbc..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/source.dart +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.source; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; - -import 'package.dart'; -import 'pubspec.dart'; -import 'system_cache.dart'; - -/// A source from which to get packages. -/// -/// Each source has many packages that it looks up using [PackageId]s. Sources -/// that inherit this directly (currently just [PathSource]) are *uncached* -/// sources. They deliver a package directly to the package that depends on it. -/// -/// Other sources are *cached* sources. These extend [CachedSource]. When a -/// package needs a dependency from a cached source, it is first installed in -/// the [SystemCache] and then acquired from there. -abstract class Source { - /// The name of the source. - /// - /// Should be lower-case, suitable for use in a filename, and unique accross - /// all sources. - String get name; - - /// Whether this source can choose between multiple versions of the same - /// package during version solving. - /// - /// Defaults to `false`. - final bool hasMultipleVersions = false; - - /// Whether or not this source is the default source. - bool get isDefault => systemCache.sources.defaultSource == this; - - /// The system cache with which this source is registered. - SystemCache get systemCache { - assert(_systemCache != null); - return _systemCache; - } - - /// The system cache variable. - /// - /// Set by [_bind]. - SystemCache _systemCache; - - /// Records the system cache to which this source belongs. - /// - /// This should only be called once for each source, by - /// [SystemCache.register]. It should not be overridden by base classes. - void bind(SystemCache systemCache) { - assert(_systemCache == null); - this._systemCache = systemCache; - } - - /// Get the list of all versions that exist for the package described by - /// [description]. - /// - /// [name] is the expected name of the package. - /// - /// Note that this does *not* require the packages to be downloaded locally, - /// which is the point. This is used during version resolution to determine - /// which package versions are available to be downloaded (or already - /// downloaded). - /// - /// By default, this assumes that each description has a single version and - /// uses [describe] to get that version. - Future> getVersions(String name, description) { - var id = new PackageId(name, this.name, Version.none, description); - return describe(id).then((pubspec) => [pubspec.version]); - } - - /// Loads the (possibly remote) pubspec for the package version identified by - /// [id]. - /// - /// This may be called for packages that have not yet been downloaded during - /// the version resolution process. - /// - /// Sources should not override this. Instead, they implement [doDescribe]. - Future describe(PackageId id) { - if (id.isRoot) throw new ArgumentError("Cannot describe the root package."); - if (id.source != name) { - throw new ArgumentError("Package $id does not use source $name."); - } - - // Delegate to the overridden one. - return doDescribe(id); - } - - /// Loads the (possibly remote) pubspec for the package version identified by - /// [id]. - /// - /// This may be called for packages that have not yet been downloaded during - /// the version resolution process. - /// - /// This method is effectively protected: subclasses must implement it, but - /// external code should not call this. Instead, call [describe]. - Future doDescribe(PackageId id); - - /// Ensures [id] is available locally and creates a symlink at [symlink] - /// pointing it. - Future get(PackageId id, String symlink); - - /// Returns the directory where this package can (or could) be found locally. - /// - /// If the source is cached, this will be a path in the system cache. In that - /// case, this will return a directory even if the package has not been - /// installed into the cache yet. - Future getDirectory(PackageId id); - - /// Gives the source a chance to interpret and validate the description for - /// a package coming from this source. - /// - /// When a [Pubspec] or [LockFile] is parsed, it reads in the description for - /// each dependency. It is up to the dependency's [Source] to determine how - /// that should be interpreted. This will be called during parsing to validate - /// that the given [description] is well-formed according to this source, and - /// to give the source a chance to canonicalize the description. - /// - /// [containingPath] is the path to the local file (pubspec or lockfile) - /// where this description appears. It may be `null` if the description is - /// coming from some in-memory source (such as pulling down a pubspec from - /// pub.dartlang.org). - /// - /// It should return if a (possibly modified) valid description, or throw a - /// [FormatException] if not valid. - /// - /// [fromLockFile] is true when the description comes from a [LockFile], to - /// allow the source to use lockfile-specific descriptions via [resolveId]. - dynamic parseDescription(String containingPath, description, - {bool fromLockFile: false}); - - /// When a [LockFile] is serialized, it uses this method to get the - /// [description] in the right format. - /// - /// [containingPath] is the containing directory of the root package. - dynamic serializeDescription(String containingPath, description) { - return description; - } - - /// When a package [description] is shown to the user, this is called to - /// convert it into a human-friendly form. - /// - /// By default, it just converts the description to a string, but sources - /// may customize this. [containingPath] is the containing directory of the - /// root package. - String formatDescription(String containingPath, description) { - return description.toString(); - } - - /// Returns whether or not [description1] describes the same package as - /// [description2] for this source. - /// - /// This method should be light-weight. It doesn't need to validate that - /// either package exists. - bool descriptionsEqual(description1, description2); - - /// Resolves [id] to a more possibly more precise that will uniquely identify - /// a package regardless of when the package is requested. - /// - /// For some sources, [PackageId]s can point to different chunks of code at - /// different times. This takes such an [id] and returns a future that - /// completes to a [PackageId] that will uniquely specify a single chunk of - /// code forever. - /// - /// For example, [GitSource] might take an [id] with description - /// `http://github.com/dart-lang/some-lib.git` and return an id with a - /// description that includes the current commit of the Git repository. - /// - /// Pub calls this after getting a package, so the source can use the local - /// package to determine information about the resolved id. - /// - /// The returned [PackageId] may have a description field that's invalid - /// according to [parseDescription], although it must still be serializable - /// to JSON and YAML. It must also be equal to [id] according to - /// [descriptionsEqual]. - /// - /// By default, this just returns [id]. - Future resolveId(PackageId id) => new Future.value(id); - - /// Returns the source's name. - String toString() => name; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/cached.dart b/sdk/lib/_internal/pub_generated/lib/src/source/cached.dart deleted file mode 100644 index 95214712a45..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/source/cached.dart +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.source.cached; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../io.dart'; -import '../package.dart'; -import '../pubspec.dart'; -import '../source.dart'; -import '../utils.dart'; - -/// Base class for a [Source] that installs packages into pub's [SystemCache]. -/// -/// A source should be cached if it requires network access to retrieve -/// packages or the package needs to be "frozen" at the point in time that it's -/// installed. (For example, Git packages are cached because installing from -/// the same repo over time may yield different commits.) -abstract class CachedSource extends Source { - /// The root directory of this source's cache within the system cache. - /// - /// This shouldn't be overridden by subclasses. - String get systemCacheRoot => path.join(systemCache.rootDir, name); - - /// If [id] is already in the system cache, just loads it from there. - /// - /// Otherwise, defers to the subclass. - Future doDescribe(PackageId id) { - return getDirectory(id).then((packageDir) { - if (fileExists(path.join(packageDir, "pubspec.yaml"))) { - return new Pubspec.load( - packageDir, - systemCache.sources, - expectedName: id.name); - } - - return describeUncached(id); - }); - } - - /// Loads the (possibly remote) pubspec for the package version identified by - /// [id]. - /// - /// This will only be called for packages that have not yet been installed in - /// the system cache. - Future describeUncached(PackageId id); - - Future get(PackageId id, String symlink) { - return downloadToSystemCache(id).then((pkg) { - createPackageSymlink(id.name, pkg.dir, symlink); - }); - } - - /// Determines if the package with [id] is already downloaded to the system - /// cache. - Future isInSystemCache(PackageId id) => - getDirectory(id).then(dirExists); - - /// Downloads the package identified by [id] to the system cache. - Future downloadToSystemCache(PackageId id); - - /// Returns the [Package]s that have been downloaded to the system cache. - List getCachedPackages(); - - /// Reinstalls all packages that have been previously installed into the - /// system cache by this source. - /// - /// Returns a [Pair] whose first element is the number of packages - /// successfully repaired and the second is the number of failures. - Future> repairCachedPackages(); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/git.dart b/sdk/lib/_internal/pub_generated/lib/src/source/git.dart deleted file mode 100644 index 7edaac24f42..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/source/git.dart +++ /dev/null @@ -1,400 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.source.git; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../git.dart' as git; -import '../io.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../pubspec.dart'; -import '../utils.dart'; -import 'cached.dart'; - -/// A package source that gets packages from Git repos. -class GitSource extends CachedSource { - /// Given a valid git package description, returns the URL of the repository - /// it pulls from. - static String urlFromDescription(description) => description["url"]; - - final name = "git"; - - /// The paths to the canonical clones of repositories for which "git fetch" - /// has already been run during this run of pub. - final _updatedRepos = new Set(); - - /// Given a Git repo that contains a pub package, gets the name of the pub - /// package. - Future getPackageNameFromRepo(String repo) { - // Clone the repo to a temp directory. - return withTempDir((tempDir) { - return _clone(repo, tempDir, shallow: true).then((_) { - var pubspec = new Pubspec.load(tempDir, systemCache.sources); - return pubspec.name; - }); - }); - } - - /// Since we don't have an easy way to read from a remote Git repo, this - /// just installs [id] into the system cache, then describes it from there. - Future describeUncached(PackageId id) { - return downloadToSystemCache(id).then((package) => package.pubspec); - } - - /// Clones a Git repo to the local filesystem. - /// - /// The Git cache directory is a little idiosyncratic. At the top level, it - /// contains a directory for each commit of each repository, named `-`. These are the canonical package directories that are - /// linked to from the `packages/` directory. - /// - /// In addition, the Git system cache contains a subdirectory named `cache/` - /// which contains a directory for each separate repository URL, named - /// `-`. These are used to check out the repository - /// itself; each of the commit-specific directories are clones of a directory - /// in `cache/`. - Future downloadToSystemCache(PackageId id) { - var revisionCachePath; - - if (!git.isInstalled) { - fail( - "Cannot get ${id.name} from Git (${_getUrl(id)}).\n" - "Please ensure Git is correctly installed."); - } - - ensureDir(path.join(systemCacheRoot, 'cache')); - return _ensureRevision(id).then((_) => getDirectory(id)).then((path) { - revisionCachePath = path; - if (entryExists(revisionCachePath)) return null; - return _clone(_repoCachePath(id), revisionCachePath, mirror: false); - }).then((_) { - var ref = _getEffectiveRef(id); - if (ref == 'HEAD') return null; - return _checkOut(revisionCachePath, ref); - }).then((_) { - return new Package.load(id.name, revisionCachePath, systemCache.sources); - }); - } - - /// Returns the path to the revision-specific cache of [id]. - Future getDirectory(PackageId id) { - return _ensureRevision(id).then((rev) { - var revisionCacheName = '${id.name}-$rev'; - return path.join(systemCacheRoot, revisionCacheName); - }); - } - - /// Ensures [description] is a Git URL. - dynamic parseDescription(String containingPath, description, - {bool fromLockFile: false}) { - // TODO(rnystrom): Handle git URLs that are relative file paths (#8570). - // TODO(rnystrom): Now that this function can modify the description, it - // may as well canonicalize it to a map so that other code in the source - // can assume that. - // A single string is assumed to be a Git URL. - if (description is String) return description; - if (description is! Map || !description.containsKey('url')) { - throw new FormatException( - "The description must be a Git URL or a map " "with a 'url' key."); - } - - var parsed = new Map.from(description); - parsed.remove('url'); - parsed.remove('ref'); - if (fromLockFile) parsed.remove('resolved-ref'); - - if (!parsed.isEmpty) { - var plural = parsed.length > 1; - var keys = parsed.keys.join(', '); - throw new FormatException("Invalid key${plural ? 's' : ''}: $keys."); - } - - return description; - } - - /// If [description] has a resolved ref, print it out in short-form. - /// - /// This helps distinguish different git commits with the same pubspec - /// version. - String formatDescription(String containingPath, description) { - if (description is Map && description.containsKey('resolved-ref')) { - return "${description['url']} at " - "${description['resolved-ref'].substring(0, 6)}"; - } else { - return super.formatDescription(containingPath, description); - } - } - - /// Two Git descriptions are equal if both their URLs and their refs are - /// equal. - bool descriptionsEqual(description1, description2) { - // TODO(nweiz): Do we really want to throw an error if you have two - // dependencies on some repo, one of which specifies a ref and one of which - // doesn't? If not, how do we handle that case in the version solver? - if (_getUrl(description1) != _getUrl(description2)) return false; - if (_getRef(description1) != _getRef(description2)) return false; - - if (description1 is Map && - description1.containsKey('resolved-ref') && - description2 is Map && - description2.containsKey('resolved-ref')) { - return description1['resolved-ref'] == description2['resolved-ref']; - } - - return true; - } - - /// Attaches a specific commit to [id] to disambiguate it. - Future resolveId(PackageId id) { - return _ensureRevision(id).then((revision) { - var description = { - 'url': _getUrl(id), - 'ref': _getRef(id) - }; - description['resolved-ref'] = revision; - return new PackageId(id.name, name, id.version, description); - }); - } - - List getCachedPackages() { - // TODO(keertip): Implement getCachedPackages(). - throw new UnimplementedError( - "The git source doesn't support listing its cached packages yet."); - } - - /// Resets all cached packages back to the pristine state of the Git - /// repository at the revision they are pinned to. - Future> repairCachedPackages() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - var successes = 0; - var failures = 0; - var packages = listDir(systemCacheRoot).where(((entry) { - return dirExists(path.join(entry, ".git")); - })).map(((packageDir) { - return new Package.load(null, packageDir, systemCache.sources); - })).toList(); - packages.sort(Package.orderByNameAndVersion); - var it0 = packages.iterator; - break0() { - completer0.complete(new Pair(successes, failures)); - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var package = it0.current; - log.message( - "Resetting Git repository for " - "${log.bold(package.name)} ${package.version}..."); - join1() { - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - catch0(error, stackTrace) { - try { - if (error is git.GitException) { - log.error( - "Failed to reset ${log.bold(package.name)} " - "${package.version}. Error:\n${error}"); - log.fine(stackTrace); - failures++; - tryDeleteEntry(package.dir); - join1(); - } else { - throw error; - } - } catch (error, stackTrace) { - completer0.completeError(error, stackTrace); - } - } - try { - new Future.value( - git.run(["clean", "-d", "--force", "-x"], workingDir: package.dir)).then((x0) { - trampoline0 = () { - trampoline0 = null; - try { - x0; - new Future.value( - git.run(["reset", "--hard", "HEAD"], workingDir: package.dir)).then((x1) { - trampoline0 = () { - trampoline0 = null; - try { - x1; - successes++; - join1(); - } catch (e0, s0) { - catch0(e0, s0); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: catch0); - } catch (e1, s1) { - catch0(e1, s1); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: catch0); - } catch (e2, s2) { - catch0(e2, s2); - } - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - if (!dirExists(systemCacheRoot)) { - completer0.complete(new Pair(0, 0)); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Ensure that the canonical clone of the repository referred to by [id] (the - /// one in `/git/cache`) exists and contains the revision - /// referred to by [id]. - /// - /// Returns a future that completes to the hash of the revision identified by - /// [id]. - Future _ensureRevision(PackageId id) { - return new Future.sync(() { - var path = _repoCachePath(id); - if (!entryExists(path)) { - return _clone(_getUrl(id), path, mirror: true).then((_) => _getRev(id)); - } - - // If [id] didn't come from a lockfile, it may be using a symbolic - // reference. We want to get the latest version of that reference. - var description = id.description; - if (description is! Map || !description.containsKey('resolved-ref')) { - return _updateRepoCache(id).then((_) => _getRev(id)); - } - - // If [id] did come from a lockfile, then we want to avoid running "git - // fetch" if possible to avoid networking time and errors. See if the - // revision exists in the repo cache before updating it. - return _getRev(id).catchError((error) { - if (error is! git.GitException) throw error; - return _updateRepoCache(id).then((_) => _getRev(id)); - }); - }); - } - - /// Runs "git fetch" in the canonical clone of the repository referred to by - /// [id]. - /// - /// This assumes that the canonical clone already exists. - Future _updateRepoCache(PackageId id) { - var path = _repoCachePath(id); - if (_updatedRepos.contains(path)) return new Future.value(); - return git.run(["fetch"], workingDir: path).then((_) { - _updatedRepos.add(path); - }); - } - - /// Runs "git rev-list" in the canonical clone of the repository referred to - /// by [id] on the effective ref of [id]. - /// - /// This assumes that the canonical clone already exists. - Future _getRev(PackageId id) { - return git.run( - ["rev-list", "--max-count=1", _getEffectiveRef(id)], - workingDir: _repoCachePath(id)).then((result) => result.first); - } - - /// Clones the repo at the URI [from] to the path [to] on the local - /// filesystem. - /// - /// If [mirror] is true, creates a bare, mirrored clone. This doesn't check - /// out the working tree, but instead makes the repository a local mirror of - /// the remote repository. See the manpage for `git clone` for more - /// information. - /// - /// If [shallow] is true, creates a shallow clone that contains no history - /// for the repository. - Future _clone(String from, String to, {bool mirror: false, bool shallow: - false}) { - return new Future.sync(() { - // Git on Windows does not seem to automatically create the destination - // directory. - ensureDir(to); - var args = ["clone", from, to]; - - if (mirror) args.insert(1, "--mirror"); - if (shallow) args.insertAll(1, ["--depth", "1"]); - - return git.run(args); - }).then((result) => null); - } - - /// Checks out the reference [ref] in [repoPath]. - Future _checkOut(String repoPath, String ref) { - return git.run( - ["checkout", ref], - workingDir: repoPath).then((result) => null); - } - - /// Returns the path to the canonical clone of the repository referred to by - /// [id] (the one in `/git/cache`). - String _repoCachePath(PackageId id) { - var repoCacheName = '${id.name}-${sha1(_getUrl(id))}'; - return path.join(systemCacheRoot, 'cache', repoCacheName); - } - - /// Returns the repository URL for [id]. - /// - /// [description] may be a description or a [PackageId]. - String _getUrl(description) { - description = _getDescription(description); - if (description is String) return description; - return description['url']; - } - - /// Returns the commit ref that should be checked out for [description]. - /// - /// This differs from [_getRef] in that it doesn't just return the ref in - /// [description]. It will return a sensible default if that ref doesn't - /// exist, and it will respect the "resolved-ref" parameter set by - /// [resolveId]. - /// - /// [description] may be a description or a [PackageId]. - String _getEffectiveRef(description) { - description = _getDescription(description); - if (description is Map && description.containsKey('resolved-ref')) { - return description['resolved-ref']; - } - - var ref = _getRef(description); - return ref == null ? 'HEAD' : ref; - } - - /// Returns the commit ref for [description], or null if none is given. - /// - /// [description] may be a description or a [PackageId]. - String _getRef(description) { - description = _getDescription(description); - if (description is String) return null; - return description['ref']; - } - - /// Returns [description] if it's a description, or [PackageId.description] if - /// it's a [PackageId]. - _getDescription(description) { - if (description is PackageId) return description.description; - return description; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/hosted.dart b/sdk/lib/_internal/pub_generated/lib/src/source/hosted.dart deleted file mode 100644 index 37f27990ee5..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/source/hosted.dart +++ /dev/null @@ -1,450 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.source.hosted; - -import 'dart:async'; -import 'dart:io' as io; -import "dart:convert"; - -import 'package:http/http.dart' as http; -import 'package:path/path.dart' as path; -import 'package:pub_semver/pub_semver.dart'; - -import '../exceptions.dart'; -import '../http.dart'; -import '../io.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../pubspec.dart'; -import '../utils.dart'; -import 'cached.dart'; - -/// A package source that gets packages from a package hosting site that uses -/// the same API as pub.dartlang.org. -class HostedSource extends CachedSource { - final name = "hosted"; - final hasMultipleVersions = true; - - /// Gets the default URL for the package server for hosted dependencies. - static String get defaultUrl { - var url = io.Platform.environment["PUB_HOSTED_URL"]; - if (url != null) return url; - - return "https://pub.dartlang.org"; - } - - /// Downloads a list of all versions of a package that are available from the - /// site. - Future> getVersions(String name, description) { - var url = - _makeUrl(description, (server, package) => "$server/api/packages/$package"); - - log.io("Get versions from $url."); - return httpClient.read(url, headers: PUB_API_HEADERS).then((body) { - var doc = JSON.decode(body); - return doc['versions'].map( - (version) => new Version.parse(version['version'])).toList(); - }).catchError((ex, stackTrace) { - var parsed = _parseDescription(description); - _throwFriendlyError(ex, stackTrace, parsed.first, parsed.last); - }); - } - - /// Downloads and parses the pubspec for a specific version of a package that - /// is available from the site. - Future describeUncached(PackageId id) { - // Request it from the server. - var url = _makeVersionUrl( - id, - (server, package, version) => - "$server/api/packages/$package/versions/$version"); - - log.io("Describe package at $url."); - return httpClient.read(url, headers: PUB_API_HEADERS).then((version) { - version = JSON.decode(version); - - // TODO(rnystrom): After this is pulled down, we could place it in - // a secondary cache of just pubspecs. This would let us have a - // persistent cache for pubspecs for packages that haven't actually - // been downloaded. - return new Pubspec.fromMap( - version['pubspec'], - systemCache.sources, - expectedName: id.name, - location: url); - }).catchError((ex, stackTrace) { - var parsed = _parseDescription(id.description); - _throwFriendlyError(ex, stackTrace, id.name, parsed.last); - }); - } - - /// Downloads the package identified by [id] to the system cache. - Future downloadToSystemCache(PackageId id) { - return isInSystemCache(id).then((inCache) { - // Already cached so don't download it. - if (inCache) return true; - - var packageDir = _getDirectory(id); - ensureDir(path.dirname(packageDir)); - var parsed = _parseDescription(id.description); - return _download(parsed.last, parsed.first, id.version, packageDir); - }).then((found) { - if (!found) fail('Package $id not found.'); - return new Package.load(id.name, _getDirectory(id), systemCache.sources); - }); - } - - /// The system cache directory for the hosted source contains subdirectories - /// for each separate repository URL that's used on the system. - /// - /// Each of these subdirectories then contains a subdirectory for each - /// package downloaded from that site. - Future getDirectory(PackageId id) => - new Future.value(_getDirectory(id)); - - String _getDirectory(PackageId id) { - var parsed = _parseDescription(id.description); - var dir = _urlToDirectory(parsed.last); - return path.join(systemCacheRoot, dir, "${parsed.first}-${id.version}"); - } - - String packageName(description) => _parseDescription(description).first; - - bool descriptionsEqual(description1, description2) => - _parseDescription(description1) == _parseDescription(description2); - - /// Ensures that [description] is a valid hosted package description. - /// - /// There are two valid formats. A plain string refers to a package with the - /// given name from the default host, while a map with keys "name" and "url" - /// refers to a package with the given name from the host at the given URL. - dynamic parseDescription(String containingPath, description, - {bool fromLockFile: false}) { - _parseDescription(description); - return description; - } - - /// Re-downloads all packages that have been previously downloaded into the - /// system cache from any server. - Future> repairCachedPackages() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - join0() { - var successes = 0; - var failures = 0; - var it0 = listDir(systemCacheRoot).iterator; - break0() { - completer0.complete(new Pair(successes, failures)); - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var serverDir = it0.current; - var url = _directoryToUrl(path.basename(serverDir)); - var packages = - _getCachedPackagesInDirectory(path.basename(serverDir)); - packages.sort(Package.orderByNameAndVersion); - var it1 = packages.iterator; - break1() { - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - var trampoline1; - continue1() { - trampoline1 = null; - if (it1.moveNext()) { - var package = it1.current; - join1() { - trampoline1 = continue1; - do trampoline1(); while (trampoline1 != null); - } - catch0(error, stackTrace) { - try { - failures++; - var message = - "Failed to repair ${log.bold(package.name)} " "${package.version}"; - join2() { - log.error("${message}. Error:\n${error}"); - log.fine(stackTrace); - tryDeleteEntry(package.dir); - join1(); - } - if (url != defaultUrl) { - message += " from ${url}"; - join2(); - } else { - join2(); - } - } catch (error, stackTrace) { - completer0.completeError(error, stackTrace); - } - } - try { - new Future.value( - _download(url, package.name, package.version, package.dir)).then((x0) { - trampoline1 = () { - trampoline1 = null; - try { - x0; - successes++; - join1(); - } catch (e0, s0) { - catch0(e0, s0); - } - }; - do trampoline1(); while (trampoline1 != null); - }, onError: catch0); - } catch (e1, s1) { - catch0(e1, s1); - } - } else { - break1(); - } - } - trampoline1 = continue1; - do trampoline1(); while (trampoline1 != null); - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - if (!dirExists(systemCacheRoot)) { - completer0.complete(new Pair(0, 0)); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Gets all of the packages that have been downloaded into the system cache - /// from the default server. - List getCachedPackages() { - return _getCachedPackagesInDirectory(_urlToDirectory(defaultUrl)); - } - - /// Gets all of the packages that have been downloaded into the system cache - /// into [dir]. - List _getCachedPackagesInDirectory(String dir) { - var cacheDir = path.join(systemCacheRoot, dir); - if (!dirExists(cacheDir)) return []; - - return listDir( - cacheDir).map( - (entry) => new Package.load(null, entry, systemCache.sources)).toList(); - } - - /// Downloads package [package] at [version] from [server], and unpacks it - /// into [destPath]. - Future _download(String server, String package, Version version, - String destPath) { - return new Future.sync(() { - var url = Uri.parse("$server/packages/$package/versions/$version.tar.gz"); - log.io("Get package from $url."); - log.message('Downloading ${log.bold(package)} ${version}...'); - - // Download and extract the archive to a temp directory. - var tempDir = systemCache.createTempDir(); - return httpClient.send( - new http.Request( - "GET", - url)).then((response) => response.stream).then((stream) { - return timeout( - extractTarGz(stream, tempDir), - HTTP_TIMEOUT, - url, - 'downloading $url'); - }).then((_) { - // Remove the existing directory if it exists. This will happen if - // we're forcing a download to repair the cache. - if (dirExists(destPath)) deleteEntry(destPath); - - // Now that the get has succeeded, move it to the real location in the - // cache. This ensures that we don't leave half-busted ghost - // directories in the user's pub cache if a get fails. - renameDir(tempDir, destPath); - return true; - }); - }); - } - - /// When an error occurs trying to read something about [package] from [url], - /// this tries to translate into a more user friendly error message. - /// - /// Always throws an error, either the original one or a better one. - void _throwFriendlyError(error, StackTrace stackTrace, String package, - String url) { - if (error is PubHttpException && error.response.statusCode == 404) { - throw new PackageNotFoundException( - "Could not find package $package at $url.", - error, - stackTrace); - } - - if (error is TimeoutException) { - fail( - "Timed out trying to find package $package at $url.", - error, - stackTrace); - } - - if (error is io.SocketException) { - fail( - "Got socket error trying to find package $package at $url.", - error, - stackTrace); - } - - // Otherwise re-throw the original exception. - throw error; - } -} - -/// This is the modified hosted source used when pub get or upgrade are run -/// with "--offline". -/// -/// This uses the system cache to get the list of available packages and does -/// no network access. -class OfflineHostedSource extends HostedSource { - /// Gets the list of all versions of [name] that are in the system cache. - Future> getVersions(String name, description) { - return newFuture(() { - var parsed = _parseDescription(description); - var server = parsed.last; - log.io( - "Finding versions of $name in " "$systemCacheRoot/${_urlToDirectory(server)}"); - return _getCachedPackagesInDirectory( - _urlToDirectory( - server)).where( - (package) => package.name == name).map((package) => package.version).toList(); - }).then((versions) { - // If there are no versions in the cache, report a clearer error. - if (versions.isEmpty) fail("Could not find package $name in cache."); - - return versions; - }); - } - - Future _download(String server, String package, Version version, - String destPath) { - // Since HostedSource is cached, this will only be called for uncached - // packages. - throw new UnsupportedError("Cannot download packages when offline."); - } - - Future doDescribeUncached(PackageId id) { - // [getVersions()] will only return packages that are already cached. - // [CachedSource] will only call [doDescribeUncached()] on a package after - // it has failed to find it in the cache, so this code should not be - // reached. - throw new UnsupportedError("Cannot describe packages when offline."); - } -} - -/// Given a URL, returns a "normalized" string to be used as a directory name -/// for packages downloaded from the server at that URL. -/// -/// This normalization strips off the scheme (which is presumed to be HTTP or -/// HTTPS) and *sort of* URL-encodes it. I say "sort of" because it does it -/// incorrectly: it uses the character's *decimal* ASCII value instead of hex. -/// -/// This could cause an ambiguity since some characters get encoded as three -/// digits and others two. It's possible for one to be a prefix of the other. -/// In practice, the set of characters that are encoded don't happen to have -/// any collisions, so the encoding is reversible. -/// -/// This behavior is a bug, but is being preserved for compatibility. -String _urlToDirectory(String url) { - // Normalize all loopback URLs to "localhost". - url = url.replaceAllMapped( - new RegExp(r"^https?://(127\.0\.0\.1|\[::1\])?"), - (match) => match[1] == null ? '' : 'localhost'); - return replace( - url, - new RegExp(r'[<>:"\\/|?*%]'), - (match) => '%${match[0].codeUnitAt(0)}'); -} - -/// Given a directory name in the system cache, returns the URL of the server -/// whose packages it contains. -/// -/// See [_urlToDirectory] for details on the mapping. Note that because the -/// directory name does not preserve the scheme, this has to guess at it. It -/// chooses "http" for loopback URLs (mainly to support the pub tests) and -/// "https" for all others. -String _directoryToUrl(String url) { - // Decode the pseudo-URL-encoded characters. - var chars = '<>:"\\/|?*%'; - for (var i = 0; i < chars.length; i++) { - var c = chars.substring(i, i + 1); - url = url.replaceAll("%${c.codeUnitAt(0)}", c); - } - - // Figure out the scheme. - var scheme = "https"; - - // See if it's a loopback IP address. - if (isLoopback(url.replaceAll(new RegExp(":.*"), ""))) scheme = "http"; - return "$scheme://$url"; -} - -/// Parses [description] into its server and package name components, then -/// converts that to a Uri given [pattern]. -/// -/// Ensures the package name is properly URL encoded. -Uri _makeUrl(description, String pattern(String server, String package)) { - var parsed = _parseDescription(description); - var server = parsed.last; - var package = Uri.encodeComponent(parsed.first); - return Uri.parse(pattern(server, package)); -} - -/// Parses [id] into its server, package name, and version components, then -/// converts that to a Uri given [pattern]. -/// -/// Ensures the package name is properly URL encoded. -Uri _makeVersionUrl(PackageId id, String pattern(String server, String package, - String version)) { - var parsed = _parseDescription(id.description); - var server = parsed.last; - var package = Uri.encodeComponent(parsed.first); - var version = Uri.encodeComponent(id.version.toString()); - return Uri.parse(pattern(server, package, version)); -} - -/// Parses the description for a package. -/// -/// If the package parses correctly, this returns a (name, url) pair. If not, -/// this throws a descriptive FormatException. -Pair _parseDescription(description) { - if (description is String) { - return new Pair(description, HostedSource.defaultUrl); - } - - if (description is! Map) { - throw new FormatException("The description must be a package name or map."); - } - - if (!description.containsKey("name")) { - throw new FormatException("The description map must contain a 'name' key."); - } - - var name = description["name"]; - if (name is! String) { - throw new FormatException("The 'name' key must have a string value."); - } - - var url = description["url"]; - if (url == null) url = HostedSource.defaultUrl; - - return new Pair(name, url); -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/path.dart b/sdk/lib/_internal/pub_generated/lib/src/source/path.dart deleted file mode 100644 index d6f7b8c0c70..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/source/path.dart +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.source.path; - -import 'dart:async'; - -import 'package:path/path.dart' as p; - -import '../exceptions.dart'; -import '../io.dart'; -import '../package.dart'; -import '../pubspec.dart'; -import '../source.dart'; -import '../utils.dart'; - -/// A package [Source] that gets packages from a given local file path. -class PathSource extends Source { - /// Returns a valid description for a reference to a package at [path]. - static describePath(String path) { - return { - "path": path, - "relative": p.isRelative(path) - }; - } - - /// Given a valid path reference description, returns the file path it - /// describes. - /// - /// This returned path may be relative or absolute and it is up to the caller - /// to know how to interpret a relative path. - static String pathFromDescription(description) => description["path"]; - - final name = 'path'; - - Future doDescribe(PackageId id) { - return new Future.sync(() { - var dir = _validatePath(id.name, id.description); - return new Pubspec.load(dir, systemCache.sources, expectedName: id.name); - }); - } - - bool descriptionsEqual(description1, description2) { - // Compare real paths after normalizing and resolving symlinks. - var path1 = canonicalize(description1["path"]); - var path2 = canonicalize(description2["path"]); - return path1 == path2; - } - - Future get(PackageId id, String symlink) { - return new Future.sync(() { - var dir = _validatePath(id.name, id.description); - createPackageSymlink( - id.name, - dir, - symlink, - relative: id.description["relative"]); - }); - } - - Future getDirectory(PackageId id) => - newFuture(() => _validatePath(id.name, id.description)); - - /// Parses a path dependency. - /// - /// This takes in a path string and returns a map. The "path" key will be the - /// original path but resolved relative to the containing path. The - /// "relative" key will be `true` if the original path was relative. - /// - /// A path coming from a pubspec is a simple string. From a lock file, it's - /// an expanded {"path": ..., "relative": ...} map. - dynamic parseDescription(String containingPath, description, - {bool fromLockFile: false}) { - if (fromLockFile) { - if (description is! Map) { - throw new FormatException("The description must be a map."); - } - - if (description["path"] is! String) { - throw new FormatException( - "The 'path' field of the description must " "be a string."); - } - - if (description["relative"] is! bool) { - throw new FormatException( - "The 'relative' field of the description " "must be a boolean."); - } - - return description; - } - - if (description is! String) { - throw new FormatException("The description must be a path string."); - } - - // Resolve the path relative to the containing file path, and remember - // whether the original path was relative or absolute. - var isRelative = p.isRelative(description); - if (isRelative) { - // Relative paths coming from pubspecs that are not on the local file - // system aren't allowed. This can happen if a hosted or git dependency - // has a path dependency. - if (containingPath == null) { - throw new FormatException( - '"$description" is a relative path, but this ' 'isn\'t a local pubspec.'); - } - - description = p.normalize(p.join(p.dirname(containingPath), description)); - } - - return { - "path": description, - "relative": isRelative - }; - } - - /// Serializes path dependency's [description]. - /// - /// For the descriptions where `relative` attribute is `true`, tries to make - /// `path` relative to the specified [containingPath]. - dynamic serializeDescription(String containingPath, description) { - if (description["relative"]) { - return { - "path": p.relative(description['path'], from: containingPath), - "relative": true - }; - } - return description; - } - - /// Converts a parsed relative path to its original relative form. - String formatDescription(String containingPath, description) { - var sourcePath = description["path"]; - if (description["relative"]) { - sourcePath = p.relative(description['path'], from: containingPath); - } - - return sourcePath; - } - - /// Ensures that [description] is a valid path description and returns a - /// normalized path to the package. - /// - /// It must be a map, with a "path" key containing a path that points to an - /// existing directory. Throws an [ApplicationException] if the path is - /// invalid. - String _validatePath(String name, description) { - var dir = description["path"]; - - if (dirExists(dir)) return dir; - - if (fileExists(dir)) { - fail( - 'Path dependency for package $name must refer to a directory, ' - 'not a file. Was "$dir".'); - } - - throw new PackageNotFoundException( - 'Could not find package $name at "$dir".'); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/source/unknown.dart b/sdk/lib/_internal/pub_generated/lib/src/source/unknown.dart deleted file mode 100644 index a3049cb5e05..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/source/unknown.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.source.unknown; - -import 'dart:async'; - -import '../package.dart'; -import '../pubspec.dart'; -import '../source.dart'; - -/// A [Null Object] that represents a source not recognized by pub. -/// -/// It provides some default behavior so that pub can work with sources it -/// doesn't recognize. -/// -/// [null object]: http://en.wikipedia.org/wiki/Null_Object_pattern -class UnknownSource extends Source { - final String name; - - UnknownSource(this.name); - - /// Two unknown sources are the same if their names are the same. - bool operator ==(other) => other is UnknownSource && other.name == name; - - int get hashCode => name.hashCode; - - Future doDescribe(PackageId id) => - throw new UnsupportedError( - "Cannot describe a package from unknown source '$name'."); - - Future get(PackageId id, String symlink) => - throw new UnsupportedError("Cannot get an unknown source '$name'."); - - /// Returns the directory where this package can be found locally. - Future getDirectory(PackageId id) => - throw new UnsupportedError( - "Cannot find a package from an unknown source '$name'."); - - bool descriptionsEqual(description1, description2) => - description1 == description2; - - /// Unknown sources do no validation. - dynamic parseDescription(String containingPath, description, - {bool fromLockFile: false}) => - description; -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/source_registry.dart b/sdk/lib/_internal/pub_generated/lib/src/source_registry.dart deleted file mode 100644 index fc5b4f38d1f..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/source_registry.dart +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.source_registry; - -import 'dart:collection'; - -import 'package.dart'; -import 'source.dart'; -import 'source/unknown.dart'; - -/// A class that keeps track of [Source]s used for getting packages. -class SourceRegistry extends IterableBase { - final _sources = new Map(); - Source _default; - - /// Returns the default source, which is used when no source is specified. - Source get defaultSource => _default; - - /// Iterates over the registered sources in name order. - Iterator get iterator { - var sources = _sources.values.toList(); - sources.sort((a, b) => a.name.compareTo(b.name)); - return sources.iterator; - } - - /// Returns whether [id1] and [id2] refer to the same package, including - /// validating that their descriptions are equivalent. - bool idsEqual(PackageId id1, PackageId id2) { - if (id1 != id2) return false; - if (id1 == null && id2 == null) return true; - return idDescriptionsEqual(id1, id2); - } - - /// Returns whether [id1] and [id2] have the same source and description. - /// - /// This doesn't check whether the name or versions are equal. - bool idDescriptionsEqual(PackageId id1, PackageId id2) { - if (id1.source != id2.source) return false; - return this[id1.source].descriptionsEqual(id1.description, id2.description); - } - - /// Sets the default source. - /// - /// This takes a string, which must be the name of a registered source. - void setDefault(String name) { - if (!_sources.containsKey(name)) { - throw new StateError('Default source $name is not in the registry'); - } - - _default = _sources[name]; - } - - /// Registers a new source. - /// - /// This source may not have the same name as a source that's already been - /// registered. - void register(Source source) { - if (_sources.containsKey(source.name)) { - throw new StateError( - 'Source registry already has a source named ' '${source.name}'); - } - - _sources[source.name] = source; - } - - /// Returns the source named [name]. - /// - /// Returns an [UnknownSource] if no source with that name has been - /// registered. If [name] is null, returns the default source. - Source operator [](String name) { - if (name == null) { - if (defaultSource != null) return defaultSource; - throw new StateError('No default source has been registered'); - } - - if (_sources.containsKey(name)) return _sources[name]; - return new UnknownSource(name); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/system_cache.dart b/sdk/lib/_internal/pub_generated/lib/src/system_cache.dart deleted file mode 100644 index 424585da3a0..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/system_cache.dart +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.system_cache; - -import 'dart:async'; -import 'dart:io'; - -import 'package:path/path.dart' as path; - -import 'io.dart'; -import 'io.dart' as io show createTempDir; -import 'log.dart' as log; -import 'package.dart'; -import 'source/cached.dart'; -import 'source/git.dart'; -import 'source/hosted.dart'; -import 'source/path.dart'; -import 'source.dart'; -import 'source_registry.dart'; - -/// The system-wide cache of downloaded packages. -/// -/// This cache contains all packages that are downloaded from the internet. -/// Packages that are available locally (e.g. path dependencies) don't use this -/// cache. -class SystemCache { - /// The root directory where this package cache is located. - final String rootDir; - - String get tempDir => path.join(rootDir, '_temp'); - - /// The sources from which to get packages. - final sources = new SourceRegistry(); - - static String defaultDir = (() { - if (Platform.environment.containsKey('PUB_CACHE')) { - return Platform.environment['PUB_CACHE']; - } else if (Platform.operatingSystem == 'windows') { - var appData = Platform.environment['APPDATA']; - return path.join(appData, 'Pub', 'Cache'); - } else { - return '${Platform.environment['HOME']}/.pub-cache'; - } - })(); - - /// Creates a new package cache which is backed by the given directory on the - /// user's file system. - SystemCache([String rootDir]) - : rootDir = rootDir == null ? SystemCache.defaultDir : rootDir; - - /// Creates a system cache and registers the standard set of sources. - /// - /// If [isOffline] is `true`, then the offline hosted source will be used. - /// Defaults to `false`. - factory SystemCache.withSources({String rootDir, bool isOffline: false}) { - var cache = new SystemCache(rootDir); - cache.register(new GitSource()); - - if (isOffline) { - cache.register(new OfflineHostedSource()); - } else { - cache.register(new HostedSource()); - } - - cache.register(new PathSource()); - cache.sources.setDefault('hosted'); - return cache; - } - - /// Registers a new source. - /// - /// This source must not have the same name as a source that's already been - /// registered. - void register(Source source) { - source.bind(this); - sources.register(source); - } - - /// Determines if the system cache contains the package identified by [id]. - Future contains(PackageId id) { - var source = sources[id.source]; - - if (source is! CachedSource) { - throw new ArgumentError("Package $id is not cacheable."); - } - - return source.isInSystemCache(id); - } - - /// Create a new temporary directory within the system cache. - /// - /// The system cache maintains its own temporary directory that it uses to - /// stage packages into while downloading. It uses this instead of the OS's - /// system temp directory to ensure that it's on the same volume as the pub - /// system cache so that it can move the directory from it. - String createTempDir() { - var temp = ensureDir(tempDir); - return io.createTempDir(temp, 'dir'); - } - - /// Deletes the system cache's internal temp directory. - void deleteTempDir() { - log.fine('Clean up system cache temp directory $tempDir.'); - if (dirExists(tempDir)) deleteEntry(tempDir); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/transcript.dart b/sdk/lib/_internal/pub_generated/lib/src/transcript.dart deleted file mode 100644 index a2778c0c824..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/transcript.dart +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.transcript; - -import 'dart:collection'; - -/// A rolling transcript of entries of type [T]. -/// -/// It has a maximum number of entries. If entries are added that exceed that -/// it discards entries from the *middle* of the transcript. Generally, in logs, -/// the first and last entries are the most important, so it maintains those. -class Transcript { - /// The maximum number of transcript entries. - final int max; - - /// The number of entries that were discarded after reaching [max]. - int get discarded => _discarded; - int _discarded = 0; - - /// The earliest half of the entries. - /// - /// This will be empty until the maximum number of entries is hit at which - /// point the oldest half of the entries will be moved from [_newest] to - /// here. - final _oldest = new List(); - - /// The most recent half of the entries. - final _newest = new Queue(); - - /// Creates a new [Transcript] that can hold up to [max] entries. - Transcript(this.max); - - /// Adds [entry] to the transcript. - /// - /// If the transcript already has the maximum number of entries, discards one - /// from the middle. - void add(T entry) { - if (discarded > 0) { - // We're already in "rolling" mode. - _newest.removeFirst(); - _discarded++; - } else if (_newest.length == max) { - // We are crossing the threshold where we have to discard items. Copy - // the first half over to the oldest list. - while (_newest.length > max ~/ 2) { - _oldest.add(_newest.removeFirst()); - } - - // Discard the middle item. - _newest.removeFirst(); - _discarded++; - } - - _newest.add(entry); - } - - /// Traverses the entries in the transcript from oldest to newest. - /// - /// Invokes [onEntry] for each item. When it reaches the point in the middle - /// where excess entries where dropped, invokes [onGap] with the number of - /// dropped entries. If no more than [max] entries were added, does not - /// invoke [onGap]. - void forEach(void onEntry(T entry), [void onGap(int)]) { - if (_oldest.isNotEmpty) { - _oldest.forEach(onEntry); - if (onGap != null) onGap(discarded); - } - - _newest.forEach(onEntry); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/utils.dart b/sdk/lib/_internal/pub_generated/lib/src/utils.dart deleted file mode 100644 index d03db2a4d72..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/utils.dart +++ /dev/null @@ -1,924 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Generic utility functions. Stuff that should possibly be in core. -library pub.utils; - -import 'dart:async'; -import "dart:convert"; -import 'dart:io'; - -// This is used by [libraryPath]. It must be kept up-to-date with all libraries -// whose paths are looked up using that function. -@MirrorsUsed(targets: const ['pub.io', 'test_pub']) -import 'dart:mirrors'; - -import "package:crypto/crypto.dart"; -import 'package:path/path.dart' as path; -import "package:stack_trace/stack_trace.dart"; - -import 'exceptions.dart'; -import 'log.dart' as log; - -export '../../asset/dart/utils.dart'; - -/// A pair of values. -class Pair { - E first; - F last; - - Pair(this.first, this.last); - - String toString() => '($first, $last)'; - - bool operator ==(other) { - if (other is! Pair) return false; - return other.first == first && other.last == last; - } - - int get hashCode => first.hashCode ^ last.hashCode; -} - -/// A completer that waits until all added [Future]s complete. -// TODO(rnystrom): Copied from web_components. Remove from here when it gets -// added to dart:core. (See #6626.) -class FutureGroup { - int _pending = 0; - Completer> _completer = new Completer>(); - final List> futures = >[]; - bool completed = false; - - final List _values = []; - - /// Wait for [task] to complete. - Future add(Future task) { - if (completed) { - throw new StateError("The FutureGroup has already completed."); - } - - _pending++; - futures.add(task.then((value) { - if (completed) return; - - _pending--; - _values.add(value); - - if (_pending <= 0) { - completed = true; - _completer.complete(_values); - } - }).catchError((e, stackTrace) { - if (completed) return; - - completed = true; - _completer.completeError(e, stackTrace); - })); - - return task; - } - - Future get future => _completer.future; -} - -/// Like [new Future], but avoids around issue 11911 by using [new Future.value] -/// under the covers. -Future newFuture(callback()) => new Future.value().then((_) => callback()); - -/// Runs [callback] in an error zone and pipes any unhandled error to the -/// returned [Future]. -/// -/// If the returned [Future] produces an error, its stack trace will always be a -/// [Chain]. By default, this chain will contain only the local stack trace, but -/// if [captureStackChains] is passed, it will contain the full stack chain for -/// the error. -Future captureErrors(Future callback(), {bool captureStackChains: false}) { - var completer = new Completer(); - var wrappedCallback = () { - new Future.sync( - callback).then(completer.complete).catchError((e, stackTrace) { - // [stackTrace] can be null if we're running without [captureStackChains], - // since dart:io will often throw errors without stack traces. - if (stackTrace != null) { - stackTrace = new Chain.forTrace(stackTrace); - } else { - stackTrace = new Chain([]); - } - if (!completer.isCompleted) completer.completeError(e, stackTrace); - }); - }; - - if (captureStackChains) { - Chain.capture(wrappedCallback, onError: (error, stackTrace) { - if (!completer.isCompleted) completer.completeError(error, stackTrace); - }); - } else { - runZoned(wrappedCallback, onError: (e, stackTrace) { - if (stackTrace == null) { - stackTrace = new Chain.current(); - } else { - stackTrace = new Chain([new Trace.from(stackTrace)]); - } - if (!completer.isCompleted) completer.completeError(e, stackTrace); - }); - } - - return completer.future; -} - -/// Like [Future.wait], but prints all errors from the futures as they occur and -/// only returns once all Futures have completed, successfully or not. -/// -/// This will wrap the first error thrown in a [SilentException] and rethrow it. -Future waitAndPrintErrors(Iterable futures) { - return Future.wait(futures.map((future) { - return future.catchError((error, stackTrace) { - log.exception(error, stackTrace); - throw error; - }); - })).catchError((error, stackTrace) { - throw new SilentException(error, stackTrace); - }); -} - -/// Returns a [StreamTransformer] that will call [onDone] when the stream -/// completes. -/// -/// The stream will be passed through unchanged. -StreamTransformer onDoneTransformer(void onDone()) { - return new StreamTransformer.fromHandlers(handleDone: (sink) { - onDone(); - sink.close(); - }); -} - -// TODO(rnystrom): Move into String? -/// Pads [source] to [length] by adding spaces at the end. -String padRight(String source, int length) { - final result = new StringBuffer(); - result.write(source); - - while (result.length < length) { - result.write(' '); - } - - return result.toString(); -} - -/// Pads [source] to [length] by adding [char]s at the beginning. -/// -/// If [char] is `null`, it defaults to a space. -String padLeft(String source, int length, [String char]) { - if (char == null) char = ' '; - if (source.length >= length) return source; - - return char * (length - source.length) + source; -} - -/// Returns a labelled sentence fragment starting with [name] listing the -/// elements [iter]. -/// -/// If [iter] does not have one item, name will be pluralized by adding "s" or -/// using [plural], if given. -String namedSequence(String name, Iterable iter, [String plural]) { - if (iter.length == 1) return "$name ${iter.single}"; - - if (plural == null) plural = "${name}s"; - return "$plural ${toSentence(iter)}"; -} - -/// Returns a sentence fragment listing the elements of [iter]. -/// -/// This converts each element of [iter] to a string and separates them with -/// commas and/or "and" where appropriate. -String toSentence(Iterable iter) { - if (iter.length == 1) return iter.first.toString(); - return iter.take(iter.length - 1).join(", ") + " and ${iter.last}"; -} - -/// Returns [name] if [number] is 1, or the plural of [name] otherwise. -/// -/// By default, this just adds "s" to the end of [name] to get the plural. If -/// [plural] is passed, that's used instead. -String pluralize(String name, int number, {String plural}) { - if (number == 1) return name; - if (plural != null) return plural; - return '${name}s'; -} - -/// Escapes any regex metacharacters in [string] so that using as a [RegExp] -/// pattern will match the string literally. -// TODO(rnystrom): Remove when #4706 is fixed. -String quoteRegExp(String string) { - // Note: make sure "\" is done first so that we don't escape the other - // escaped characters. We could do all of the replaces at once with a regexp - // but string literal for regex that matches all regex metacharacters would - // be a bit hard to read. - for (var metacharacter in r"\^$.*+?()[]{}|".split("")) { - string = string.replaceAll(metacharacter, "\\$metacharacter"); - } - - return string; -} - -/// Creates a URL string for [address]:[port]. -/// -/// Handles properly formatting IPv6 addresses. -Uri baseUrlForAddress(InternetAddress address, int port) { - if (address.isLoopback) { - return new Uri(scheme: "http", host: "localhost", port: port); - } - - // IPv6 addresses in URLs need to be enclosed in square brackets to avoid - // URL ambiguity with the ":" in the address. - if (address.type == InternetAddressType.IP_V6) { - return new Uri(scheme: "http", host: "[${address.address}]", port: port); - } - - return new Uri(scheme: "http", host: address.address, port: port); -} - -/// Returns whether [host] is a host for a localhost or loopback URL. -/// -/// Unlike [InternetAddress.isLoopback], this hostnames from URLs as well as -/// from [InternetAddress]es, including "localhost". -bool isLoopback(String host) { - if (host == 'localhost') return true; - - // IPv6 hosts in URLs are surrounded by square brackets. - if (host.startsWith("[") && host.endsWith("]")) { - host = host.substring(1, host.length - 1); - } - - try { - return new InternetAddress(host).isLoopback; - } on ArgumentError catch (_) { - // The host isn't an IP address and isn't "localhost', so it's almost - // certainly not a loopback host. - return false; - } -} - -/// Flattens nested lists inside an iterable into a single list containing only -/// non-list elements. -List flatten(Iterable nested) { - var result = []; - helper(list) { - for (var element in list) { - if (element is List) { - helper(element); - } else { - result.add(element); - } - } - } - helper(nested); - return result; -} - -/// Returns a set containing all elements in [minuend] that are not in -/// [subtrahend]. -Set setMinus(Iterable minuend, Iterable subtrahend) { - var minuendSet = new Set.from(minuend); - minuendSet.removeAll(subtrahend); - return minuendSet; -} - -/// Returns whether there's any overlap between [set1] and [set2]. -bool overlaps(Set set1, Set set2) { - // Iterate through the smaller set. - var smaller = set1.length > set2.length ? set1 : set2; - var larger = smaller == set1 ? set2 : set1; - return smaller.any(larger.contains); -} - -/// Returns a list containing the sorted elements of [iter]. -List ordered(Iterable iter) { - var list = iter.toList(); - list.sort(); - return list; -} - -/// Returns the element of [iter] for which [f] returns the minimum value. -minBy(Iterable iter, Comparable f(element)) { - var min = null; - var minComparable = null; - for (var element in iter) { - var comparable = f(element); - if (minComparable == null || comparable.compareTo(minComparable) < 0) { - min = element; - minComparable = comparable; - } - } - return min; -} - -/// Returns every pair of consecutive elements in [iter]. -/// -/// For example, if [iter] is `[1, 2, 3, 4]`, this will return `[(1, 2), (2, 3), -/// (3, 4)]`. -Iterable pairs(Iterable iter) { - var previous = iter.first; - return iter.skip(1).map((element) { - var oldPrevious = previous; - previous = element; - return new Pair(oldPrevious, element); - }); -} - -/// Creates a new map from [map] with new keys and values. -/// -/// The return values of [key] are used as the keys and the return values of -/// [value] are used as the values for the new map. -/// -/// [key] defaults to returning the original key and [value] defaults to -/// returning the original value. -Map mapMap(Map map, {key(key, value), value(key, value)}) { - if (key == null) key = (key, _) => key; - if (value == null) value = (_, value) => value; - - var result = {}; - map.forEach((mapKey, mapValue) { - result[key(mapKey, mapValue)] = value(mapKey, mapValue); - }); - return result; -} - -/// Like [Map.fromIterable], but [key] and [value] may return [Future]s. -Future mapFromIterableAsync(Iterable iter, {key(element), value(element)}) - { - if (key == null) key = (element) => element; - if (value == null) value = (element) => element; - - var map = new Map(); - return Future.wait(iter.map((element) { - return Future.wait( - [ - new Future.sync(() => key(element)), - new Future.sync(() => value(element))]).then((results) { - map[results[0]] = results[1]; - }); - })).then((_) => map); -} - -/// Returns the transitive closure of [graph]. -/// -/// This assumes [graph] represents a graph with a vertex for each key and an -/// edge betweek each key and the values for that key. -Map transitiveClosure(Map graph) { - // This uses the Floyd-Warshall algorithm - // (https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm). - var result = {}; - graph.forEach((vertex, edges) { - result[vertex] = new Set.from(edges)..add(vertex); - }); - - for (var vertex1 in graph.keys) { - for (var vertex2 in graph.keys) { - for (var vertex3 in graph.keys) { - if (result[vertex2].contains(vertex1) && - result[vertex1].contains(vertex3)) { - result[vertex2].add(vertex3); - } - } - } - } - - return result; -} - -/// Given a list of filenames, returns a set of patterns that can be used to -/// filter for those filenames. -/// -/// For a given path, that path ends with some string in the returned set if -/// and only if that path's basename is in [files]. -Set createFileFilter(Iterable files) { - return files.expand((file) { - var result = ["/$file"]; - if (Platform.operatingSystem == 'windows') result.add("\\$file"); - return result; - }).toSet(); -} - -/// Given a blacklist of directory names, returns a set of patterns that can -/// be used to filter for those directory names. -/// -/// For a given path, that path contains some string in the returned set if -/// and only if one of that path's components is in [dirs]. -Set createDirectoryFilter(Iterable dirs) { - return dirs.expand((dir) { - var result = ["/$dir/"]; - if (Platform.operatingSystem == 'windows') { - result - ..add("/$dir\\") - ..add("\\$dir/") - ..add("\\$dir\\"); - } - return result; - }).toSet(); -} - -/// Returns the maximum value in [iter] by [compare]. -/// -/// [compare] defaults to [Comparable.compare]. -maxAll(Iterable iter, [int compare(element1, element2)]) { - if (compare == null) compare = Comparable.compare; - return iter.reduce( - (max, element) => compare(element, max) > 0 ? element : max); -} - -/// Returns the minimum value in [iter] by [compare]. -/// -/// [compare] defaults to [Comparable.compare]. -minAll(Iterable iter, [int compare(element1, element2)]) { - if (compare == null) compare = Comparable.compare; - return iter.reduce( - (max, element) => compare(element, max) < 0 ? element : max); -} - -/// Replace each instance of [matcher] in [source] with the return value of -/// [fn]. -String replace(String source, Pattern matcher, String fn(Match)) { - var buffer = new StringBuffer(); - var start = 0; - for (var match in matcher.allMatches(source)) { - buffer.write(source.substring(start, match.start)); - start = match.end; - buffer.write(fn(match)); - } - buffer.write(source.substring(start)); - return buffer.toString(); -} - -/// Returns whether or not [str] ends with [matcher]. -bool endsWithPattern(String str, Pattern matcher) { - for (var match in matcher.allMatches(str)) { - if (match.end == str.length) return true; - } - return false; -} - -/// Returns the hex-encoded sha1 hash of [source]. -String sha1(String source) { - var sha = new SHA1(); - sha.add(source.codeUnits); - return CryptoUtils.bytesToHex(sha.close()); -} - -/// Configures [future] so that its result (success or exception) is passed on -/// to [completer]. -void chainToCompleter(Future future, Completer completer) { - future.then(completer.complete, onError: completer.completeError); -} - -/// Ensures that [stream] can emit at least one value successfully (or close -/// without any values). -/// -/// For example, reading asynchronously from a non-existent file will return a -/// stream that fails on the first chunk. In order to handle that more -/// gracefully, you may want to check that the stream looks like it's working -/// before you pipe the stream to something else. -/// -/// This lets you do that. It returns a [Future] that completes to a [Stream] -/// emitting the same values and errors as [stream], but only if at least one -/// value can be read successfully. If an error occurs before any values are -/// emitted, the returned Future completes to that error. -Future validateStream(Stream stream) { - var completer = new Completer(); - var controller = new StreamController(sync: true); - - StreamSubscription subscription; - subscription = stream.listen((value) { - // We got a value, so the stream is valid. - if (!completer.isCompleted) completer.complete(controller.stream); - controller.add(value); - }, onError: (error, [stackTrace]) { - // If the error came after values, it's OK. - if (completer.isCompleted) { - controller.addError(error, stackTrace); - return; - } - - // Otherwise, the error came first and the stream is invalid. - completer.completeError(error, stackTrace); - - // We don't be returning the stream at all in this case, so unsubscribe - // and swallow the error. - subscription.cancel(); - }, onDone: () { - // It closed with no errors, so the stream is valid. - if (!completer.isCompleted) completer.complete(controller.stream); - controller.close(); - }); - - return completer.future; -} - -// TODO(nweiz): remove this when issue 7964 is fixed. -/// Returns a [Future] that will complete to the first element of [stream]. -/// -/// Unlike [Stream.first], this is safe to use with single-subscription streams. -Future streamFirst(Stream stream) { - var completer = new Completer(); - var subscription; - subscription = stream.listen((value) { - subscription.cancel(); - completer.complete(value); - }, onError: (e, [stackTrace]) { - completer.completeError(e, stackTrace); - }, onDone: () { - completer.completeError(new StateError("No elements"), new Chain.current()); - }, cancelOnError: true); - return completer.future; -} - -/// Returns a wrapped version of [stream] along with a [StreamSubscription] that -/// can be used to control the wrapped stream. -Pair streamWithSubscription(Stream stream) { - var controller = stream.isBroadcast ? - new StreamController.broadcast(sync: true) : - new StreamController(sync: true); - var subscription = stream.listen( - controller.add, - onError: controller.addError, - onDone: controller.close); - return new Pair(controller.stream, subscription); -} - -// TODO(nweiz): remove this when issue 7787 is fixed. -/// Creates two single-subscription [Stream]s that each emit all values and -/// errors from [stream]. -/// -/// This is useful if [stream] is single-subscription but multiple subscribers -/// are necessary. -Pair tee(Stream stream) { - var controller1 = new StreamController(sync: true); - var controller2 = new StreamController(sync: true); - stream.listen((value) { - controller1.add(value); - controller2.add(value); - }, onError: (error, [stackTrace]) { - controller1.addError(error, stackTrace); - controller2.addError(error, stackTrace); - }, onDone: () { - controller1.close(); - controller2.close(); - }); - return new Pair(controller1.stream, controller2.stream); -} - -/// Merges [stream1] and [stream2] into a single stream that emits events from -/// both sources. -Stream mergeStreams(Stream stream1, Stream stream2) { - var doneCount = 0; - var controller = new StreamController(sync: true); - - for (var stream in [stream1, stream2]) { - stream.listen(controller.add, onError: controller.addError, onDone: () { - doneCount++; - if (doneCount == 2) controller.close(); - }); - } - - return controller.stream; -} - -/// A regular expression matching a trailing CR character. -final _trailingCR = new RegExp(r"\r$"); - -// TODO(nweiz): Use `text.split(new RegExp("\r\n?|\n\r?"))` when issue 9360 is -// fixed. -/// Splits [text] on its line breaks in a Windows-line-break-friendly way. -List splitLines(String text) => - text.split("\n").map((line) => line.replaceFirst(_trailingCR, "")).toList(); - -/// Converts a stream of arbitrarily chunked strings into a line-by-line stream. -/// -/// The lines don't include line termination characters. A single trailing -/// newline is ignored. -Stream streamToLines(Stream stream) { - var buffer = new StringBuffer(); - return stream.transform( - new StreamTransformer.fromHandlers(handleData: (chunk, sink) { - var lines = splitLines(chunk); - var leftover = lines.removeLast(); - for (var line in lines) { - if (!buffer.isEmpty) { - buffer.write(line); - line = buffer.toString(); - buffer = new StringBuffer(); - } - - sink.add(line); - } - buffer.write(leftover); - }, handleDone: (sink) { - if (!buffer.isEmpty) sink.add(buffer.toString()); - sink.close(); - })); -} - -/// Like [Iterable.where], but allows [test] to return [Future]s and uses the -/// results of those [Future]s as the test. -Future futureWhere(Iterable iter, test(value)) { - return Future.wait(iter.map((e) { - var result = test(e); - if (result is! Future) result = new Future.value(result); - return result.then((result) => new Pair(e, result)); - })).then( - (pairs) => - pairs.where( - (pair) => pair.last)).then((pairs) => pairs.map((pair) => pair.first)); -} - -// TODO(nweiz): unify the following functions with the utility functions in -// pkg/http. - -/// Like [String.split], but only splits on the first occurrence of the pattern. -/// -/// This always returns an array of two elements or fewer. -List split1(String toSplit, String pattern) { - if (toSplit.isEmpty) return []; - - var index = toSplit.indexOf(pattern); - if (index == -1) return [toSplit]; - return [ - toSplit.substring(0, index), - toSplit.substring(index + pattern.length)]; -} - -/// Adds additional query parameters to [url], overwriting the original -/// parameters if a name conflict occurs. -Uri addQueryParameters(Uri url, Map parameters) { - var queryMap = queryToMap(url.query); - queryMap.addAll(parameters); - return url.resolve("?${mapToQuery(queryMap)}"); -} - -/// Convert a URL query string (or `application/x-www-form-urlencoded` body) -/// into a [Map] from parameter names to values. -Map queryToMap(String queryList) { - var map = {}; - for (var pair in queryList.split("&")) { - var split = split1(pair, "="); - if (split.isEmpty) continue; - var key = urlDecode(split[0]); - var value = split.length > 1 ? urlDecode(split[1]) : ""; - map[key] = value; - } - return map; -} - -/// Convert a [Map] from parameter names to values to a URL query string. -String mapToQuery(Map map) { - var pairs = >[]; - map.forEach((key, value) { - key = Uri.encodeQueryComponent(key); - value = - (value == null || value.isEmpty) ? null : Uri.encodeQueryComponent(value); - pairs.add([key, value]); - }); - return pairs.map((pair) { - if (pair[1] == null) return pair[0]; - return "${pair[0]}=${pair[1]}"; - }).join("&"); -} - -/// Returns the union of all elements in each set in [sets]. -Set unionAll(Iterable sets) => - sets.fold(new Set(), (union, set) => union.union(set)); - -// TODO(nweiz): remove this when issue 9068 has been fixed. -/// Whether [uri1] and [uri2] are equal. -/// -/// This consider HTTP URIs to default to port 80, and HTTPs URIs to default to -/// port 443. -bool urisEqual(Uri uri1, Uri uri2) => - canonicalizeUri(uri1) == canonicalizeUri(uri2); - -/// Return [uri] with redundant port information removed. -Uri canonicalizeUri(Uri uri) { - return uri; -} - -/// Returns a human-friendly representation of [inputPath]. -/// -/// If [inputPath] isn't too distant from the current working directory, this -/// will return the relative path to it. Otherwise, it will return the absolute -/// path. -String nicePath(String inputPath) { - var relative = path.relative(inputPath); - var split = path.split(relative); - if (split.length > 1 && split[0] == '..' && split[1] == '..') { - return path.absolute(inputPath); - } - return relative; -} - -/// Returns a human-friendly representation of [duration]. -String niceDuration(Duration duration) { - var result = duration.inMinutes > 0 ? "${duration.inMinutes}:" : ""; - - var s = duration.inSeconds % 59; - var ms = duration.inMilliseconds % 1000; - - // If we're using verbose logging, be more verbose but more accurate when - // reporting timing information. - if (log.verbosity.isLevelVisible(log.Level.FINE)) { - ms = padLeft(ms.toString(), 3, '0'); - } else { - ms ~/= 100; - } - - return "$result$s.${ms}s"; -} - -/// Decodes a URL-encoded string. -/// -/// Unlike [Uri.decodeComponent], this includes replacing `+` with ` `. -String urlDecode(String encoded) => - Uri.decodeComponent(encoded.replaceAll("+", " ")); - -/// Takes a simple data structure (composed of [Map]s, [Iterable]s, scalar -/// objects, and [Future]s) and recursively resolves all the [Future]s contained -/// within. -/// -/// Completes with the fully resolved structure. -Future awaitObject(object) { - // Unroll nested futures. - if (object is Future) return object.then(awaitObject); - if (object is Iterable) { - return Future.wait(object.map(awaitObject).toList()); - } - if (object is! Map) return new Future.value(object); - - var pairs = >[]; - object.forEach((key, value) { - pairs.add(awaitObject(value).then((resolved) => new Pair(key, resolved))); - }); - return Future.wait(pairs).then((resolvedPairs) { - var map = {}; - for (var pair in resolvedPairs) { - map[pair.first] = pair.last; - } - return map; - }); -} - -/// Returns the path to the library named [libraryName]. -/// -/// The library name must be globally unique, or the wrong library path may be -/// returned. Any libraries accessed must be added to the [MirrorsUsed] -/// declaration in the import above. -String libraryPath(String libraryName) { - var lib = currentMirrorSystem().findLibrary(new Symbol(libraryName)); - return path.fromUri(lib.uri); -} - -/// Whether "special" strings such as Unicode characters or color escapes are -/// safe to use. -/// -/// On Windows or when not printing to a terminal, only printable ASCII -/// characters should be used. -bool get canUseSpecialChars => - !runningAsTest && - Platform.operatingSystem != 'windows' && - stdioType(stdout) == StdioType.TERMINAL; - -/// Gets a "special" string (ANSI escape or Unicode). -/// -/// On Windows or when not printing to a terminal, returns something else since -/// those aren't supported. -String getSpecial(String special, [String onWindows = '']) => - canUseSpecialChars ? special : onWindows; - -/// Prepends each line in [text] with [prefix]. -/// -/// If [firstPrefix] is passed, the first line is prefixed with that instead. -String prefixLines(String text, {String prefix: '| ', String firstPrefix}) { - var lines = text.split('\n'); - if (firstPrefix == null) { - return lines.map((line) => '$prefix$line').join('\n'); - } - - var firstLine = "$firstPrefix${lines.first}"; - lines = lines.skip(1).map((line) => '$prefix$line').toList(); - lines.insert(0, firstLine); - return lines.join('\n'); -} - -/// Whether pub is running as a subprocess in an integration test or in a unit -/// test that has explicitly set this. -bool runningAsTest = Platform.environment.containsKey('_PUB_TESTING'); - -/// Whether today is April Fools' day. -bool get isAprilFools { - // Tests should never see April Fools' output. - if (runningAsTest) return false; - - var date = new DateTime.now(); - return date.month == 4 && date.day == 1; -} - -/// Wraps [fn] to guard against several different kinds of stack overflow -/// exceptions: -/// -/// * A sufficiently long [Future] chain can cause a stack overflow if there are -/// no asynchronous operations in it (issue 9583). -/// * A recursive function that recurses too deeply without an asynchronous -/// operation can cause a stack overflow. -/// * Even if the former is guarded against by adding asynchronous operations, -/// returning a value through the [Future] chain can still cause a stack -/// overflow. -Future resetStack(fn()) { - // Using a [Completer] breaks the [Future] chain for the return value and - // avoids the third case described above. - var completer = new Completer(); - - // Using [new Future] adds an asynchronous operation that works around the - // first and second cases described above. - newFuture(fn).then((val) { - scheduleMicrotask(() => completer.complete(val)); - }).catchError((err, stackTrace) { - scheduleMicrotask(() => completer.completeError(err, stackTrace)); - }); - return completer.future; -} - -/// The subset of strings that don't need quoting in YAML. -/// -/// This pattern does not strictly follow the plain scalar grammar of YAML, -/// which means some strings may be unnecessarily quoted, but it's much simpler. -final _unquotableYamlString = new RegExp(r"^[a-zA-Z_-][a-zA-Z_0-9-]*$"); - -/// Converts [data], which is a parsed YAML object, to a pretty-printed string, -/// using indentation for maps. -String yamlToString(data) { - var buffer = new StringBuffer(); - - _stringify(bool isMapValue, String indent, data) { - // TODO(nweiz): Serialize using the YAML library once it supports - // serialization. - - // Use indentation for (non-empty) maps. - if (data is Map && !data.isEmpty) { - if (isMapValue) { - buffer.writeln(); - indent += ' '; - } - - // Sort the keys. This minimizes deltas in diffs. - var keys = data.keys.toList(); - keys.sort((a, b) => a.toString().compareTo(b.toString())); - - var first = true; - for (var key in keys) { - if (!first) buffer.writeln(); - first = false; - - var keyString = key; - if (key is! String || !_unquotableYamlString.hasMatch(key)) { - keyString = JSON.encode(key); - } - - buffer.write('$indent$keyString:'); - _stringify(true, indent, data[key]); - } - - return; - } - - // Everything else we just stringify using JSON to handle escapes in - // strings and number formatting. - var string = data; - - // Don't quote plain strings if not needed. - if (data is! String || !_unquotableYamlString.hasMatch(data)) { - string = JSON.encode(data); - } - - if (isMapValue) { - buffer.write(' $string'); - } else { - buffer.write('$indent$string'); - } - } - - _stringify(false, '', data); - return buffer.toString(); -} - -/// Throw a [ApplicationException] with [message]. -void fail(String message, [innerError, StackTrace innerTrace]) { - if (innerError != null) { - throw new WrappedException(message, innerError, innerTrace); - } else { - throw new ApplicationException(message); - } -} - -/// Throw a [DataException] with [message] to indicate that the command has -/// failed because of invalid input data. -/// -/// This will report the error and cause pub to exit with [exit_codes.DATA]. -void dataError(String message) => throw new DataException(message); diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator.dart b/sdk/lib/_internal/pub_generated/lib/src/validator.dart deleted file mode 100644 index 25e68435d3b..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator.dart +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator; - -import 'dart:async'; - -import 'entrypoint.dart'; -import 'log.dart' as log; -import 'utils.dart'; -import 'validator/compiled_dartdoc.dart'; -import 'validator/dependency.dart'; -import 'validator/dependency_override.dart'; -import 'validator/directory.dart'; -import 'validator/executable.dart'; -import 'validator/license.dart'; -import 'validator/name.dart'; -import 'validator/pubspec_field.dart'; -import 'validator/sdk_constraint.dart'; -import 'validator/size.dart'; -import 'validator/utf8_readme.dart'; - -/// The base class for validators that check whether a package is fit for -/// uploading. -/// -/// Each validator should override [errors], [warnings], or both to return -/// lists of errors or warnings to display to the user. Errors will cause the -/// package not to be uploaded; warnings will require the user to confirm the -/// upload. -abstract class Validator { - /// The entrypoint that's being validated. - final Entrypoint entrypoint; - - /// The accumulated errors for this validator. - /// - /// Filled by calling [validate]. - final errors = []; - - /// The accumulated warnings for this validator. - /// - /// Filled by calling [validate]. - final warnings = []; - - Validator(this.entrypoint); - - /// Validates the entrypoint, adding any errors and warnings to [errors] and - /// [warnings], respectively. - Future validate(); - - /// Run all validators on the [entrypoint] package and print their results. - /// - /// The future completes with the error and warning messages, respectively. - /// - /// [packageSize], if passed, should complete to the size of the tarred - /// package, in bytes. This is used to validate that it's not too big to - /// upload to the server. - static Future, List>> runAll(Entrypoint entrypoint, - [Future packageSize]) { - var validators = [ - new LicenseValidator(entrypoint), - new NameValidator(entrypoint), - new PubspecFieldValidator(entrypoint), - new DependencyValidator(entrypoint), - new DependencyOverrideValidator(entrypoint), - new DirectoryValidator(entrypoint), - new ExecutableValidator(entrypoint), - new CompiledDartdocValidator(entrypoint), - new Utf8ReadmeValidator(entrypoint), - new SdkConstraintValidator(entrypoint)]; - if (packageSize != null) { - validators.add(new SizeValidator(entrypoint, packageSize)); - } - - return Future.wait( - validators.map((validator) => validator.validate())).then((_) { - var errors = flatten(validators.map((validator) => validator.errors)); - var warnings = flatten(validators.map((validator) => validator.warnings)); - - if (!errors.isEmpty) { - log.error("Missing requirements:"); - for (var error in errors) { - log.error("* ${error.split('\n').join('\n ')}"); - } - log.error(""); - } - - if (!warnings.isEmpty) { - log.warning("Suggestions:"); - for (var warning in warnings) { - log.warning("* ${warning.split('\n').join('\n ')}"); - } - log.warning(""); - } - - return new Pair, List>(errors, warnings); - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/compiled_dartdoc.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/compiled_dartdoc.dart deleted file mode 100644 index 99900d8916c..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/compiled_dartdoc.dart +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.compiled_dartdoc; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../entrypoint.dart'; -import '../io.dart'; -import '../validator.dart'; - -/// Validates that a package doesn't contain compiled Dartdoc -/// output. -class CompiledDartdocValidator extends Validator { - CompiledDartdocValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - return new Future.sync(() { - for (var entry in entrypoint.root.listFiles(useGitIgnore: true)) { - if (path.basename(entry) != "nav.json") continue; - var dir = path.dirname(entry); - - // Look for tell-tale Dartdoc output files all in the same directory. - var files = [ - entry, - path.join(dir, "index.html"), - path.join(dir, "styles.css"), - path.join(dir, "dart-logo-small.png"), - path.join(dir, "client-live-nav.js")]; - - if (files.every((val) => fileExists(val))) { - warnings.add( - "Avoid putting generated documentation in " "${path.relative(dir)}.\n" - "Generated documentation bloats the package with redundant " "data."); - } - } - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/dependency.dart deleted file mode 100644 index e57b09660e2..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency.dart +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.dependency; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; - -import '../entrypoint.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../utils.dart'; -import '../validator.dart'; - -/// The range of all pub versions that don't support `^` version constraints. -final _preCaretPubVersions = new VersionConstraint.parse("<1.8.0-dev.3.0"); - -// TODO(nweiz): replace this with "^1.8.0" for the 1.8 release. -/// The range of all pub versions that do support `^` version constraints. -/// -/// This is intersected with the user's SDK constraint to provide a suggested -/// constraint. -final _postCaretPubVersions = new VersionConstraint.parse("^1.8.0-dev.3.0"); - -/// A validator that validates a package's dependencies. -class DependencyValidator extends Validator { - /// Whether the SDK constraint guarantees that `^` version constraints are - /// safe. - bool get _caretAllowed => - entrypoint.root.pubspec.environment.sdkVersion.intersect( - _preCaretPubVersions).isEmpty; - - DependencyValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var caretDeps = []; - var it0 = entrypoint.root.pubspec.dependencies.iterator; - break0() { - join0() { - completer0.complete(); - } - if (caretDeps.isNotEmpty && !_caretAllowed) { - _errorAboutCaretConstraints(caretDeps); - join0(); - } else { - join0(); - } - } - var trampoline0; - continue0() { - trampoline0 = null; - if (it0.moveNext()) { - var dependency = it0.current; - join1() { - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } - if (dependency.source != "hosted") { - new Future.value(_warnAboutSource(dependency)).then((x0) { - trampoline0 = () { - trampoline0 = null; - try { - x0; - join1(); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }; - do trampoline0(); while (trampoline0 != null); - }, onError: completer0.completeError); - } else { - join2() { - join1(); - } - if (dependency.constraint.isAny) { - _warnAboutNoConstraint(dependency); - join2(); - } else { - join3() { - join2(); - } - if (dependency.constraint is Version) { - _warnAboutSingleVersionConstraint(dependency); - join3(); - } else { - join4() { - join3(); - } - if (dependency.constraint is VersionRange) { - join5() { - join6() { - join4(); - } - if (dependency.constraint.toString().startsWith("^")) { - caretDeps.add(dependency); - join6(); - } else { - join6(); - } - } - if (dependency.constraint.min == null) { - _warnAboutNoConstraintLowerBound(dependency); - join5(); - } else { - join7() { - join5(); - } - if (dependency.constraint.max == null) { - _warnAboutNoConstraintUpperBound(dependency); - join7(); - } else { - join7(); - } - } - } else { - join4(); - } - } - } - } - } else { - break0(); - } - } - trampoline0 = continue0; - do trampoline0(); while (trampoline0 != null); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } - - /// Warn that dependencies should use the hosted source. - Future _warnAboutSource(PackageDep dep) { - return entrypoint.cache.sources['hosted'].getVersions( - dep.name, - dep.name).catchError((e) => []).then((versions) { - var constraint; - var primary = Version.primary(versions); - if (primary != null) { - constraint = _constraintForVersion(primary); - } else { - constraint = dep.constraint.toString(); - if (!dep.constraint.isAny && dep.constraint is! Version) { - constraint = '"$constraint"'; - } - } - - // Path sources are errors. Other sources are just warnings. - var messages = warnings; - if (dep.source == "path") { - messages = errors; - } - - messages.add( - 'Don\'t depend on "${dep.name}" from the ${dep.source} ' - 'source. Use the hosted source instead. For example:\n' '\n' 'dependencies:\n' - ' ${dep.name}: $constraint\n' '\n' - 'Using the hosted source ensures that everyone can download your ' - 'package\'s dependencies along with your package.'); - }); - } - - /// Warn that dependencies should have version constraints. - void _warnAboutNoConstraint(PackageDep dep) { - var message = - 'Your dependency on "${dep.name}" should have a version ' 'constraint.'; - var locked = entrypoint.lockFile.packages[dep.name]; - if (locked != null) { - message = - '$message For example:\n' '\n' 'dependencies:\n' - ' ${dep.name}: ${_constraintForVersion(locked.version)}\n'; - } - warnings.add( - "$message\n" - 'Without a constraint, you\'re promising to support ${log.bold("all")} ' - 'future versions of "${dep.name}".'); - } - - /// Warn that dependencies should allow more than a single version. - void _warnAboutSingleVersionConstraint(PackageDep dep) { - warnings.add( - 'Your dependency on "${dep.name}" should allow more than one version. ' - 'For example:\n' '\n' 'dependencies:\n' - ' ${dep.name}: ${_constraintForVersion(dep.constraint)}\n' '\n' - 'Constraints that are too tight will make it difficult for people to ' - 'use your package\n' - 'along with other packages that also depend on "${dep.name}".'); - } - - /// Warn that dependencies should have lower bounds on their constraints. - void _warnAboutNoConstraintLowerBound(PackageDep dep) { - var message = 'Your dependency on "${dep.name}" should have a lower bound.'; - var locked = entrypoint.lockFile.packages[dep.name]; - if (locked != null) { - var constraint; - if (locked.version == (dep.constraint as VersionRange).max) { - constraint = _constraintForVersion(locked.version); - } else { - constraint = '">=${locked.version} ${dep.constraint}"'; - } - - message = - '$message For example:\n' '\n' 'dependencies:\n' ' ${dep.name}: $constraint\n'; - } - warnings.add( - "$message\n" - 'Without a constraint, you\'re promising to support ${log.bold("all")} ' - 'previous versions of "${dep.name}".'); - } - - /// Warn that dependencies should have upper bounds on their constraints. - void _warnAboutNoConstraintUpperBound(PackageDep dep) { - var constraint; - if ((dep.constraint as VersionRange).includeMin) { - constraint = _constraintForVersion((dep.constraint as VersionRange).min); - } else { - constraint = - '"${dep.constraint} ' '<${(dep.constraint as VersionRange).min.nextBreaking}"'; - } - - warnings.add( - 'Your dependency on "${dep.name}" should have an upper bound. For ' 'example:\n' - '\n' 'dependencies:\n' ' ${dep.name}: $constraint\n' '\n' - 'Without an upper bound, you\'re promising to support ' - '${log.bold("all")} future versions of ${dep.name}.'); - } - - /// Emits an error for any version constraints that use `^` without an - /// appropriate SDK constraint. - void _errorAboutCaretConstraints(List caretDeps) { - var newSdkConstraint = - entrypoint.root.pubspec.environment.sdkVersion.intersect(_postCaretPubVersions); - - if (newSdkConstraint.isEmpty) newSdkConstraint = _postCaretPubVersions; - - var buffer = new StringBuffer( - "Older versions of pub don't support ^ version constraints.\n" - "Make sure your SDK constraint excludes those old versions:\n" "\n" - "environment:\n" " sdk: \"$newSdkConstraint\"\n" "\n"); - - if (caretDeps.length == 1) { - buffer.writeln("Or use a fully-expanded constraint:"); - } else { - buffer.writeln("Or use fully-expanded constraints:"); - } - - buffer.writeln(); - buffer.writeln("dependencies:"); - - caretDeps.forEach((dep) { - VersionRange constraint = dep.constraint; - buffer.writeln( - " ${dep.name}: \">=${constraint.min} <${constraint.max}\""); - }); - - errors.add(buffer.toString().trim()); - } - - /// Returns the suggested version constraint for a dependency that was tested - /// against [version]. - String _constraintForVersion(Version version) { - if (_caretAllowed) return "^$version"; - return '">=$version <${version.nextBreaking}"'; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency_override.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/dependency_override.dart deleted file mode 100644 index c01b27065d3..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/dependency_override.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.dependency_override; - -import 'dart:async'; - -import '../entrypoint.dart'; -import '../validator.dart'; - -/// A validator that validates a package's dependencies overrides (or the -/// absence thereof). -class DependencyOverrideValidator extends Validator { - DependencyOverrideValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - if (entrypoint.root.dependencyOverrides.isNotEmpty) { - errors.add( - 'Your pubspec.yaml must not have a "dependency_overrides" field.\n' - 'This ensures you test your package against the same versions of ' - 'its dependencies\n' 'that users will have when they use it.'); - } - return new Future.value(); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/directory.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/directory.dart deleted file mode 100644 index a9935e8461d..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/directory.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.directory; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../entrypoint.dart'; -import '../io.dart'; -import '../validator.dart'; - -/// A validator that validates a package's top-level directories. -class DirectoryValidator extends Validator { - DirectoryValidator(Entrypoint entrypoint) - : super(entrypoint); - - static final _PLURAL_NAMES = [ - "benchmarks", - "docs", - "examples", - "tests", - "tools"]; - - Future validate() { - return new Future.sync(() { - for (var dir in listDir(entrypoint.root.dir)) { - if (!dirExists(dir)) continue; - - dir = path.basename(dir); - if (_PLURAL_NAMES.contains(dir)) { - // Cut off the "s" - var singularName = dir.substring(0, dir.length - 1); - warnings.add( - 'Rename the top-level "$dir" directory to ' '"$singularName".\n' - 'The Pub layout convention is to use singular directory ' 'names.\n' - 'Plural names won\'t be correctly identified by Pub and other ' 'tools.'); - } - - if (dir.contains(new RegExp(r"^samples?$"))) { - warnings.add( - 'Rename the top-level "$dir" directory to "example".\n' - 'This allows Pub to find your examples and create "packages" ' - 'directories for them.\n'); - } - } - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/executable.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/executable.dart deleted file mode 100644 index 537edc43635..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/executable.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.executable; - -import 'dart:async'; - -import 'package:path/path.dart' as p; - -import '../entrypoint.dart'; -import '../validator.dart'; - -/// Validates that a package's pubspec doesn't contain executables that -/// reference non-existent scripts. -class ExecutableValidator extends Validator { - ExecutableValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var binFiles = - entrypoint.root.listFiles(beneath: "bin", recursive: false).map(((path) { - return entrypoint.root.relative(path); - })).toList(); - entrypoint.root.pubspec.executables.forEach(((executable, script) { - var scriptPath = p.join("bin", "$script.dart"); - if (binFiles.contains(scriptPath)) return; - warnings.add( - 'Your pubspec.yaml lists an executable "$executable" that ' - 'points to a script "$scriptPath" that does not exist.'); - })); - completer0.complete(); - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/license.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/license.dart deleted file mode 100644 index 944b58752b3..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/license.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.license; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../entrypoint.dart'; -import '../utils.dart'; -import '../validator.dart'; - -/// A validator that checks that a LICENSE-like file exists. -class LicenseValidator extends Validator { - LicenseValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - return new Future.sync(() { - var licenseLike = - new RegExp(r"^([a-zA-Z0-9]+[-_])?(LICENSE|COPYING)(\..*)?$"); - if (entrypoint.root.listFiles( - recursive: false).map(path.basename).any(licenseLike.hasMatch)) { - return; - } - - errors.add( - "You must have a COPYING or LICENSE file in the root directory.\n" - "An open-source license helps ensure people can legally use your " "code."); - }); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/name.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/name.dart deleted file mode 100644 index 8b558846e3f..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/name.dart +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.name; - -import 'dart:async'; - -import 'package:path/path.dart' as path; - -import '../entrypoint.dart'; -import '../utils.dart'; -import '../validator.dart'; - -/// Dart reserved words, from the Dart spec. -final _RESERVED_WORDS = [ - "assert", - "break", - "case", - "catch", - "class", - "const", - "continue", - "default", - "do", - "else", - "extends", - "false", - "final", - "finally", - "for", - "if", - "in", - "is", - "new", - "null", - "return", - "super", - "switch", - "this", - "throw", - "true", - "try", - "var", - "void", - "while", - "with"]; - -/// A validator that validates the name of the package and its libraries. -class NameValidator extends Validator { - NameValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - return new Future.sync(() { - _checkName( - entrypoint.root.name, - 'Package name "${entrypoint.root.name}"', - isPackage: true); - - var libraries = _libraries; - for (var library in libraries) { - var libName = path.basenameWithoutExtension(library); - _checkName( - libName, - 'The name of "$library", "$libName",', - isPackage: false); - } - - if (libraries.length == 1) { - var libName = path.basenameWithoutExtension(libraries[0]); - if (libName == entrypoint.root.name) return; - warnings.add( - 'The name of "${libraries[0]}", "$libName", should match ' - 'the name of the package, "${entrypoint.root.name}".\n' - 'This helps users know what library to import.'); - } - }); - } - - /// Returns a list of all libraries in the current package as paths relative - /// to the package's root directory. - List get _libraries { - var libDir = entrypoint.root.path("lib"); - return entrypoint.root.listFiles( - beneath: "lib").map( - (file) => - path.relative( - file, - from: path.dirname( - libDir))).where( - (file) => - !path.split(file).contains("src") && path.extension(file) == '.dart').toList(); - } - - void _checkName(String name, String description, {bool isPackage}) { - // Packages names are more stringent than libraries. - var messages = isPackage ? errors : warnings; - - if (name == "") { - errors.add("$description may not be empty."); - } else if (!new RegExp(r"^[a-zA-Z0-9_]*$").hasMatch(name)) { - messages.add( - "$description may only contain letters, numbers, and " "underscores.\n" - "Using a valid Dart identifier makes the name usable in Dart code."); - } else if (!new RegExp(r"^[a-zA-Z_]").hasMatch(name)) { - messages.add( - "$description must begin with a letter or underscore.\n" - "Using a valid Dart identifier makes the name usable in Dart code."); - } else if (_RESERVED_WORDS.contains(name.toLowerCase())) { - messages.add( - "$description may not be a reserved word in Dart.\n" - "Using a valid Dart identifier makes the name usable in Dart code."); - } else if (new RegExp(r"[A-Z]").hasMatch(name)) { - warnings.add( - '$description should be lower-case. Maybe use ' '"${_unCamelCase(name)}"?'); - } - } - - String _unCamelCase(String source) { - var builder = new StringBuffer(); - var lastMatchEnd = 0; - for (var match in new RegExp(r"[a-z]([A-Z])").allMatches(source)) { - builder - ..write(source.substring(lastMatchEnd, match.start + 1)) - ..write("_") - ..write(match.group(1).toLowerCase()); - lastMatchEnd = match.end; - } - builder.write(source.substring(lastMatchEnd)); - return builder.toString().toLowerCase(); - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/pubspec_field.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/pubspec_field.dart deleted file mode 100644 index d0f55b70cd3..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/pubspec_field.dart +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.pubspec_field; - -import 'dart:async'; - -import '../entrypoint.dart'; -import '../validator.dart'; - -/// A validator that checks that the pubspec has valid "author" and "homepage" -/// fields. -class PubspecFieldValidator extends Validator { - PubspecFieldValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - _validateAuthors(); - _validateFieldIsString('description'); - _validateFieldIsString('homepage'); - _validateFieldUrl('homepage'); - _validateFieldUrl('documentation'); - - // Any complex parsing errors in version will be exposed through - // [Pubspec.allErrors]. - _validateFieldIsString('version'); - - // Pubspec errors are detected lazily, so we make sure there aren't any - // here. - for (var error in entrypoint.root.pubspec.allErrors) { - errors.add('In your pubspec.yaml, ${error.message}'); - } - - return new Future.value(); - } - - /// Adds an error if the "author" or "authors" field doesn't exist or has the - /// wrong type. - void _validateAuthors() { - var pubspec = entrypoint.root.pubspec; - var author = pubspec.fields['author']; - var authors = pubspec.fields['authors']; - if (author == null && authors == null) { - errors.add('Your pubspec.yaml must have an "author" or "authors" field.'); - return; - } - - if (author != null && author is! String) { - errors.add( - 'Your pubspec.yaml\'s "author" field must be a string, but it ' - 'was "$author".'); - return; - } - - if (authors != null && - (authors is! List || authors.any((author) => author is! String))) { - errors.add( - 'Your pubspec.yaml\'s "authors" field must be a list, but ' - 'it was "$authors".'); - return; - } - - if (authors == null) authors = [author]; - - var hasName = new RegExp(r"^ *[^< ]"); - var hasEmail = new RegExp(r"<[^>]+> *$"); - for (var authorName in authors) { - if (!hasName.hasMatch(authorName)) { - warnings.add( - 'Author "$authorName" in pubspec.yaml should have a ' 'name.'); - } - if (!hasEmail.hasMatch(authorName)) { - warnings.add( - 'Author "$authorName" in pubspec.yaml should have an ' - 'email address\n(e.g. "name ").'); - } - } - } - - /// Adds an error if [field] doesn't exist or isn't a string. - void _validateFieldIsString(String field) { - var value = entrypoint.root.pubspec.fields[field]; - if (value == null) { - errors.add('Your pubspec.yaml is missing a "$field" field.'); - } else if (value is! String) { - errors.add( - 'Your pubspec.yaml\'s "$field" field must be a string, but ' - 'it was "$value".'); - } - } - - /// Adds an error if the URL for [field] is invalid. - void _validateFieldUrl(String field) { - var url = entrypoint.root.pubspec.fields[field]; - if (url == null) return; - - if (url is! String) { - errors.add( - 'Your pubspec.yaml\'s "$field" field must be a string, but ' 'it was "$url".'); - return; - } - - var goodScheme = new RegExp(r'^https?:'); - if (!goodScheme.hasMatch(url)) { - errors.add( - 'Your pubspec.yaml\'s "$field" field must be an "http:" or ' - '"https:" URL, but it was "$url".'); - } - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/sdk_constraint.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/sdk_constraint.dart deleted file mode 100644 index 0fe9ac87742..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/sdk_constraint.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.sdk_constraint; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; - -import '../entrypoint.dart'; -import '../log.dart' as log; -import '../package.dart'; -import '../validator.dart'; - -/// A validator that validates that a package's SDK constraint doesn't use the -/// "^" syntax. -class SdkConstraintValidator extends Validator { - SdkConstraintValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var constraint = entrypoint.root.pubspec.environment.sdkVersion; - join0() { - errors.add( - "^ version constraints aren't allowed for SDK constraints since " - "older versions of pub don't support them.\n" "Expand it manually instead:\n" - "\n" "environment:\n" " sdk: \">=${constraint.min} <${constraint.max}\""); - completer0.complete(); - } - if (!constraint.toString().startsWith("^")) { - completer0.complete(null); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; - } -} diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/size.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/size.dart deleted file mode 100644 index 129fea9f088..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/size.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.size; - -import 'dart:async'; -import 'dart:math' as math; - -import '../entrypoint.dart'; -import '../validator.dart'; - -/// The maximum size of the package to upload (10 MB). -const _MAX_SIZE = 10 * 1024 * 1024; - -/// A validator that validates that a package isn't too big. -class SizeValidator extends Validator { - final Future packageSize; - - SizeValidator(Entrypoint entrypoint, this.packageSize) - : super(entrypoint); - - Future validate() { - return packageSize.then((size) { - if (size <= _MAX_SIZE) return; - var sizeInMb = (size / math.pow(2, 20)).toStringAsPrecision(4); - errors.add( - "Your package is $sizeInMb MB. Hosted packages must be " "smaller than 10 MB."); - }); - } -} - diff --git a/sdk/lib/_internal/pub_generated/lib/src/validator/utf8_readme.dart b/sdk/lib/_internal/pub_generated/lib/src/validator/utf8_readme.dart deleted file mode 100644 index c3e2bf7617a..00000000000 --- a/sdk/lib/_internal/pub_generated/lib/src/validator/utf8_readme.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.validator.utf8_readme; - -import 'dart:async'; -import 'dart:convert'; - -import '../entrypoint.dart'; -import '../io.dart'; -import '../validator.dart'; - -/// Validates that a package's README is valid utf-8. -class Utf8ReadmeValidator extends Validator { - Utf8ReadmeValidator(Entrypoint entrypoint) - : super(entrypoint); - - Future validate() { - return new Future.sync(() { - var readme = entrypoint.root.readmePath; - if (readme == null) return; - var bytes = readBinaryFile(readme); - try { - // UTF8.decode doesn't allow invalid UTF-8. - UTF8.decode(bytes); - } on FormatException catch (_) { - warnings.add( - "$readme contains invalid UTF-8.\n" - "This will cause it to be displayed incorrectly on " "pub.dartlang.org."); - } - }); - } -} - diff --git a/sdk/lib/_internal/pub_generated/test/ascii_tree_test.dart b/sdk/lib/_internal/pub_generated/test/ascii_tree_test.dart deleted file mode 100644 index 04cf1f7fa44..00000000000 --- a/sdk/lib/_internal/pub_generated/test/ascii_tree_test.dart +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library lock_file_test; - -import 'package:unittest/unittest.dart'; - -import '../lib/src/ascii_tree.dart' as tree; -import '../lib/src/utils.dart'; - -main() { - runningAsTest = true; - - group('tree.fromFiles', () { - test('no files', () { - expect(tree.fromFiles([]), equals("")); - }); - - test('up to ten files in one directory are shown', () { - var files = [ - "dir/a.dart", - "dir/b.dart", - "dir/c.dart", - "dir/d.dart", - "dir/e.dart", - "dir/f.dart", - "dir/g.dart", - "dir/h.dart", - "dir/i.dart", - "dir/j.dart"]; - expect(tree.fromFiles(files), equals(""" -'-- dir - |-- a.dart - |-- b.dart - |-- c.dart - |-- d.dart - |-- e.dart - |-- f.dart - |-- g.dart - |-- h.dart - |-- i.dart - '-- j.dart -""")); - }); - - test('files are elided if there are more than ten', () { - var files = [ - "dir/a.dart", - "dir/b.dart", - "dir/c.dart", - "dir/d.dart", - "dir/e.dart", - "dir/f.dart", - "dir/g.dart", - "dir/h.dart", - "dir/i.dart", - "dir/j.dart", - "dir/k.dart"]; - expect(tree.fromFiles(files), equals(""" -'-- dir - |-- a.dart - |-- b.dart - |-- c.dart - | (5 more...) - |-- i.dart - |-- j.dart - '-- k.dart -""")); - }); - - test('files are not elided at the top level', () { - var files = [ - "a.dart", - "b.dart", - "c.dart", - "d.dart", - "e.dart", - "f.dart", - "g.dart", - "h.dart", - "i.dart", - "j.dart", - "k.dart"]; - expect(tree.fromFiles(files), equals(""" -|-- a.dart -|-- b.dart -|-- c.dart -|-- d.dart -|-- e.dart -|-- f.dart -|-- g.dart -|-- h.dart -|-- i.dart -|-- j.dart -'-- k.dart -""")); - }); - - test('a complex example', () { - var files = [ - "TODO", - "example/console_example.dart", - "example/main.dart", - "example/web copy/web_example.dart", - "test/absolute_test.dart", - "test/basename_test.dart", - "test/dirname_test.dart", - "test/extension_test.dart", - "test/is_absolute_test.dart", - "test/is_relative_test.dart", - "test/join_test.dart", - "test/normalize_test.dart", - "test/relative_test.dart", - "test/split_test.dart", - ".gitignore", - "README.md", - "lib/path.dart", - "pubspec.yaml", - "test/all_test.dart", - "test/path_posix_test.dart", - "test/path_windows_test.dart"]; - - expect(tree.fromFiles(files), equals(""" -|-- .gitignore -|-- README.md -|-- TODO -|-- example -| |-- console_example.dart -| |-- main.dart -| '-- web copy -| '-- web_example.dart -|-- lib -| '-- path.dart -|-- pubspec.yaml -'-- test - |-- absolute_test.dart - |-- all_test.dart - |-- basename_test.dart - | (7 more...) - |-- path_windows_test.dart - |-- relative_test.dart - '-- split_test.dart -""")); - }); - }); - - group('treeFromMap', () { - test('empty map', () { - expect(tree.fromMap({}), equals("")); - }); - - test('a complex example', () { - var map = { - ".gitignore": {}, - "README.md": {}, - "TODO": {}, - "example": { - "console_example.dart": {}, - "main.dart": {}, - "web copy": { - "web_example.dart": {} - }, - }, - "lib": { - "path.dart": {} - }, - "pubspec.yaml": {}, - "test": { - "absolute_test.dart": {}, - "basename_test.dart": {}, - "dirname_test.dart": {}, - "extension_test.dart": {}, - "is_absolute_test.dart": {}, - "is_relative_test.dart": {}, - "join_test.dart": {}, - "normalize_test.dart": {}, - "relative_test.dart": {}, - "split_test.dart": {} - } - }; - - expect(tree.fromMap(map), equals(""" -|-- .gitignore -|-- README.md -|-- TODO -|-- example -| |-- console_example.dart -| |-- main.dart -| '-- web copy -| '-- web_example.dart -|-- lib -| '-- path.dart -|-- pubspec.yaml -'-- test - |-- absolute_test.dart - |-- basename_test.dart - |-- dirname_test.dart - |-- extension_test.dart - |-- is_absolute_test.dart - |-- is_relative_test.dart - |-- join_test.dart - |-- normalize_test.dart - |-- relative_test.dart - '-- split_test.dart -""")); - }); - }); - - test('does not elide children if showAllChildren is true', () { - var map = { - 'dir': { - 'a.dart': {}, - 'b.dart': {}, - 'c.dart': {}, - 'd.dart': {}, - 'e.dart': {}, - 'f.dart': {}, - 'g.dart': {}, - 'h.dart': {}, - 'i.dart': {}, - 'j.dart': {}, - 'k.dart': {}, - 'l.dart': {}, - } - }; - expect(tree.fromMap(map, showAllChildren: true), equals(""" -'-- dir - |-- a.dart - |-- b.dart - |-- c.dart - |-- d.dart - |-- e.dart - |-- f.dart - |-- g.dart - |-- h.dart - |-- i.dart - |-- j.dart - |-- k.dart - '-- l.dart -""")); - }); - -} diff --git a/sdk/lib/_internal/pub_generated/test/async_compile_test.dart b/sdk/lib/_internal/pub_generated/test/async_compile_test.dart deleted file mode 100644 index 6c0af598344..00000000000 --- a/sdk/lib/_internal/pub_generated/test/async_compile_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/descriptor.dart' as d; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_process.dart'; - -import 'test_pub.dart'; -import '../lib/src/io.dart'; - -void main() { - integration("the generated pub source is up to date", () { - var compilerArgs = Platform.executableArguments.toList()..addAll( - [ - p.join(pubRoot, 'bin', 'async_compile.dart'), - '--force', - '--verbose', - p.join(sandboxDir, "pub_generated")]); - - new ScheduledProcess.start(Platform.executable, compilerArgs).shouldExit(0); - - new d.DirectoryDescriptor.fromFilesystem( - "pub_generated", - p.join(pubRoot, "..", "pub_generated")).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/all_includes_all_default_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/all_includes_all_default_directories_test.dart deleted file mode 100644 index 6fd966c49d1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/all_includes_all_default_directories_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../serve/utils.dart'; -import '../test_pub.dart'; - -main() { - initConfig(); - - setUp(() { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir('benchmark', [d.file('file.txt', 'benchmark')]), - d.dir('bin', [d.file('file.txt', 'bin')]), - d.dir('example', [d.file('file.txt', 'example')]), - d.dir('test', [d.file('file.txt', 'test')]), - d.dir('web', [d.file('file.txt', 'web')]), - d.dir('unknown', [d.file('file.txt', 'unknown')])]).create(); - }); - - integration("build --all finds assets in default source directories", () { - schedulePub( - args: ["build", "--all"], - output: new RegExp(r'Built 5 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir('benchmark', [d.file('file.txt', 'benchmark')]), - d.dir('bin', [d.file('file.txt', 'bin')]), - d.dir('example', [d.file('file.txt', 'example')]), - d.dir('test', [d.file('file.txt', 'test')]), - d.dir('web', [d.file('file.txt', 'web')]), - // Only includes default source directories. - d.nothing('unknown')])]).validate(); - }); - - integration("serve --all finds assets in default source directories", () { - pubServe(args: ["--all"]); - - requestShouldSucceed("file.txt", "benchmark", root: "benchmark"); - requestShouldSucceed("file.txt", "bin", root: "bin"); - requestShouldSucceed("file.txt", "example", root: "example"); - requestShouldSucceed("file.txt", "test", root: "test"); - requestShouldSucceed("file.txt", "web", root: "web"); - - expectNotServed("unknown"); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/directory_args_test.dart b/sdk/lib/_internal/pub_generated/test/barback/directory_args_test.dart deleted file mode 100644 index 44ecc9908ed..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/directory_args_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir('bar', [d.file('file.txt', 'bar')]), - d.dir('foo', [d.file('file.txt', 'foo')]), - d.dir('test', [d.file('file.txt', 'test')]), - d.dir('web', [d.file('file.txt', 'web')])]).create(); - }); - - integration("builds only the given directories", () { - schedulePub( - args: ["build", "foo", "bar"], - output: new RegExp(r'Built 2 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir('bar', [d.file('file.txt', 'bar')]), - d.dir('foo', [d.file('file.txt', 'foo')]), - d.nothing('test'), - d.nothing('web')])]).validate(); - }); - - integration("serves only the given directories", () { - pubServe(args: ["foo", "bar"]); - - requestShouldSucceed("file.txt", "bar", root: "bar"); - requestShouldSucceed("file.txt", "foo", root: "foo"); - expectNotServed("test"); - expectNotServed("web"); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_args_with_all_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_args_with_all_test.dart deleted file mode 100644 index 939b1227a91..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_args_with_all_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.appDir().create(); - }); - - pubBuildAndServeShouldFail( - "if a directory is passed with --all", - args: ["example", "--all"], - error: 'Directory names are not allowed if "--all" is passed.', - exitCode: exit_codes.USAGE); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_arg_does_not_exist_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_arg_does_not_exist_test.dart deleted file mode 100644 index 3e31c5acd8d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_arg_does_not_exist_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.dir( - appPath, - [d.appPubspec(), d.dir("bar", [d.file("file.txt", "contents")])]).create(); - }); - - pubBuildAndServeShouldFail( - "if a specified directory doesn't exist", - args: ["foo", "bar", "baz"], - error: 'Directories "foo" and "baz" do not exist.', - exitCode: exit_codes.DATA); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_outside_package_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_outside_package_test.dart deleted file mode 100644 index 840f7d411a3..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_dir_outside_package_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.appDir().create(); - }); - - pubBuildAndServeShouldFail( - "if source directory reaches outside the package", - args: [".."], - error: 'Directory ".." isn\'t in this package.', - exitCode: exit_codes.USAGE); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_if_no_default_dirs_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_if_no_default_dirs_test.dart deleted file mode 100644 index fb3e6072ec9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/fails_if_no_default_dirs_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.appDir().create(); - }); - - pubBuildAndServeShouldFail( - "if no directories were passed and no default " "ones exist", - args: [], - buildError: 'Your package must have a "web" directory,\n' - 'or you must specify the source directories.', - serveError: 'Your package must have "web" and/or "test" directories,\n' - 'or you must specify the source directories.', - exitCode: exit_codes.DATA); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_on_all_with_no_buildable_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_on_all_with_no_buildable_directories_test.dart deleted file mode 100644 index d88fc9647ec..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/fails_on_all_with_no_buildable_directories_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.appDir().create(); - }); - - pubBuildAndServeShouldFail( - "on --all with no default source directories", - args: ["--all"], - error: 'There are no source directories present.\n' - 'The default directories are "benchmark", "bin", "example", ' - '"test" and "web".', - exitCode: exit_codes.DATA); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_on_disallowed_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_on_disallowed_directories_test.dart deleted file mode 100644 index 507ac4d976d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/fails_on_disallowed_directories_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.appDir().create(); - }); - - var libSub = path.join("lib", "sub"); - pubBuildAndServeShouldFail( - "if given directories are not allowed", - args: [libSub, "lib"], - error: 'Directories "$libSub" and "lib" are not allowed.', - exitCode: exit_codes.USAGE); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/fails_on_overlapping_directories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/fails_on_overlapping_directories_test.dart deleted file mode 100644 index a66e87ec32e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/fails_on_overlapping_directories_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.dir( - "sub1", - [ - d.file("file.txt", "contents"), - d.dir("sub2", [d.file("file.txt", "contents")]), - d.dir("sub3", [d.file("file.txt", "contents")])])])]).create(); - }); - - var webSub1 = path.join("web", "sub1"); - var webSub1Sub2 = path.join("web", "sub1", "sub2"); - var webSub1Sub3 = path.join("web", "sub1", "sub3"); - - pubBuildAndServeShouldFail( - "if a superdirectory follows a subdirectory", - args: [webSub1Sub2, webSub1], - error: 'Directories "$webSub1Sub2" and "$webSub1" cannot overlap.', - exitCode: exit_codes.USAGE); - - pubBuildAndServeShouldFail( - "if a subdirectory follows a superdirectory", - args: [webSub1, webSub1Sub2], - error: 'Directories "$webSub1" and "$webSub1Sub2" cannot overlap.', - exitCode: exit_codes.USAGE); - - pubBuildAndServeShouldFail( - "if multiple directories overlap", - args: [webSub1, webSub1Sub2, webSub1Sub3], - error: 'Directories "$webSub1", "$webSub1Sub2" and "$webSub1Sub3" ' - 'cannot overlap.', - exitCode: exit_codes.USAGE); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/subdirectories_test.dart b/sdk/lib/_internal/pub_generated/test/barback/subdirectories_test.dart deleted file mode 100644 index 393030a256a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/subdirectories_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../serve/utils.dart'; -import '../test_pub.dart'; - -main() { - initConfig(); - - setUp(() { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.dir("one", [d.dir("inner", [d.file("file.txt", "one")])]), - d.dir("two", [d.dir("inner", [d.file("file.txt", "two")])]), - d.dir("nope", [d.dir("inner", [d.file("file.txt", "nope")])])])]).create(); - }); - - var webOne = p.join("web", "one"); - var webTwoInner = p.join("web", "two", "inner"); - - integration("builds subdirectories", () { - schedulePub( - args: ["build", webOne, webTwoInner], - output: new RegExp(r'Built 2 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - "build", - [ - d.dir( - "web", - [ - d.dir("one", [d.dir("inner", [d.file("file.txt", "one")])]), - d.dir("two", [d.dir("inner", [d.file("file.txt", "two")])]), - d.nothing("nope")])])]).validate(); - }); - - integration("serves subdirectories", () { - pubServe(args: [webOne, webTwoInner]); - - requestShouldSucceed("inner/file.txt", "one", root: webOne); - requestShouldSucceed("file.txt", "two", root: webTwoInner); - expectNotServed("web"); - expectNotServed(p.join("web", "three")); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/barback/utils.dart b/sdk/lib/_internal/pub_generated/test/barback/utils.dart deleted file mode 100644 index ebdfd426275..00000000000 --- a/sdk/lib/_internal/pub_generated/test/barback/utils.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../test_pub.dart'; - -/// Runs separate integration tests for "pub build", "pub serve", and -/// "pub build --format json" and validates that in all cases, it fails with -/// an expected error message and exits with [exitCode]. -/// -/// The integrations assume set up is already done, so you will likely want to -/// call [setUp] before this. -/// -/// If [error] is provided, then both pub build and pub serve should exit with -/// that message. Otherwise, [buildError] is the expected error from pub build -/// and [serveError] from pub serve. -void pubBuildAndServeShouldFail(String description, {List args, - String error, String buildError, String serveError, int exitCode}) { - - if (error != null) { - assert(buildError == null); - buildError = error; - - assert(serveError == null); - serveError = error; - } - - // Usage errors also print the usage, so validate that. - var buildExpectation = buildError; - var serveExpectation = serveError; - if (exitCode == exit_codes.USAGE) { - buildExpectation = - allOf(startsWith(buildExpectation), contains("Usage: pub build")); - serveExpectation = - allOf(startsWith(serveExpectation), contains("Usage: pub serve")); - } - - integration("build fails $description", () { - schedulePub( - args: ["build"]..addAll(args), - error: buildExpectation, - exitCode: exitCode); - }); - - integration("build --format json fails $description", () { - schedulePub(args: ["build", "--format", "json"]..addAll(args), outputJson: { - "error": buildError // No usage in JSON output. - }, exitCode: exitCode); - }); - - integration("serve fails $description", () { - schedulePub( - args: ["serve"]..addAll(args), - error: serveExpectation, - exitCode: exitCode); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/allows_arbitrary_modes_test.dart b/sdk/lib/_internal/pub_generated/test/build/allows_arbitrary_modes_test.dart deleted file mode 100644 index ef8fd723aa2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/allows_arbitrary_modes_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ModeTransformer extends Transformer { - final BarbackSettings settings; - ModeTransformer.asPlugin(this.settings); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return new Future.value().then((_) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, settings.mode.toString())); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows user-defined mode names", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - schedulePub(args: ["build", "--mode", "depeche"]); - - d.dir( - appPath, - [d.dir('build', [d.dir('web', [d.file('foo.out', 'depeche')])])]).validate(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/can_specify_output_directory_test.dart b/sdk/lib/_internal/pub_generated/test/build/can_specify_output_directory_test.dart deleted file mode 100644 index fac70030881..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/can_specify_output_directory_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("can specify the output directory to build into", () { - d.dir( - appPath, - [d.appPubspec(), d.dir('web', [d.file('file.txt', 'web')])]).create(); - - var outDir = path.join("out", "dir"); - schedulePub( - args: ["build", "-o", outDir], - output: contains('Built 1 file to "$outDir".')); - - d.dir( - appPath, - [ - d.dir( - "out", - [d.dir("dir", [d.dir("web", [d.file("file.txt", "web")]),])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/cleans_entire_build_directory_test.dart b/sdk/lib/_internal/pub_generated/test/build/cleans_entire_build_directory_test.dart deleted file mode 100644 index 6a2548b70c3..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/cleans_entire_build_directory_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration("cleans entire build directory before a build", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir('example', [d.file('file.txt', 'example')]), - d.dir('test', [d.file('file.txt', 'test')])]).create(); - - // Make a build directory containing "example". - schedulePub( - args: ["build", "example"], - output: new RegExp(r'Built 1 file to "build".')); - - // Now build again with just "test". Should wipe out "example". - schedulePub( - args: ["build", "test"], - output: new RegExp(r'Built 1 file to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.nothing('example'), - d.dir('test', [d.file('file.txt', 'test')]),])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_next_to_entrypoints_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_next_to_entrypoints_test.dart deleted file mode 100644 index d05ef15e7b4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_next_to_entrypoints_test.dart +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - - integration("compiles dart.js and interop.js next to entrypoints", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - serveBrowserPackage(); - - d.dir(appPath, [d.appPubspec({ - "browser": "1.0.0" - }), - d.dir( - 'foo', - [ - d.file('file.dart', 'void main() => print("hello");'), - d.dir( - 'subdir', - [d.file('subfile.dart', 'void main() => print("subhello");')])]), - d.dir( - 'web', - [ - d.file('file.dart', 'void main() => print("hello");'), - d.dir( - 'subweb', - [d.file('subfile.dart', 'void main() => print("subhello");')])])]).create(); - - pubGet(); - - schedulePub( - args: ["build", "foo", "web"], - output: new RegExp(r'Built 12 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'foo', - [ - d.matcherFile('file.dart.js', isNot(isEmpty)), - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])]), - d.dir( - 'subdir', - [ - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])]), - d.matcherFile('subfile.dart.js', isNot(isEmpty)),])]), - d.dir( - 'web', - [ - d.matcherFile('file.dart.js', isNot(isEmpty)), - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])]), - d.dir( - 'subweb', - [ - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])]), - d.matcherFile('subfile.dart.js', isNot(isEmpty))])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dependency_override_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dependency_override_test.dart deleted file mode 100644 index de98aaa2435..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dependency_override_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - // This is a regression test for http://dartbug.com/16617. - - initConfig(); - - integration( - "compiles dart.js and interop.js next to entrypoints when " - "browser is a dependency_override", - () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - serveBrowserPackage(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependency_overrides": { - "browser": "any" - } - }), - d.dir( - 'web', - [d.file('file.dart', 'void main() => print("hello");')])]).create(); - - pubGet(); - - schedulePub( - args: ["build", "--all"], - output: new RegExp(r'Built 3 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dev_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dev_dependency_test.dart deleted file mode 100644 index 26184aa4833..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/copies_browser_js_with_dev_dependency_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - // This is a regression test for http://dartbug.com/16617. - - initConfig(); - - integration( - "compiles dart.js and interop.js next to entrypoints when " - "browser is a dev dependency", - () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - serveBrowserPackage(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dev_dependencies": { - "browser": "any" - } - }), - d.dir( - 'web', - [d.file('file.dart', 'void main() => print("hello");')])]).create(); - - pubGet(); - - schedulePub( - args: ["build", "--all"], - output: new RegExp(r'Built 3 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/copies_non_dart_files_to_build_test.dart b/sdk/lib/_internal/pub_generated/test/build/copies_non_dart_files_to_build_test.dart deleted file mode 100644 index ab808b710e5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/copies_non_dart_files_to_build_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration("copies non-Dart files to build/", () { - servePackages((builder) => builder.serve("browser", "1.0.0")); - - d.dir( - appPath, - [// A browser dependency with no entrypoints shouldn't cause dart.js to be - // copied in. - d.appPubspec({ - "browser": "1.0.0" - }), - d.dir( - 'web', - [ - d.file('file.txt', 'contents'), - d.dir('subdir', [d.file('subfile.txt', 'subcontents')])])]).create(); - - schedulePub( - args: ["build"], - output: new RegExp(r'Built 2 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.nothing('packages'), - d.file('file.txt', 'contents'), - d.dir('subdir', [d.file('subfile.txt', 'subcontents')])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/defaults_to_release_mode_test.dart b/sdk/lib/_internal/pub_generated/test/build/defaults_to_release_mode_test.dart deleted file mode 100644 index 86e314633fc..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/defaults_to_release_mode_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ModeTransformer extends Transformer { - final BarbackSettings settings; - ModeTransformer.asPlugin(this.settings); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return new Future.value().then((_) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, settings.mode.toString())); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("defaults to release mode", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - schedulePub(args: ["build"]); - - d.dir( - appPath, - [d.dir('build', [d.dir('web', [d.file('foo.out', 'release')])])]).validate(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/handles_long_paths_test.dart b/sdk/lib/_internal/pub_generated/test/build/handles_long_paths_test.dart deleted file mode 100644 index 094938e9d4a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/handles_long_paths_test.dart +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import 'package:path/path.dart' as path; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - // This is a regression test for dartbug.com/14442. - // - // If you have a long chain of path dependencies with long relative paths, - // you can end up with a combined path that is longer than the OS can handle. - // For example, the path that revealed this bug was: - // - // C:\jenkins-slave\workspace\mSEE-Dev\ozone\dart\portfolio-manager\src\main\ - // portfolio-manager\..\..\..\..\portfolio-common\src\main\portfolio-common\ - // ../../../../dart-visualization/src/main/dart-visualization\lib\src\vega\ - // data\transform\visual - // - // This test ensures that we're normalizing at some point before we throw the - // path at the OS to choke on. - - integration("handles long relative paths", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - d.dir( - "some_long_dependency_name", - [ - d.libPubspec("foo", "0.0.1"), - d.dir("lib", [d.file("foo.txt", "foo")])]).create(); - - // Build a 2,800 character (non-canonicalized) path. - var longPath = ""; - for (var i = 0; i < 100; i++) { - longPath = path.join(longPath, "..", "some_long_dependency_name"); - } - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": longPath - } - }), d.dir("web", [d.file("index.html", "html"),])]).create(); - - schedulePub( - args: ["build"], - output: new RegExp(r'Built 2 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.file("index.html", "html"), - d.dir('packages', [d.dir('foo', [d.file('foo.txt', 'foo')])])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/includes_assets_from_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/build/includes_assets_from_dependencies_test.dart deleted file mode 100644 index d244e17e74c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/includes_assets_from_dependencies_test.dart +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration("includes assets from the 'lib' directory of dependencies", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - d.dir( - "foo", - [ - d.libPubspec("foo", "0.0.1"), - d.dir( - "lib", - [ - d.file("foo.txt", "foo"), - d.dir("sub", [d.file("bar.txt", "bar"),])])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), - d.dir("example", [d.file("index.html", "html"),]), - d.dir( - "web", - [ - d.file("index.html", "html"), - d.dir("sub", [d.file("index.html", "html")])])]).create(); - - schedulePub( - args: ["build", "--all"], - output: new RegExp(r'Built 7 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'example', - [ - d.file("index.html", "html"), - d.dir( - 'packages', - [ - d.dir( - 'foo', - [d.file('foo.txt', 'foo'), d.dir('sub', [d.file('bar.txt', 'bar'),]),])])]), - d.dir( - 'web', - [ - d.file("index.html", "html"), - d.dir( - 'packages', - [ - d.dir( - 'foo', - [d.file('foo.txt', 'foo'), d.dir('sub', [d.file('bar.txt', 'bar'),]),])]), - d.dir( - "sub", - [ - d.file("index.html", "html"), - // "packages" should *only* be created in the top-level directory. - d.nothing("packages")])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_from_dependencies_in_debug_test.dart b/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_from_dependencies_in_debug_test.dart deleted file mode 100644 index a1dff8ae3a6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_from_dependencies_in_debug_test.dart +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration("includes .dart files from dependencies in debug mode", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - d.dir( - "foo", - [ - d.libPubspec("foo", "0.0.1"), - d.dir( - "lib", - [ - d.file('foo.dart', 'foo() => print("hello");'), - d.dir("sub", [d.file('bar.dart', 'bar() => print("hello");'),])])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), - d.dir( - "example", - [ - d.file("main.dart", 'myapp() => print("not entrypoint");'), - d.dir( - "sub", - [d.file("main.dart", 'myapp() => print("not entrypoint");')])])]).create(); - - schedulePub( - args: ["build", "--mode", "debug", "example"], - output: new RegExp(r'Built \d+ files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'example', - [ - d.file("main.dart", 'myapp() => print("not entrypoint");'), - d.dir( - 'packages', - [ - d.dir( - 'foo', - [ - d.file('foo.dart', 'foo() => print("hello");'), - d.dir("sub", [d.file('bar.dart', 'bar() => print("hello");'),])])]), - d.dir( - "sub", - [ - d.file("main.dart", 'myapp() => print("not entrypoint");'), - // Does *not* copy packages into subdirectories. - d.nothing("packages")])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_in_debug_mode_test.dart b/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_in_debug_mode_test.dart deleted file mode 100644 index ac7a293c628..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/includes_dart_files_in_debug_mode_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration("includes Dart files in debug mode", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - 'web', - [ - d.file('file1.dart', 'var main = () => print("hello");'), - d.file('file2.dart', 'void main(arg1, arg2, arg3) => print("hello");'), - d.file('file3.dart', 'class Foo { void main() => print("hello"); }'), - d.file('file4.dart', 'var foo;')])]).create(); - - schedulePub( - args: ["build", "--mode", "debug"], - output: new RegExp(r'Built \d+ files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.nothing('file1.dart.js'), - d.matcherFile('file1.dart', isNot(isEmpty)), - d.nothing('file2.dart.js'), - d.matcherFile('file2.dart', isNot(isEmpty)), - d.nothing('file3.dart.js'), - d.matcherFile('file3.dart', isNot(isEmpty)), - d.nothing('file4.dart.js'), - d.matcherFile('file4.dart', isNot(isEmpty))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/outputs_error_to_json_test.dart b/sdk/lib/_internal/pub_generated/test/build/outputs_error_to_json_test.dart deleted file mode 100644 index 38f42bdba04..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/outputs_error_to_json_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) => throw new Exception('oh no!'); -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("outputs error to JSON in a failed build", () { - // Loading transformers takes several seconds, so make sure we don't - // timeout. - currentSchedule.timeout *= 2; - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), - d.dir("lib", [d.file("transformer.dart", TRANSFORMER)]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - schedulePub(args: ["build", "--format", "json"], outputJson: { - "buildResult": "failure", - "errors": [{ - "error": startsWith( - "Transform Rewrite on myapp|web/foo.txt " "threw error: oh no!") - }], - "log": [] - }, exitCode: exit_codes.DATA); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/outputs_results_to_json_test.dart b/sdk/lib/_internal/pub_generated/test/build/outputs_results_to_json_test.dart deleted file mode 100644 index 8eff17dad4c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/outputs_results_to_json_test.dart +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration("outputs results to JSON in a successful build", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - 'web', - [d.file('main.dart', 'void main() => print("hello");')])]).create(); - - schedulePub(args: ["build", "--format", "json"], outputJson: { - 'buildResult': 'success', - 'outputDirectory': 'build', - 'numFiles': 1, - 'log': [{ - 'level': 'Info', - 'transformer': { - 'name': 'Dart2JS', - 'primaryInput': { - 'package': 'myapp', - 'path': 'web/main.dart' - } - }, - 'assetId': { - 'package': 'myapp', - 'path': 'web/main.dart' - }, - 'message': 'Compiling myapp|web/main.dart...' - }, { - 'level': 'Info', - 'transformer': { - 'name': 'Dart2JS', - 'primaryInput': { - 'package': 'myapp', - 'path': 'web/main.dart' - } - }, - 'assetId': { - 'package': 'myapp', - 'path': 'web/main.dart' - }, - 'message': contains(r'to compile myapp|web/main.dart.') - }, { - 'level': 'Fine', - 'transformer': { - 'name': 'Dart2JS', - 'primaryInput': { - 'package': 'myapp', - 'path': 'web/main.dart' - } - }, - 'assetId': { - 'package': 'myapp', - 'path': 'web/main.dart' - }, - 'message': contains(r'Took') - }] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/preserves_htaccess_test.dart b/sdk/lib/_internal/pub_generated/test/build/preserves_htaccess_test.dart deleted file mode 100644 index 7453adfd7f0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/preserves_htaccess_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration("preserves .htaccess as a special case", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - 'web', - [d.file('.htaccess', 'fblthp'), d.file('.hidden', 'asdfgh')])]).create(); - - schedulePub( - args: ["build"], - output: new RegExp(r'Built \d+ files? to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [d.file('.htaccess', 'fblthp'), d.nothing('.hidden')])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/build/utils.dart b/sdk/lib/_internal/pub_generated/test/build/utils.dart deleted file mode 100644 index 6160c5eefe2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/build/utils.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -/// Runs the hosted test server and serves a valid "browser" package that -/// contains the same files (but not their contents) as the real browser -/// package. -void serveBrowserPackage() { - serve([d.dir('api', [d.dir('packages', [d.file('browser', JSON.encode({ - 'versions': [packageVersionApiMap(packageMap('browser', '1.0.0'))] - })), - d.dir( - 'browser', - [ - d.dir( - 'versions', - [ - d.file( - '1.0.0', - JSON.encode( - packageVersionApiMap(packageMap('browser', '1.0.0'), full: true)))])])])]), - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.dir( - 'versions', - [ - d.tar( - '1.0.0.tar.gz', - [ - d.file('pubspec.yaml', yaml(packageMap("browser", "1.0.0"))), - d.dir( - 'lib', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])])])])])]); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_matching_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_matching_version_test.dart deleted file mode 100644 index cea5e2ca791..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_matching_version_test.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'adds the latest version of the package matching the ' 'version constraint', - () { - servePackages((builder) { - builder.serve("foo", "1.2.2"); - builder.serve("foo", "1.2.3"); - builder.serve("foo", "2.0.0-dev"); - builder.serve("foo", "2.0.0"); - }); - - schedulePub( - args: ["cache", "add", "foo", "-v", ">=1.0.0 <2.0.0"], - output: 'Downloading foo 1.2.3...'); - - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - d.hostedCache( - [ - d.nothing("foo-1.2.2"), - d.nothing("foo-2.0.0-dev"), - d.nothing("foo-2.0.0")]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_version_test.dart deleted file mode 100644 index 8d27b956130..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/adds_latest_version_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('adds the latest stable version of the package', () { - servePackages((builder) { - builder.serve("foo", "1.2.2"); - builder.serve("foo", "1.2.3"); - builder.serve("foo", "1.2.4-dev"); - }); - - schedulePub( - args: ["cache", "add", "foo"], - output: 'Downloading foo 1.2.3...'); - - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/all_adds_all_matching_versions_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/all_adds_all_matching_versions_test.dart deleted file mode 100644 index 9d299369bd0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/all_adds_all_matching_versions_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('"--all" adds all matching versions of the package', () { - servePackages((builder) { - builder.serve("foo", "1.2.2"); - builder.serve("foo", "1.2.3-dev"); - builder.serve("foo", "1.2.3"); - builder.serve("foo", "2.0.0"); - }); - - schedulePub( - args: ["cache", "add", "foo", "-v", ">=1.0.0 <2.0.0", "--all"], - output: ''' - Downloading foo 1.2.2... - Downloading foo 1.2.3-dev... - Downloading foo 1.2.3...'''); - - d.cacheDir({ - "foo": "1.2.2" - }).validate(); - d.cacheDir({ - "foo": "1.2.3-dev" - }).validate(); - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/all_with_some_versions_present_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/all_with_some_versions_present_test.dart deleted file mode 100644 index bdfd5ebd586..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/all_with_some_versions_present_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('"--all" adds all non-installed versions of the package', () { - servePackages((builder) { - builder.serve("foo", "1.2.1"); - builder.serve("foo", "1.2.2"); - builder.serve("foo", "1.2.3"); - builder.serve("foo", "2.0.0"); - }); - - // Install a couple of versions first. - schedulePub( - args: ["cache", "add", "foo", "-v", "1.2.1"], - output: 'Downloading foo 1.2.1...'); - - schedulePub( - args: ["cache", "add", "foo", "-v", "1.2.3"], - output: 'Downloading foo 1.2.3...'); - - // They should show up as already installed now. - schedulePub(args: ["cache", "add", "foo", "--all"], output: ''' - Already cached foo 1.2.1. - Downloading foo 1.2.2... - Already cached foo 1.2.3. - Downloading foo 2.0.0...'''); - - d.cacheDir({ - "foo": "1.2.1" - }).validate(); - d.cacheDir({ - "foo": "1.2.2" - }).validate(); - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - d.cacheDir({ - "foo": "2.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/already_cached_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/already_cached_test.dart deleted file mode 100644 index dad15dafa2c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/already_cached_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('does nothing if the package is already cached', () { - servePackages((builder) { - builder.serve("foo", "1.2.3"); - }); - - // Run once to put it in the cache. - schedulePub( - args: ["cache", "add", "foo"], - output: 'Downloading foo 1.2.3...'); - - // Should be in the cache now. - schedulePub( - args: ["cache", "add", "foo"], - output: 'Already cached foo 1.2.3.'); - - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/bad_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/bad_version_test.dart deleted file mode 100644 index 322aefec5e9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/bad_version_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if the version constraint cannot be parsed', () { - schedulePub(args: ["cache", "add", "foo", "-v", "1.0"], error: """ - Could not parse version "1.0". Unknown text at "1.0". - - Usage: pub cache add [--version ] [--all] - -h, --help Print this usage information. - --all Install all matching versions. - -v, --version Version constraint. - - Run "pub help" to see global options. - See http://dartlang.org/tools/pub/cmd/pub-cache.html for detailed documentation. - """, exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/missing_package_arg_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/missing_package_arg_test.dart deleted file mode 100644 index d2a593d3b06..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/missing_package_arg_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if no package was given', () { - schedulePub(args: ["cache", "add"], error: """ - No package to add given. - - Usage: pub cache add [--version ] [--all] - -h, --help Print this usage information. - --all Install all matching versions. - -v, --version Version constraint. - - Run "pub help" to see global options. - See http://dartlang.org/tools/pub/cmd/pub-cache.html for detailed documentation. - """, exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/no_matching_version_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/no_matching_version_test.dart deleted file mode 100644 index dba517a00b7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/no_matching_version_test.dart +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if no version matches the version constraint', () { - servePackages((builder) { - builder.serve("foo", "1.2.2"); - builder.serve("foo", "1.2.3"); - }); - - schedulePub( - args: ["cache", "add", "foo", "-v", ">2.0.0"], - error: 'Package foo has no versions that match >2.0.0.', - exitCode: 1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/package_not_found_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/package_not_found_test.dart deleted file mode 100644 index 1a6b87b316f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/package_not_found_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if the package cound not be found on the source', () { - serveNoPackages(); - - schedulePub( - args: ["cache", "add", "foo"], - error: new RegExp(r"Could not find package foo at http://.*"), - exitCode: exit_codes.UNAVAILABLE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/add/unexpected_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/cache/add/unexpected_arguments_test.dart deleted file mode 100644 index add07de28e0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/add/unexpected_arguments_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if there are extra arguments', () { - schedulePub(args: ["cache", "add", "foo", "bar", "baz"], error: """ - Unexpected arguments "bar" and "baz". - - Usage: pub cache add [--version ] [--all] - -h, --help Print this usage information. - --all Install all matching versions. - -v, --version Version constraint. - - Run "pub help" to see global options. - See http://dartlang.org/tools/pub/cmd/pub-cache.html for detailed documentation. - """, exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/list_test.dart b/sdk/lib/_internal/pub_generated/test/cache/list_test.dart deleted file mode 100644 index b3e445931f4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/list_test.dart +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_cache_test; - -import 'package:path/path.dart' as path; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - hostedDir(package) { - return path.join( - sandboxDir, - cachePath, - "hosted", - "pub.dartlang.org", - package); - } - - integration('running pub cache list when there is no cache', () { - schedulePub(args: ['cache', 'list'], output: '{"packages":{}}'); - }); - - integration('running pub cache list on empty cache', () { - // Set up a cache. - d.dir( - cachePath, - [d.dir('hosted', [d.dir('pub.dartlang.org', [])])]).create(); - - schedulePub(args: ['cache', 'list'], outputJson: { - "packages": {} - }); - }); - - integration('running pub cache list', () { - // Set up a cache. - d.dir( - cachePath, - [ - d.dir( - 'hosted', - [ - d.dir( - 'pub.dartlang.org', - [ - d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3"), d.libDir("foo")]), - d.dir( - "bar-2.0.0", - [d.libPubspec("bar", "2.0.0"), d.libDir("bar")])])])]).create(); - - schedulePub(args: ['cache', 'list'], outputJson: { - "packages": { - "bar": { - "2.0.0": { - "location": hostedDir('bar-2.0.0') - } - }, - "foo": { - "1.2.3": { - "location": hostedDir('foo-1.2.3') - } - } - } - }); - }); - - integration('includes packages containing deps with bad sources', () { - // Set up a cache. - d.dir( - cachePath, - [ - d.dir( - 'hosted', - [ - d.dir( - 'pub.dartlang.org', - [d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3", deps: { - "bar": { - "bad": "bar" - } - }), d.libDir("foo")])])])]).create(); - - schedulePub(args: ['cache', 'list'], outputJson: { - "packages": { - "foo": { - "1.2.3": { - "location": hostedDir('foo-1.2.3') - } - } - } - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/empty_cache_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/empty_cache_test.dart deleted file mode 100644 index 3588ea1e824..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/empty_cache_test.dart +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('does nothing if the cache is empty', () { - // Repair them. - schedulePub( - args: ["cache", "repair"], - output: "No packages in cache, so nothing to repair."); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_binstub_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_binstub_test.dart deleted file mode 100644 index 51c4deb2227..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_binstub_test.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:io'; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('handles a corrupted binstub script', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [d.dir('bin', [d.file(binStubName('script'), 'junk')])]).create(); - - schedulePub( - args: ["cache", "repair"], - error: contains('Error reading binstub for "script":')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_global_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_global_lockfile_test.dart deleted file mode 100644 index 9839e648510..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_corrupted_global_lockfile_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('handles a corrupted global lockfile', () { - d.dir( - cachePath, - [d.dir('global_packages/foo', [d.file('pubspec.lock', 'junk')])]).create(); - - schedulePub( - args: ["cache", "repair"], - error: contains('Failed to reactivate foo:'), - output: contains('Failed to reactivate 1 package.')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_failure_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_failure_test.dart deleted file mode 100644 index 54f953a34a6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_failure_test.dart +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('handles failure to reinstall some packages', () { - // Only serve two packages so repairing will have a failure. - servePackages((builder) { - builder.serve("foo", "1.2.3"); - builder.serve("foo", "1.2.5"); - }); - - // Set up a cache with some packages. - d.dir( - cachePath, - [ - d.dir( - 'hosted', - [ - d.async( - port.then( - (p) => - d.dir( - 'localhost%58$p', - [ - d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3"), d.file("broken.txt")]), - d.dir("foo-1.2.4", [d.libPubspec("foo", "1.2.4"), d.file("broken.txt")]), - d.dir( - "foo-1.2.5", - [d.libPubspec("foo", "1.2.5"), d.file("broken.txt")])])))])]).create(); - - // Repair them. - var pub = startPub(args: ["cache", "repair"]); - - pub.stdout.expect("Downloading foo 1.2.3..."); - pub.stdout.expect("Downloading foo 1.2.4..."); - pub.stdout.expect("Downloading foo 1.2.5..."); - - pub.stderr.expect(startsWith("Failed to repair foo 1.2.4. Error:")); - pub.stderr.expect("HTTP error 404: Not Found"); - - pub.stdout.expect("Reinstalled 2 packages."); - pub.stdout.expect("Failed to reinstall 1 package."); - - pub.shouldExit(exit_codes.UNAVAILABLE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_orphaned_binstub_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/handles_orphaned_binstub_test.dart deleted file mode 100644 index 56f48ad2e63..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/handles_orphaned_binstub_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -const _ORPHANED_BINSTUB = """ -#!/usr/bin/env sh -# This file was created by pub v0.1.2-3. -# Package: foo -# Version: 1.0.0 -# Executable: foo-script -# Script: script -dart "/path/to/.pub-cache/global_packages/foo/bin/script.dart.snapshot" "\$@" -"""; - -main() { - initConfig(); - integration('handles an orphaned binstub script', () { - d.dir( - cachePath, - [d.dir('bin', [d.file(binStubName('script'), _ORPHANED_BINSTUB)])]).create(); - - schedulePub( - args: ["cache", "repair"], - error: allOf( - [ - contains('Binstubs exist for non-activated packages:'), - contains('From foo: foo-script')])); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/recompiles_snapshots_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/recompiles_snapshots_test.dart deleted file mode 100644 index bb8f6c8c75c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/recompiles_snapshots_test.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('recompiles activated executable snapshots', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages/foo/bin', - [d.file('script.dart.snapshot', 'junk')])]).create(); - - schedulePub(args: ["cache", "repair"], output: ''' - Downloading foo 1.0.0... - Reinstalled 1 package. - Reactivating foo 1.0.0... - Precompiling executables... - Loading source assets... - Precompiled foo:script. - Reactivated 1 package.'''); - - var pub = pubRun(global: true, args: ["foo:script"]); - pub.stdout.expect("ok"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_git_packages_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_git_packages_test.dart deleted file mode 100644 index a71e10dacae..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_git_packages_test.dart +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('reinstalls previously cached git packages', () { - // Create two cached revisions of foo. - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - pubGet(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.1')]).commit(); - - pubUpgrade(); - - // Break them. - var fooDirs; - schedule(() { - // Find the cached foo packages for each revision. - var gitCacheDir = path.join(sandboxDir, cachePath, "git"); - fooDirs = listDir( - gitCacheDir).where((dir) => path.basename(dir).startsWith("foo-")).toList(); - - // Delete "foo.dart" from them. - for (var dir in fooDirs) { - deleteEntry(path.join(dir, "lib", "foo.dart")); - } - }); - - // Repair them. - schedulePub(args: ["cache", "repair"], output: ''' - Resetting Git repository for foo 1.0.0... - Resetting Git repository for foo 1.0.1... - Reinstalled 2 packages.'''); - - // The missing libraries should have been replaced. - schedule(() { - var fooLibs = fooDirs.map((dir) { - var fooDirName = path.basename(dir); - return d.dir( - fooDirName, - [d.dir("lib", [d.file("foo.dart", 'main() => "foo";')])]); - }).toList(); - - d.dir(cachePath, [d.dir("git", fooLibs)]).validate(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_hosted_packages_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_hosted_packages_test.dart deleted file mode 100644 index ddac6dea7c6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/reinstalls_hosted_packages_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('reinstalls previously cached hosted packages', () { - servePackages((builder) { - builder.serve("foo", "1.2.3"); - builder.serve("foo", "1.2.4"); - builder.serve("foo", "1.2.5"); - builder.serve("bar", "1.2.3"); - builder.serve("bar", "1.2.4"); - }); - - // Set up a cache with some broken packages. - d.dir( - cachePath, - [ - d.dir( - 'hosted', - [ - d.async( - port.then( - (p) => - d.dir( - 'localhost%58$p', - [ - d.dir("foo-1.2.3", [d.libPubspec("foo", "1.2.3"), d.file("broken.txt")]), - d.dir("foo-1.2.5", [d.libPubspec("foo", "1.2.5"), d.file("broken.txt")]), - d.dir( - "bar-1.2.4", - [d.libPubspec("bar", "1.2.4"), d.file("broken.txt")])])))])]).create(); - - // Repair them. - schedulePub(args: ["cache", "repair"], output: ''' - Downloading bar 1.2.4... - Downloading foo 1.2.3... - Downloading foo 1.2.5... - Reinstalled 3 packages.'''); - - // The broken versions should have been replaced. - d.hostedCache( - [ - d.dir("bar-1.2.4", [d.nothing("broken.txt")]), - d.dir("foo-1.2.3", [d.nothing("broken.txt")]), - d.dir("foo-1.2.5", [d.nothing("broken.txt")])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/cache/repair/updates_binstubs_test.dart b/sdk/lib/_internal/pub_generated/test/cache/repair/updates_binstubs_test.dart deleted file mode 100644 index 874796e74a5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/cache/repair/updates_binstubs_test.dart +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -const _OUTDATED_BINSTUB = """ -#!/usr/bin/env sh -# This file was created by pub v0.1.2-3. -# Package: foo -# Version: 1.0.0 -# Executable: foo-script -# Script: script -dart "/path/to/.pub-cache/global_packages/foo/bin/script.dart.snapshot" "\$@" -"""; - -main() { - initConfig(); - integration('updates an outdated binstub script', () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "foo-script": "script" - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir('bin', [d.file(binStubName('foo-script'), _OUTDATED_BINSTUB)])]).create(); - - // Repair them. - schedulePub(args: ["cache", "repair"], output: ''' - Downloading foo 1.0.0... - Reinstalled 1 package. - Reactivating foo 1.0.0... - Precompiling executables... - Loading source assets... - Precompiled foo:script. - Installed executable foo-script. - Reactivated 1 package.'''); - - // The broken versions should have been replaced. - d.dir( - cachePath, - [d.dir('bin', [// 255 is the VM's exit code upon seeing an out-of-date snapshot. - d.matcherFile( - binStubName('foo-script'), - contains('255'))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/allows_import_in_dart_code_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/allows_import_in_dart_code_test.dart deleted file mode 100644 index 5f8cadcaeb7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/allows_import_in_dart_code_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("handles imports in the Dart code", () { - d.dir( - "foo", - [d.libPubspec("foo", "0.0.1"), d.dir("lib", [d.file("foo.dart", """ -library foo; -foo() => 'footext'; -""")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), d.dir("lib", [d.file("lib.dart", """ -library lib; -lib() => 'libtext'; -""")]), d.dir("web", [d.file("main.dart", """ -import 'package:foo/foo.dart'; -import 'package:myapp/lib.dart'; -void main() { - print(foo()); - print(lib()); -} -""")])]).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("main.dart.js", contains("footext")); - requestShouldSucceed("main.dart.js", contains("libtext")); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_entrypoints_in_root_package_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_entrypoints_in_root_package_test.dart deleted file mode 100644 index 6fb2e5e9c17..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_entrypoints_in_root_package_test.dart +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("compiles Dart entrypoints in root package to JS", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - 'benchmark', - [ - d.file('file.dart', 'void main() => print("hello");'), - d.file('lib.dart', 'void foo() => print("hello");'), - d.dir('subdir', [d.file('subfile.dart', 'void main() => print("ping");')])]), - d.dir( - 'foo', - [ - d.file('file.dart', 'void main() => print("hello");'), - d.file('lib.dart', 'void foo() => print("hello");'), - d.dir('subdir', [d.file('subfile.dart', 'void main() => print("ping");')])]), - d.dir( - 'web', - [ - d.file('file.dart', 'void main() => print("hello");'), - d.file('lib.dart', 'void foo() => print("hello");'), - d.dir( - 'subdir', - [d.file('subfile.dart', 'void main() => print("ping");')])])]).create(); - - schedulePub( - args: ["build", "benchmark", "foo", "web"], - output: new RegExp(r'Built 6 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'benchmark', - [ - d.matcherFile('file.dart.js', isNot(isEmpty)), - d.nothing('file.dart'), - d.nothing('lib.dart'), - d.dir( - 'subdir', - [ - d.matcherFile('subfile.dart.js', isNot(isEmpty)), - d.nothing('subfile.dart')])]), - d.dir( - 'foo', - [ - d.matcherFile('file.dart.js', isNot(isEmpty)), - d.nothing('file.dart'), - d.nothing('lib.dart'), - d.dir( - 'subdir', - [ - d.matcherFile('subfile.dart.js', isNot(isEmpty)), - d.nothing('subfile.dart')])]), - d.dir( - 'web', - [ - d.matcherFile('file.dart.js', isNot(isEmpty)), - d.nothing('file.dart'), - d.nothing('lib.dart'), - d.dir( - 'subdir', - [ - d.matcherFile('subfile.dart.js', isNot(isEmpty)), - d.nothing('subfile.dart')])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_dart_file_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_dart_file_test.dart deleted file mode 100644 index 0354e436ecc..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_dart_file_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("compiles a generated Dart file to JS", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "version": "0.0.1", - "transformers": ["myapp/transformer"] - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer("munge"))]), - d.dir("web", [d.file("main.dart", """ -const TOKEN = "before"; -void main() => print(TOKEN); -""")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("main.dart.js", contains("(before, munge)")); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_outside_web_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_outside_web_test.dart deleted file mode 100644 index 494e7adc490..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_outside_web_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - // This is a regression test for issue #17198. - initConfig(); - withBarbackVersions("any", () { - integration( - "compiles a Dart file that imports a generated file to JS " "outside web/", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "version": "0.0.1", - "transformers": ["myapp/transformer"] - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer("munge"))]), - d.dir("test", [d.file("main.dart", """ -import "other.dart"; -void main() => print(TOKEN); -"""), d.file("other.dart", """ -library other; -const TOKEN = "before"; -""")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(args: ["test"]); - requestShouldSucceed( - "main.dart.js", - contains("(before, munge)"), - root: "test"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_test.dart deleted file mode 100644 index 36416eca140..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_generated_file_from_dependency_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration( - "compiles a Dart file that imports a generated file in another " - "package to JS", - () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "0.0.1", - "transformers": ["foo/transformer"] - }), d.dir("lib", [d.file("foo.dart", """ -library foo; -const TOKEN = "before"; -foo() => TOKEN; -"""), d.file("transformer.dart", dartTransformer("munge"))])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), d.dir("web", [d.file("main.dart", """ -import "package:foo/foo.dart"; -main() => print(foo()); -""")])]).create(); - - createLockFile("myapp", sandbox: ["foo"], pkg: ["barback"]); - - pubServe(); - requestShouldSucceed("main.dart.js", contains("(before, munge)")); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_imported_generated_file_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/compiles_imported_generated_file_test.dart deleted file mode 100644 index d86c91ce66f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/compiles_imported_generated_file_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("compiles a Dart file that imports a generated file to JS", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "version": "0.0.1", - "transformers": ["myapp/transformer"] - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer("munge"))]), - d.dir("web", [d.file("main.dart", """ -import "other.dart"; -void main() => print(TOKEN); -"""), d.file("other.dart", """ -library other; -const TOKEN = "before"; -""")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("main.dart.js", contains("(before, munge)")); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/converts_isolate_entrypoint_in_web_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/converts_isolate_entrypoint_in_web_test.dart deleted file mode 100644 index 941add520ef..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/converts_isolate_entrypoint_in_web_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("converts a Dart isolate entrypoint in web to JS", () { - // Increase the timeout because dart2js takes a lot longer than usual to - // compile isolate entrypoints. - currentSchedule.timeout *= 2; - - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file( - "isolate.dart", - "void main(List args, SendPort " - "sendPort) => print('hello');")])]).create(); - - pubServe(); - requestShouldSucceed("isolate.dart.js", contains("hello")); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_if_disabled_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_if_disabled_test.dart deleted file mode 100644 index 6de1fdc1e02..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_if_disabled_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("does not compile if dart2js is disabled", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [d.file("main.dart", "void main() => print('hello');")])]).create(); - - pubServe(args: ["--no-dart2js"]); - requestShould404("main.dart.js"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_until_its_output_is_requested_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_until_its_output_is_requested_test.dart deleted file mode 100644 index 54dadb20130..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_compile_until_its_output_is_requested_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("does not compile until its output is requested", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "version": "0.0.1", - }), - d.dir("web", [d.file("syntax-error.dart", "syntax error")])]).create(); - - var server = pubServe(); - server.stdout.expect("Build completed successfully"); - - // Once we request the output, it should start compiling and fail. - requestShould404("syntax-error.dart.js"); - server.stdout.expect( - emitsLines( - "[Info from Dart2JS]:\n" "Compiling myapp|web/syntax-error.dart...")); - server.stdout.expect(consumeThrough("Build completed with 1 errors.")); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_command_line_options_type_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_command_line_options_type_test.dart deleted file mode 100644 index 0bcc3724cba..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_command_line_options_type_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("doesn't support invalid commandLineOptions type", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "commandLineOptions": "foo", - } - }] - }), d.dir("web", [d.file("main.dart", "void main() {}")])]).create(); - - var server = pubServe(); - // Make a request first to trigger compilation. - requestShould404("main.dart.js"); - server.stderr.expect( - emitsLines( - 'Build error:\n' 'Transform Dart2JS on myapp|web/main.dart threw error: ' - 'Invalid value for \$dart2js.commandLineOptions: ' - '"foo" (expected list of strings).')); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_environment_type_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_environment_type_test.dart deleted file mode 100644 index 7cb55fb7b69..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_environment_type_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("doesn't support invalid environment type", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "environment": "foo", - } - }] - }), d.dir("web", [d.file("main.dart", "void main() {}")])]).create(); - - var server = pubServe(); - // Make a request first to trigger compilation. - requestShould404("main.dart.js"); - server.stderr.expect( - emitsLines( - 'Build error:\n' 'Transform Dart2JS on myapp|web/main.dart threw error: ' - 'Invalid value for \$dart2js.environment: "foo" ' - '(expected map from strings to strings).')); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_option_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_option_test.dart deleted file mode 100644 index 6d3fb7e9204..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/does_not_support_invalid_option_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("doesn't support an invalid dart2js option", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "invalidOption": true - } - }] - })]).create(); - - // TODO(nweiz): This should provide more context about how the option got - // passed to dart2js. See issue 16008. - var pub = startPubServe(); - pub.stderr.expect('Unrecognized dart2js option "invalidOption".'); - pub.shouldExit(exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/doesnt_support_invalid_type_for_boolean_option_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/doesnt_support_invalid_type_for_boolean_option_test.dart deleted file mode 100644 index 61f5cc9c5a5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/doesnt_support_invalid_type_for_boolean_option_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("doesn't support invalid type for boolean option", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "checked": "foo", - } - }] - }), d.dir("web", [d.file("main.dart", "void main() {}")])]).create(); - - var server = pubServe(); - requestShould404("main.dart.js"); - server.stderr.expect( - emitsLines( - 'Build error:\n' 'Transform Dart2JS on myapp|web/main.dart threw error: ' - 'Invalid value for \$dart2js.checked: "foo" ' '(expected true or false).')); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoint_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoint_in_dependency_test.dart deleted file mode 100644 index 43ff0424845..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoint_in_dependency_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("ignores a Dart entrypoint in a dependency", () { - d.dir( - "foo", - [ - d.libPubspec("foo", "0.0.1"), - d.dir("lib", [d.file("lib.dart", "main() => print('foo');")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubServe(shouldGetFirst: true); - requestShould404("web/packages/foo/lib.dart.js"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoints_in_lib_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoints_in_lib_test.dart deleted file mode 100644 index 4c1a880826d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_entrypoints_in_lib_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - setUp(() { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir('lib', [d.file('file.dart', 'void main() => print("hello");'),]), - d.dir('web', [d.file('index.html', 'html'),])]).create(); - }); - - integration("build ignores Dart entrypoints in lib", () { - schedulePub( - args: ["build", "--all"], - output: new RegExp(r'Built 1 file to "build".')); - - d.dir(appPath, [d.dir('build', [d.nothing('lib')])]).validate(); - }); - - integration("serve ignores Dart entrypoints in lib", () { - pubServe(); - requestShould404("packages/myapp/main.dart.js"); - endPubServe(); - }); - -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_non_entrypoint_dart_files_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/ignores_non_entrypoint_dart_files_test.dart deleted file mode 100644 index bf2bdb9c5c1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/ignores_non_entrypoint_dart_files_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - setUp(() { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - 'web', - [ - d.file('file1.dart', 'var main = () => print("hello");'), - d.file('file2.dart', 'void main(arg1, arg2, arg3) => print("hello");'), - d.file('file3.dart', 'class Foo { void main() => print("hello"); }'), - d.file('file4.dart', 'var foo;')])]).create(); - }); - - integration("build ignores non-entrypoint Dart files", () { - schedulePub( - args: ["build"], - output: new RegExp(r'Built 0 files to "build".')); - - d.dir(appPath, [d.dir('build', [d.nothing('web')])]).validate(); - }); - - integration("serve ignores non-entrypoint Dart files", () { - pubServe(); - requestShould404("file1.dart.js"); - requestShould404("file2.dart.js"); - requestShould404("file3.dart.js"); - requestShould404("file4.dart.js"); - endPubServe(); - }); - -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_in_debug_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_in_debug_test.dart deleted file mode 100644 index 4e5d9e8d467..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/includes_source_maps_in_debug_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("includes source map URLs in a debug build", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [d.file("main.dart", "void main() => print('hello');")])]).create(); - - schedulePub( - args: ["build", "--mode", "debug"], - output: new RegExp(r'Built \d+ files to "build".'), - exitCode: 0); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.matcherFile('main.dart.js', contains("# sourceMappingURL=main.dart.js.map")), - d.matcherFile( - 'main.dart.js.map', - contains('"file": "main.dart.js"'))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/minifies_in_release_mode_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/minifies_in_release_mode_test.dart deleted file mode 100644 index 147c41fa432..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/minifies_in_release_mode_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("generates minified JS in release mode", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [d.file("main.dart", "void main() => print('hello');")])]).create(); - - pubServe(args: ["--mode", "release"]); - requestShouldSucceed("main.dart.js", isMinifiedDart2JSOutput); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/minify_configuration_overrides_mode_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/minify_configuration_overrides_mode_test.dart deleted file mode 100644 index eca9f08f3a1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/minify_configuration_overrides_mode_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("minify configuration overrides the mode", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "minify": true - } - }] - }), - d.dir( - "web", - [d.file("main.dart", "void main() => print('Hello!');")])]).create(); - - pubServe(); - requestShouldSucceed("main.dart.js", isMinifiedDart2JSOutput); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_in_release_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_in_release_test.dart deleted file mode 100644 index 248d2a2f21f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/omits_source_map_in_release_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("omits source maps from a release build", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [d.file("main.dart", "void main() => print('hello');")])]).create(); - - schedulePub( - args: ["build"], - output: new RegExp(r'Built 1 file to "build".'), - exitCode: 0); - - d.dir( - appPath, - [d.dir('build', [d.dir('web', [d.nothing('main.dart.js.map')])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/output_can_be_consumed_by_successive_phases.dart b/sdk/lib/_internal/pub_generated/test/dart2js/output_can_be_consumed_by_successive_phases.dart deleted file mode 100644 index 76953f60217..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/output_can_be_consumed_by_successive_phases.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -/// The code for a transformer that renames ".js" files to ".out". -const JS_REWRITE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.js'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, contents)); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("output can be consumed by successive phases", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["\$dart2js", "myapp/src/transformer"] - }), - d.dir( - "lib", - [d.dir("src", [d.file("transformer.dart", JS_REWRITE_TRANSFORMER)])]), - d.dir("web", [d.file("main.dart", "void main() {}")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("main.dart.out", isUnminifiedDart2JSOutput); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/outputs_deferred_libraries_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/outputs_deferred_libraries_test.dart deleted file mode 100644 index fc1ac701217..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/outputs_deferred_libraries_test.dart +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const MAIN = """ -import 'dart:async'; - -import 'a.dart' deferred as a; -import 'b.dart' deferred as b; - -void main() { - Future.wait([lazyA.loadLibrary(), lazyB.loadLibrary()]).then((_) { - a.fn(); - b.fn(); - }); -} -"""; - -const A = """ -library a; - -fn() => print("a"); -"""; - -const B = """ -library b; - -fn() => print("b"); -"""; - -main() { - initConfig(); - integration("compiles deferred libraries to separate outputs", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - 'web', - [ - d.file('main.dart', MAIN), - d.file('a.dart', A), - d.file('b.dart', B)])]).create(); - - schedulePub( - args: ["build"], - output: new RegExp(r'Built 3 files to "build".')); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.matcherFile('main.dart.js', isNot(isEmpty)), - d.matcherFile('main.dart.js_1.part.js', isNot(isEmpty)), - d.matcherFile('main.dart.js_2.part.js', isNot(isEmpty)),])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/passes_along_environment_constants_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/passes_along_environment_constants_test.dart deleted file mode 100644 index 5245f868ef1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/passes_along_environment_constants_test.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("passes along environment constants", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "environment": { - 'CONSTANT': 'true' - } - } - }] - }), d.dir("web", [d.file("main.dart", """ -void main() { - if (const bool.fromEnvironment('CONSTANT')) { - print("hello"); - } -} -""")])]).create(); - - pubServe(); - requestShouldSucceed("main.dart.js", contains("hello")); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/reports_dart_parse_errors_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/reports_dart_parse_errors_test.dart deleted file mode 100644 index 1c17de5fce6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/reports_dart_parse_errors_test.dart +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("reports Dart parse errors", () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - 'web', - [ - d.file('file.txt', 'contents'), - d.file('file.dart', 'void void;'), - d.dir('subdir', [d.file('subfile.dart', 'void void;')])])]).create(); - - var pub = startPub(args: ["build"]); - pub.stdout.expect(startsWith("Loading source assets...")); - pub.stdout.expect(startsWith("Building myapp...")); - - var consumeFile = consumeThrough( - inOrder( - ["[Error from Dart2JS]:", startsWith(p.join("web", "file.dart") + ":")])); - var consumeSubfile = consumeThrough( - inOrder( - [ - "[Error from Dart2JS]:", - startsWith(p.join("web", "subdir", "subfile.dart") + ":")])); - - // It's nondeterministic what order the dart2js transformers start running, - // so we allow the error messages to be emitted in either order. - pub.stderr.expect( - either( - inOrder([consumeFile, consumeSubfile]), - inOrder([consumeSubfile, consumeFile]))); - - pub.shouldExit(exit_codes.DATA); - - // Doesn't output anything if an error occurred. - d.dir(appPath, [d.dir('build', [d.nothing('web')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_in_subdirectory_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_in_subdirectory_test.dart deleted file mode 100644 index 3a040fbca7d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_in_subdirectory_test.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../serve/utils.dart'; -import '../test_pub.dart'; - -main() { - initConfig(); - - // This test is a bit shaky. Since dart2js is free to inline things, it's - // not precise as to which source libraries will actually be referenced in - // the source map. But this tries to use a type in the core library - // (StringBuffer) and validate that its source ends up in the source map. - integration( - "Dart core libraries are available to source maps when the " - "build directory is a subdirectory", - () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.dir( - "sub", - [ - d.file( - "main.dart", - "main() => new StringBuffer().writeAll(['s']);")])])]).create(); - - var webSub = path.join("web", "sub"); - pubServe(args: [webSub]); - - requestShouldSucceed( - "main.dart.js.map", - contains(r"packages/$sdk/lib/core/string_buffer.dart"), - root: webSub); - requestShouldSucceed( - r"packages/$sdk/lib/core/string_buffer.dart", - contains("class StringBuffer"), - root: webSub); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_test.dart deleted file mode 100644 index 6e0647f669d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/source_maps_include_core_libs_test.dart +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - // This test is a bit shaky. Since dart2js is free to inline things, it's - // not precise as to which source libraries will actually be referenced in - // the source map. But this tries to use a type in the core library - // (StringBuffer) and validate that its source ends up in the source map. - integration("Dart core libraries are available to source maps", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file("main.dart", "main() => new StringBuffer().writeAll(['s']);"), - d.dir( - "sub", - [ - d.file( - "main.dart", - "main() => new StringBuffer().writeAll(['s']);")])])]).create(); - - schedulePub( - args: ["build", "--mode", "debug"], - output: new RegExp(r'Built \d+ files to "build".'), - exitCode: 0); - - d.dir( - appPath, - [ - d.dir( - "build", - [ - d.dir( - "web", - [ - d.matcherFile( - "main.dart.js.map", - contains(r"packages/$sdk/lib/core/string_buffer.dart")), - d.dir( - "sub", - [ - d.matcherFile( - "main.dart.js.map", - contains(r"../packages/$sdk/lib/core/string_buffer.dart"))]), - d.dir( - "packages", - [ - d.dir( - r"$sdk", - [ - d.dir( - "lib", - [ - d.dir( - r"core", - [ - d.matcherFile( - "string_buffer.dart", - contains("class StringBuffer"))])])])])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/supports_configuration_with_build_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/supports_configuration_with_build_test.dart deleted file mode 100644 index 1c464125c41..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/supports_configuration_with_build_test.dart +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "compiles dart.js and interop.js next to entrypoints when " - "dartjs is explicitly configured", - () { - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 3; - - serve([d.dir('api', [d.dir('packages', [d.file('browser', JSON.encode({ - 'versions': [packageVersionApiMap(packageMap('browser', '1.0.0'))] - })), - d.dir( - 'browser', - [ - d.dir( - 'versions', - [ - d.file( - '1.0.0', - JSON.encode( - packageVersionApiMap(packageMap('browser', '1.0.0'), full: true)))])])])]), - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.dir( - 'versions', - [ - d.tar( - '1.0.0.tar.gz', - [ - d.file('pubspec.yaml', yaml(packageMap("browser", "1.0.0"))), - d.dir( - 'lib', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])])])])])]); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "browser": "1.0.0" - }, - "transformers": [{ - "\$dart2js": { - "minify": true - } - }] - }), - d.dir( - 'web', - [d.file('file.dart', 'void main() => print("hello");'),])]).create(); - - pubGet(); - - schedulePub( - args: ["build"], - output: new RegExp(r'Built 3 files to "build".'), - exitCode: 0); - - d.dir( - appPath, - [ - d.dir( - 'build', - [ - d.dir( - 'web', - [ - d.matcherFile('file.dart.js', isMinifiedDart2JSOutput), - d.dir( - 'packages', - [ - d.dir( - 'browser', - [ - d.file('dart.js', 'contents of dart.js'), - d.file('interop.js', 'contents of interop.js')])]),])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/supports_valid_options_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/supports_valid_options_test.dart deleted file mode 100644 index 07afaa9afdb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/supports_valid_options_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("supports most dart2js command-line options", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "commandLineOptions": ["--enable-diagnostic-colors"], - "checked": true, - "csp": true, - "minify": true, - "verbose": true, - "environment": { - "name": "value" - }, - "suppressWarnings": true, - "suppressHints": true, - "suppressPackageWarnings": false, - "terse": true - } - }] - }), - d.dir( - "web", - [d.file("main.dart", "void main() => print('Hello!');")])]).create(); - - // None of these options should be rejected, either by pub or by dart2js. - pubServe(); - requestShouldSucceed("main.dart.js", isNot(isEmpty)); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dart2js/unminified_in_nonrelease_mode_test.dart b/sdk/lib/_internal/pub_generated/test/dart2js/unminified_in_nonrelease_mode_test.dart deleted file mode 100644 index e31219306a7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dart2js/unminified_in_nonrelease_mode_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - integration("generates unminified JS when not in release mode", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [d.file("main.dart", "void main() => print('hello');")])]).create(); - - pubServe(args: ["--mode", "whatever"]); - requestShouldSucceed("main.dart.js", isUnminifiedDart2JSOutput); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/conservative_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/conservative_dependencies_test.dart deleted file mode 100644 index 2e8cca00c0a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/conservative_dependencies_test.dart +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -void main() { - initConfig(); - - integration( - "reports previous transformers as dependencies if the " - "transformer is transformed", - () { - // The root app just exists so that something is transformed by pkg and qux. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "version": "1.0.0", - "dependencies": { - "pkg": { - "path": "../pkg" - }, - "qux": { - "path": "../qux" - } - }, - "transformers": ["pkg", "qux"] - })]).create(); - - d.dir("pkg", [d.pubspec({ - "name": "pkg", - "version": "1.0.0", - "dependencies": { - "foo": { - "path": "../foo" - }, - "bar": { - "path": "../bar" - }, - "baz": { - "path": "../baz" - }, - }, - "transformers": [{ - "foo": { - "\$include": "lib/pkg.dart" - } - }, { - "bar": { - "\$exclude": "lib/transformer.dart" - } - }, "baz"] - }), - d.dir( - "lib", - [d.file("pkg.dart", ""), d.file("transformer.dart", transformer())])]).create(); - - // Even though foo and bar don't modify pkg/lib/transformer.dart themselves, - // it may be modified to import a library that they modify or generate, so - // pkg will depend on them. - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - d.dir( - "bar", - [ - d.libPubspec("bar", "1.0.0"), - d.dir("lib", [d.file("bar.dart", transformer())])]).create(); - - // baz transforms pkg/lib/transformer.dart, so pkg will obviously - // depend on it. - d.dir( - "baz", - [ - d.libPubspec("baz", "1.0.0"), - d.dir("lib", [d.file("baz.dart", transformer())])]).create(); - - // qux doesn't transform anything in pkg, so pkg won't depend on it. - d.dir( - "qux", - [ - d.libPubspec("qux", "1.0.0"), - d.dir("lib", [d.file("qux.dart", transformer())])]).create(); - - expectDependencies({ - 'pkg': ['foo', 'bar', 'baz'], - 'foo': [], - 'bar': [], - 'baz': [], - 'qux': [] - }); - }); - - integration( - "reports all transitive package dependencies' transformers as " - "dependencies if the transformer is transformed", - () { - // The root app just exists so that something is transformed by pkg and qux. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "pkg": { - "path": "../pkg" - }, - "qux": { - "path": "../qux" - } - }, - "transformers": ["pkg"] - })]).create(); - - d.dir("pkg", [d.pubspec({ - "name": "pkg", - "version": "1.0.0", - "dependencies": { - "foo": { - "path": "../foo" - }, - "baz": { - "path": "../baz" - } - }, - "transformers": ["baz"] - }), d.dir("lib", [d.file("pkg.dart", transformer())])]).create(); - - // pkg depends on foo. Even though it's not transformed by foo, its - // transformed transformer could import foo, so it has to depend on foo. - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "dependencies": { - "bar": { - "path": "../bar" - } - }, - "transformers": ["foo"] - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - // foo depends on bar, and like pkg's dependency on foo, the transformed - // version of foo's transformer could import bar, so foo has to depend on - // bar. - d.dir("bar", [d.pubspec({ - "name": "bar", - "version": "1.0.0", - "transformers": ["bar"] - }), d.dir("lib", [d.file("bar.dart", transformer())])]).create(); - - /// foo is transformed by baz. - d.dir( - "baz", - [ - d.libPubspec("baz", "1.0.0"), - d.dir("lib", [d.file("baz.dart", transformer())])]).create(); - - /// qux is not part of pkg's transitive dependency tree, so pkg shouldn't - /// depend on it. - d.dir("qux", [d.pubspec({ - "name": "qux", - "version": "1.0.0", - "transformers": ["qux"] - }), d.dir("lib", [d.file("qux.dart", transformer())])]).create(); - - expectDependencies({ - 'pkg': ['foo', 'bar', 'baz'], - 'foo': [], - 'bar': [], - 'baz': [], - 'qux': [] - }); - }); - - integration( - "reports previous transformers as dependencies if a " - "nonexistent local file is imported", - () { - // The root app just exists so that something is transformed by pkg and bar. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "pkg": { - "path": "../pkg" - }, - "bar": { - "path": "../bar" - } - }, - "transformers": ["pkg", "bar"] - })]).create(); - - d.dir("pkg", [d.pubspec({ - "name": "pkg", - "version": "1.0.0", - "dependencies": { - "foo": { - "path": "../foo" - }, - "bar": { - "path": "../bar" - } - }, - "transformers": [{ - "foo": { - "\$include": "lib/pkg.dart" - } - }] - }), - d.dir( - "lib", - [ - d.file("pkg.dart", ""), - d.file("transformer.dart", transformer(["nonexistent.dart"]))])]).create(); - - // Since pkg's transformer imports a nonexistent file, we assume that file - // was generated by foo's transformer. Thus pkg's transformer depends on - // foo's even though the latter doesn't transform the former. - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - /// qux is not part of pkg's transitive dependency tree, so pkg shouldn't - /// depend on it. - d.dir( - "bar", - [ - d.libPubspec("bar", "1.0.0"), - d.dir("lib", [d.file("bar.dart", transformer())])]).create(); - - expectDependencies({ - 'pkg': ['foo'], - 'foo': [], - 'bar': [] - }); - }); - - integration( - "reports all that package's dependencies' transformers as " - "dependencies if a non-existent file is imported from another package", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - }, - "qux": { - "path": "../qux" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file( - "myapp.dart", - transformer(["package:foo/nonexistent.dart"]))])]).create(); - - // myapp imported a nonexistent file from foo so myapp will depend on every - // transformer transitively reachable from foo, since the nonexistent file - // could be generated to import anything. - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "dependencies": { - "bar": { - "path": "../bar" - }, - "baz": { - "path": "../baz" - } - }, - "transformers": ["foo"] - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - // bar is a dependency of foo so myapp will depend on it. - d.dir("bar", [d.pubspec({ - "name": "bar", - "version": "1.0.0", - "transformers": ["bar"] - }), d.dir("lib", [d.file("bar.dart", transformer())])]).create(); - - // baz is a dependency of foo so myapp will depend on it. - d.dir("baz", [d.pubspec({ - "name": "baz", - "version": "1.0.0", - "transformers": ["baz"] - }), d.dir("lib", [d.file("baz.dart", transformer())])]).create(); - - // qux is not transitively reachable from foo so myapp won't depend on it. - d.dir("qux", [d.pubspec({ - "name": "qux", - "version": "1.0.0", - "transformers": ["qux"] - }), d.dir("lib", [d.file("qux.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['foo', 'bar', 'baz'], - 'foo': [], - 'bar': [], - 'baz': [], - 'qux': [] - }); - }); - - integration( - "reports all that package's dependencies' transformers as " - "dependencies if a non-existent transformer is used from another package", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - }, - "qux": { - "path": "../qux" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file( - "myapp.dart", - transformer(["package:foo/nonexistent.dart"]))])]).create(); - - // myapp imported a nonexistent file from foo so myapp will depend on every - // transformer transitively reachable from foo, since the nonexistent file - // could be generated to import anything. - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "dependencies": { - "bar": { - "path": "../bar" - }, - "baz": { - "path": "../baz" - } - }, - "transformers": ["bar"] - })]).create(); - - // bar is a dependency of foo so myapp will depend on it. - d.dir( - "bar", - [ - d.libPubspec("bar", "1.0.0"), - d.dir("lib", [d.file("bar.dart", transformer())])]).create(); - - // baz is a dependency of foo so myapp will depend on it. - d.dir("baz", [d.pubspec({ - "name": "baz", - "version": "1.0.0", - "transformers": ["baz"] - }), d.dir("lib", [d.file("baz.dart", transformer())])]).create(); - - // qux is not transitively reachable from foo so myapp won't depend on it. - d.dir("qux", [d.pubspec({ - "name": "qux", - "version": "1.0.0", - "transformers": ["qux"] - }), d.dir("lib", [d.file("qux.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['bar', 'baz'], - 'bar': [], - 'baz': [], - 'qux': [] - }); - }); - - test("reports dependencies on transformers in past phases", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/first", "myapp/second", "myapp/third"] - }), - d.dir( - "lib", - [ - d.file("first.dart", transformer()), - d.file("second.dart", transformer()), - d.file("third.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp/first': [], - 'myapp/second': ['myapp/first'], - 'myapp/third': ['myapp/second', 'myapp/first'] - }); - }); - - integration( - "considers the entrypoint package's dev and override " "dependencies", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "dev_dependencies": { - "bar": { - "path": "../bar" - } - }, - "dependency_overrides": { - "baz": { - "path": "../baz" - } - }, - "transformers": ["foo", "myapp"] - }), d.dir("lib", [d.file("myapp.dart", transformer())])]).create(); - - // foo transforms myapp's transformer so it could import from bar or baz. - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": ["foo"] - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - // bar is a dev dependency that myapp could import from, so myapp should - // depend on it. - d.dir("bar", [d.pubspec({ - "name": "bar", - "version": "1.0.0", - "transformers": ["bar"] - }), d.dir("lib", [d.file("bar.dart", transformer())])]).create(); - - // baz is an override dependency that myapp could import from, so myapp - // should depend on it. - d.dir("baz", [d.pubspec({ - "name": "baz", - "version": "1.0.0", - "transformers": ["baz"] - }), d.dir("lib", [d.file("baz.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['foo', 'bar', 'baz'], - 'foo': [], - 'bar': [], - 'baz': [] - }); - }); - - integration( - "doesn't consider a non-entrypoint package's dev and override " "dependencies", - () { - // myapp just exists so that pkg isn't the entrypoint. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "pkg": { - "path": "../pkg" - } - } - })]).create(); - - d.dir("pkg", [d.pubspec({ - "name": "pkg", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "dev_dependencies": { - "bar": { - "path": "../bar" - } - }, - "dependency_overrides": { - "baz": { - "path": "../baz" - } - }, - "transformers": ["foo", "pkg"] - }), d.dir("lib", [d.file("pkg.dart", transformer())])]).create(); - - // foo transforms pkg's transformer so it could theoretcially import from - // bar or baz. However, since pkg isn't the entrypoint, it doesn't have - // access to them. - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": ["foo"] - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - // bar is a dev dependency that myapp can't import from, so myapp shouldn't - // depend on it. - d.dir("bar", [d.pubspec({ - "name": "bar", - "version": "1.0.0", - "transformers": ["bar"] - }), d.dir("lib", [d.file("bar.dart", transformer())])]).create(); - - // baz is a dev dependency that myapp can't import from, so myapp shouldn't - // depend on it. - d.dir("baz", [d.pubspec({ - "name": "baz", - "version": "1.0.0", - "transformers": ["baz"] - }), d.dir("lib", [d.file("baz.dart", transformer())])]).create(); - - expectDependencies({ - 'pkg': ['foo'], - 'foo': [], - 'bar': [], - 'baz': [] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/cycle_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/cycle_test.dart deleted file mode 100644 index bfe4cb2402e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/cycle_test.dart +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -void main() { - initConfig(); - - integration( - "allows a package dependency cycle that's unrelated to " "transformers", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp/first", "myapp/second"] - }), - d.dir( - 'lib', - [ - d.file("first.dart", transformer()), - d.file("second.dart", transformer())])]).create(); - - d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: { - "bar": { - "path": "../bar" - } - })]).create(); - - d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: { - "baz": { - "path": "../baz" - } - })]).create(); - - d.dir("baz", [d.libPubspec("baz", "1.0.0", deps: { - "foo": { - "path": "../foo" - } - })]).create(); - - expectDependencies({ - 'myapp/first': [], - 'myapp/second': ['myapp/first'] - }); - }); - - integration( - "disallows a package dependency cycle that may be related to " "transformers", - () { - // Two layers of myapp transformers are necessary here because otherwise pub - // will figure out that the transformer doesn't import "foo" and thus - // doesn't transitively import itself. Import loops are tested below. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp/first", "myapp/second"] - }), - d.dir( - 'lib', - [ - d.file("first.dart", transformer()), - d.file("second.dart", transformer())])]).create(); - - d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: { - "bar": { - "path": "../bar" - } - })]).create(); - - d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: { - "myapp": { - "path": "../myapp" - } - })]).create(); - - expectCycleException( - [ - "myapp is transformed by myapp/second", - "myapp depends on foo", - "foo depends on bar", - "bar depends on myapp", - "myapp is transformed by myapp/first"]); - }); - - integration("disallows a transformation dependency cycle", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["foo"] - }), d.dir('lib', [d.file("myapp.dart", transformer())])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "dependencies": { - "bar": { - "path": "../bar" - } - }, - "transformers": ["bar"] - }), d.dir('lib', [d.file("foo.dart", transformer())])]).create(); - - d.dir("bar", [d.pubspec({ - "name": "bar", - "dependencies": { - "myapp": { - "path": "../myapp" - } - }, - "transformers": ["myapp"] - }), d.dir('lib', [d.file("bar.dart", transformer())])]).create(); - - expectCycleException( - [ - "bar is transformed by myapp", - "myapp is transformed by foo", - "foo is transformed by bar"]); - }); - - integration( - "allows a cross-package import cycle that's unrelated to " "transformers", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - 'lib', - [d.file("myapp.dart", transformer(['package:foo/foo.dart']))])]).create(); - - d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: { - "bar": { - "path": "../bar" - } - }), - d.dir('lib', [d.file("foo.dart", "import 'package:bar/bar.dart';")])]).create(); - - d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: { - "baz": { - "path": "../baz" - } - }), - d.dir('lib', [d.file("bar.dart", "import 'package:baz/baz.dart';")])]).create(); - - d.dir("baz", [d.libPubspec("baz", "1.0.0", deps: { - "foo": { - "path": "../foo" - } - }), - d.dir('lib', [d.file("baz.dart", "import 'package:foo/foo.dart';")])]).create(); - - expectDependencies({ - 'myapp': [] - }); - }); - - integration( - "disallows a cross-package import cycle that's related to " "transformers", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - 'lib', - [d.file("myapp.dart", transformer(['package:foo/foo.dart']))])]).create(); - - d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: { - "bar": { - "path": "../bar" - } - }), - d.dir('lib', [d.file("foo.dart", "import 'package:bar/bar.dart';")])]).create(); - - d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: { - "myapp": { - "path": "../myapp" - } - }), - d.dir( - 'lib', - [d.file("bar.dart", "import 'package:myapp/myapp.dart';")])]).create(); - - expectCycleException( - [ - "myapp is transformed by myapp", - "myapp depends on foo", - "foo depends on bar", - "bar depends on myapp"]); - }); - - integration( - "allows a single-package import cycle that's unrelated to " "transformers", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - 'lib', - [ - d.file("myapp.dart", transformer(['foo.dart'])), - d.file("foo.dart", "import 'bar.dart';"), - d.file("bar.dart", "import 'baz.dart';"), - d.file("baz.dart", "import 'foo.dart';")])]).create(); - - expectDependencies({ - 'myapp': [] - }); - }); - - integration( - "allows a single-package import cycle that's related to " "transformers", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - 'lib', - [ - d.file("myapp.dart", transformer(['foo.dart'])), - d.file("foo.dart", "import 'bar.dart';"), - d.file("bar.dart", "import 'myapp.dart';"),])]).create(); - - expectDependencies({ - 'myapp': [] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/dev_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/dev_transformers_test.dart deleted file mode 100644 index 853c406f96a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/dev_transformers_test.dart +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -void main() { - initConfig(); - - integration( - "doesn't return a dependency's transformer that can't run on lib", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - } - })]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo": { - "\$include": "test/foo_test.dart" - } - }] - }), - d.dir("lib", [d.file("foo.dart", transformer())]), - d.dir("test", [d.file("foo_test.dart", "")])]).create(); - - expectDependencies({}); - }); - - integration( - "does return the root package's transformer that can't run on " "lib", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp": { - "\$include": "test/myapp_test.dart" - } - }] - }), - d.dir("lib", [d.file("myapp.dart", transformer())]), - d.dir("test", [d.file("myapp_test.dart", "")])]).create(); - - expectDependencies({ - "myapp": [] - }); - }); - - integration( - "doesn't return a dependency's transformer that can run on bin", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - } - })]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo": { - "\$include": "bin/foo.dart" - } - }] - }), - d.dir("lib", [d.file("foo.dart", transformer())]), - d.dir("test", [d.file("foo_test.dart", "")])]).create(); - - expectDependencies({ - "foo": [] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/error_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/error_test.dart deleted file mode 100644 index 2670867e2e4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/error_test.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exceptions.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -void main() { - initConfig(); - - integration("fails if an unknown package is imported", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), - d.dir( - 'lib', - [d.file("myapp.dart", transformer(["package:foo/foo.dart"]))])]).create(); - - expectException(predicate((error) { - expect(error, new isInstanceOf()); - expect( - error.message, - equals( - 'A transformer imported unknown package "foo" (in ' - '"package:foo/foo.dart").')); - return true; - })); - }); - - integration("fails on a syntax error", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), d.dir('lib', [d.file("myapp.dart", "library;")])]).create(); - - expectException(new isInstanceOf()); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/import_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/import_dependencies_test.dart deleted file mode 100644 index 50ea1c9467c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/import_dependencies_test.dart +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -void main() { - initConfig(); - - integration( - "reports a dependency if a transformed local file is imported", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": [{ - "foo": { - "\$include": "lib/lib.dart" - } - }, "myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("lib.dart", ""), - d.file("transformer.dart", transformer(["lib.dart"]))])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0" - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['foo'], - 'foo': [] - }); - }); - - integration( - "reports a dependency if a transformed foreign file is imported", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("transformer.dart", transformer(["package:foo/foo.dart"]))])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo": { - "\$include": "lib/foo.dart" - } - }] - }), - d.dir( - "lib", - [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['foo'], - 'foo': [] - }); - }); - - integration( - "reports a dependency if a transformed external package file is " - "imported from an export", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("transformer.dart", transformer(["local.dart"])), - d.file("local.dart", "export 'package:foo/foo.dart';")])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo": { - "\$include": "lib/foo.dart" - } - }] - }), - d.dir( - "lib", - [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['foo'], - 'foo': [] - }); - }); - - integration( - "reports a dependency if a transformed foreign file is " - "transitively imported", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("transformer.dart", transformer(["local.dart"])), - d.file("local.dart", "import 'package:foo/foreign.dart';")])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo": { - "\$include": "lib/foo.dart" - } - }] - }), - d.dir( - "lib", - [ - d.file("foo.dart", ""), - d.file("transformer.dart", transformer()), - d.file("foreign.dart", "import 'foo.dart';")])]).create(); - - expectDependencies({ - 'myapp': ['foo'], - 'foo': [] - }); - }); - - integration( - "reports a dependency if a transformed foreign file is " - "transitively imported across packages", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("transformer.dart", transformer(["package:foo/foo.dart"])),])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "dependencies": { - "bar": { - "path": "../bar" - } - } - }), - d.dir("lib", [d.file("foo.dart", "import 'package:bar/bar.dart';")])]).create(); - - d.dir("bar", [d.pubspec({ - "name": "bar", - "version": "1.0.0", - "transformers": [{ - "bar": { - "\$include": "lib/bar.dart" - } - }] - }), - d.dir( - "lib", - [d.file("bar.dart", ""), d.file("transformer.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['bar'], - 'bar': [] - }); - }); - - integration( - "reports a dependency if an imported file is transformed by a " - "different package", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": [{ - "foo": { - '\$include': 'lib/local.dart' - } - }, "myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("transformer.dart", transformer(["local.dart"])), - d.file("local.dart", "")])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0" - }), d.dir("lib", [d.file("transformer.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': ['foo'], - 'foo': [] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/no_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/no_dependencies_test.dart deleted file mode 100644 index 7aeb6ee7040..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/no_dependencies_test.dart +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -void main() { - initConfig(); - - integration("reports no dependencies if no transformers are used", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - } - })]).create(); - - d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create(); - - expectDependencies({}); - }); - - integration( - "reports no dependencies if a transformer is used in a " - "package that doesn't expose a transformer", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["foo"] - })]).create(); - - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - expectDependencies({ - "foo": [] - }); - }); - - integration("reports no dependencies for non-file/package imports", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file( - "myapp.dart", - transformer( - ["dart:async", "http://dartlang.org/nonexistent.dart"]))])]).create(); - - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - expectDependencies({ - "myapp": [] - }); - }); - - integration("reports no dependencies for a single self transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), d.dir("lib", [d.file("myapp.dart", transformer())])]).create(); - - expectDependencies({ - "myapp": [] - }); - }); - - integration( - "reports no dependencies if a transformer applies to files that " - "aren't used by the exposed transformer", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": [{ - "foo": { - "\$include": "lib/myapp.dart" - } - }, { - "foo": { - "\$exclude": "lib/transformer.dart" - } - }, "myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("transformer.dart", transformer())])]).create(); - - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - expectDependencies({ - "myapp": [], - "foo": [] - }); - }); - - integration( - "reports no dependencies if a transformer applies to a " - "dependency's files that aren't used by the exposed transformer", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("transformer.dart", transformer(["package:foo/foo.dart"]))])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo": { - "\$exclude": "lib/foo.dart" - } - }] - }), - d.dir( - "lib", - [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp': [], - 'foo': [] - }); - }); - - test("reports no dependencies on transformers in future phases", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/first": { - "\$include": "lib/myapp.dart" - } - }, { - "myapp/second": { - "\$include": "lib/first.dart" - } - }, { - "myapp/third": { - "\$include": "lib/second.dart" - } - }] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.file("first.dart", transformer()), - d.file("second.dart", transformer()), - d.file("third.dart", transformer())])]).create(); - - expectDependencies({ - 'myapp/first': [], - 'myapp/second': [], - 'myapp/third': [] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/transformers_needed_by_library_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/transformers_needed_by_library_test.dart deleted file mode 100644 index 1f27f68ae44..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/transformers_needed_by_library_test.dart +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -void main() { - initConfig(); - - integration("reports a dependency if the library itself is transformed", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": [{ - "foo": { - "\$include": "bin/myapp.dart.dart" - } - }] - }), - d.dir( - "bin", - [d.file("myapp.dart", "import 'package:myapp/lib.dart';"),])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0" - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - expectLibraryDependencies('myapp|bin/myapp.dart', ['foo']); - }); - - integration( - "reports a dependency if a transformed local file is imported", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": [{ - "foo": { - "\$include": "lib/lib.dart" - } - }] - }), - d.dir("lib", [d.file("lib.dart", ""),]), - d.dir( - "bin", - [d.file("myapp.dart", "import 'package:myapp/lib.dart';"),])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0" - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - expectLibraryDependencies('myapp|bin/myapp.dart', ['foo']); - }); - - integration( - "reports a dependency if a transformed foreign file is imported", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - }), - d.dir( - "bin", - [d.file("myapp.dart", "import 'package:foo/foo.dart';")])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo": { - "\$include": "lib/foo.dart" - } - }] - }), - d.dir( - "lib", - [d.file("foo.dart", ""), d.file("transformer.dart", transformer())])]).create(); - - expectLibraryDependencies('myapp|bin/myapp.dart', ['foo']); - }); - - integration( - "doesn't report a dependency if no transformed files are " "imported", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": [{ - "foo": { - "\$include": "lib/lib.dart" - } - }] - }), - d.dir("lib", [d.file("lib.dart", ""), d.file("untransformed.dart", ""),]), - d.dir( - "bin", - [ - d.file( - "myapp.dart", - "import 'package:myapp/untransformed.dart';"),])]).create(); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0" - }), d.dir("lib", [d.file("foo.dart", transformer())])]).create(); - - expectLibraryDependencies('myapp|bin/myapp.dart', []); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_computer/utils.dart b/sdk/lib/_internal/pub_generated/test/dependency_computer/utils.dart deleted file mode 100644 index 33b1bf76431..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_computer/utils.dart +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/barback/cycle_exception.dart'; -import '../../lib/src/barback/dependency_computer.dart'; -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/io.dart'; -import '../../lib/src/package.dart'; -import '../../lib/src/package_graph.dart'; -import '../../lib/src/source/path.dart'; -import '../../lib/src/system_cache.dart'; -import '../../lib/src/utils.dart'; -import '../test_pub.dart'; - -/// Expects that [DependencyComputer.transformersNeededByTransformers] will -/// return a graph matching [expected] when run on the package graph defined by -/// packages in the sandbox. -void expectDependencies(Map> expected) { - expected = mapMap(expected, value: (_, ids) => ids.toSet()); - - schedule(() { - var computer = new DependencyComputer(_loadPackageGraph()); - var result = mapMap( - computer.transformersNeededByTransformers(), - key: (id, _) => id.toString(), - value: (_, ids) => ids.map((id) => id.toString()).toSet()); - expect(result, equals(expected)); - }, "expect dependencies to match $expected"); -} - -/// Expects that [computeTransformersNeededByTransformers] will throw an -/// exception matching [matcher] when run on the package graph defiend by -/// packages in the sandbox. -void expectException(matcher) { - schedule(() { - expect(() { - var computer = new DependencyComputer(_loadPackageGraph()); - computer.transformersNeededByTransformers(); - }, throwsA(matcher)); - }, "expect an exception: $matcher"); -} - -/// Expects that [computeTransformersNeededByTransformers] will throw a -/// [CycleException] with the given [steps] when run on the package graph -/// defiend by packages in the sandbox. -void expectCycleException(Iterable steps) { - expectException(predicate((error) { - expect(error, new isInstanceOf()); - expect(error.steps, equals(steps)); - return true; - }, "cycle exception:\n${steps.map((step) => " $step").join("\n")}")); -} - -/// Expects that [DependencyComputer.transformersNeededByLibrary] will return -/// transformer ids matching [expected] when run on the library identified by -/// [id]. -void expectLibraryDependencies(String id, Iterable expected) { - expected = expected.toSet(); - - schedule(() { - var computer = new DependencyComputer(_loadPackageGraph()); - var result = computer.transformersNeededByLibrary( - new AssetId.parse(id)).map((id) => id.toString()).toSet(); - expect(result, equals(expected)); - }, "expect dependencies to match $expected"); -} - -/// Loads a [PackageGraph] from the packages in the sandbox. -/// -/// This graph will also include barback and its transitive dependencies from -/// the repo. -PackageGraph _loadPackageGraph() { - // Load the sandbox packages. - var packages = {}; - - var systemCache = new SystemCache(p.join(sandboxDir, cachePath)); - systemCache.sources - ..register(new PathSource()) - ..setDefault('path'); - var entrypoint = new Entrypoint(p.join(sandboxDir, appPath), systemCache); - - for (var package in listDir(sandboxDir)) { - if (!fileExists(p.join(package, 'pubspec.yaml'))) continue; - var packageName = p.basename(package); - packages[packageName] = - new Package.load(packageName, package, systemCache.sources); - } - - loadPackage(packageName) { - if (packages.containsKey(packageName)) return; - packages[packageName] = - new Package.load(packageName, packagePath(packageName), systemCache.sources); - for (var dep in packages[packageName].dependencies) { - loadPackage(dep.name); - } - } - - loadPackage('barback'); - - return new PackageGraph(entrypoint, null, packages); -} - -/// Returns the contents of a no-op transformer that imports each URL in -/// [imports]. -String transformer([Iterable imports]) { - if (imports == null) imports = []; - - var buffer = - new StringBuffer()..writeln('import "package:barback/barback.dart";'); - for (var import in imports) { - buffer.writeln('import "$import";'); - } - - buffer.writeln(""" -NoOpTransformer extends Transformer { - bool isPrimary(AssetId id) => true; - void apply(Transform transform) {} -} -"""); - - return buffer.toString(); -} diff --git a/sdk/lib/_internal/pub_generated/test/dependency_override_test.dart b/sdk/lib/_internal/pub_generated/test/dependency_override_test.dart deleted file mode 100644 index 51eef32407e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dependency_override_test.dart +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; - -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -main() { - initConfig(); - forBothPubGetAndUpgrade((command) { - integration("chooses best version matching override constraint", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "2.0.0"); - builder.serve("foo", "3.0.0"); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": ">2.0.0" - }, - "dependency_overrides": { - "foo": "<3.0.0" - } - })]).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": "2.0.0" - }).validate(); - }); - - integration("treats override as implicit dependency", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependency_overrides": { - "foo": "any" - } - })]).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": "1.0.0" - }).validate(); - }); - - integration("ignores other constraints on overridden package", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "2.0.0"); - builder.serve("foo", "3.0.0"); - builder.serve("bar", "1.0.0", pubspec: { - "dependencies": { - "foo": "5.0.0-nonexistent" - } - }); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "bar": "any" - }, - "dependency_overrides": { - "foo": "<3.0.0" - } - })]).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": "2.0.0", - "bar": "1.0.0" - }).validate(); - }); - - integration("warns about overridden dependencies", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("bar", "1.0.0"); - }); - - d.dir("baz", [d.libDir("baz"), d.libPubspec("baz", "0.0.1")]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependency_overrides": { - "foo": "any", - "bar": "any", - "baz": { - "path": "../baz" - } - } - })]).create(); - - var bazPath = path.join("..", "baz"); - - schedulePub(args: [command.name], output: command.success, error: """ - Warning: You are using these overridden dependencies: - ! bar 1.0.0 - ! baz 0.0.1 from path $bazPath - ! foo 1.0.0 - """); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/deps_test.dart b/sdk/lib/_internal/pub_generated/test/deps_test.dart deleted file mode 100644 index 20403c2c90e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/deps_test.dart +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -main() { - initConfig(); - - setUp(() { - servePackages((builder) { - builder.serve("normal", "1.2.3", deps: { - "transitive": "any", - "circular_a": "any" - }); - builder.serve("transitive", "1.2.3", deps: { - "shared": "any" - }); - builder.serve("shared", "1.2.3", deps: { - "other": "any" - }); - builder.serve("unittest", "1.2.3", deps: { - "shared": "any" - }); - builder.serve("other", "1.0.0"); - builder.serve("overridden", "1.0.0"); - builder.serve("overridden", "2.0.0"); - builder.serve("override_only", "1.2.3"); - builder.serve("circular_a", "1.2.3", deps: { - "circular_b": "any" - }); - builder.serve("circular_b", "1.2.3", deps: { - "circular_a": "any" - }); - }); - - d.dir( - "from_path", - [d.libDir("from_path"), d.libPubspec("from_path", "1.2.3")]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "normal": "any", - "overridden": "1.0.0", - "from_path": { - "path": "../from_path" - } - }, - "dev_dependencies": { - "unittest": "any" - }, - "dependency_overrides": { - "overridden": "2.0.0", - "override_only": "any" - } - })]).create(); - }); - - integration("lists dependencies in compact form", () { - pubGet(); - schedulePub(args: ['deps', '-s', 'compact'], output: ''' - myapp 0.0.0 - - dependencies: - - from_path 1.2.3 - - normal 1.2.3 [transitive circular_a] - - overridden 2.0.0 - - dev dependencies: - - unittest 1.2.3 [shared] - - dependency overrides: - - overridden 2.0.0 - - override_only 1.2.3 - - transitive dependencies: - - circular_a 1.2.3 [circular_b] - - circular_b 1.2.3 [circular_a] - - other 1.0.0 - - shared 1.2.3 [other] - - transitive 1.2.3 [shared] - '''); - }); - - integration("lists dependencies in list form", () { - pubGet(); - schedulePub(args: ['deps', '--style', 'list'], output: ''' - myapp 0.0.0 - - dependencies: - - from_path 1.2.3 - - normal 1.2.3 - - transitive any - - circular_a any - - overridden 2.0.0 - - dev dependencies: - - unittest 1.2.3 - - shared any - - dependency overrides: - - overridden 2.0.0 - - override_only 1.2.3 - - transitive dependencies: - - circular_a 1.2.3 - - circular_b any - - circular_b 1.2.3 - - circular_a any - - other 1.0.0 - - shared 1.2.3 - - other any - - transitive 1.2.3 - - shared any - '''); - }); - - integration("lists dependencies in tree form", () { - pubGet(); - schedulePub(args: ['deps'], output: ''' - myapp 0.0.0 - |-- from_path 1.2.3 - |-- normal 1.2.3 - | |-- circular_a 1.2.3 - | | '-- circular_b 1.2.3 - | | '-- circular_a... - | '-- transitive 1.2.3 - | '-- shared... - |-- overridden 2.0.0 - |-- override_only 1.2.3 - '-- unittest 1.2.3 - '-- shared 1.2.3 - '-- other 1.0.0 - '''); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/descriptor.dart b/sdk/lib/_internal/pub_generated/test/descriptor.dart deleted file mode 100644 index 18fa385d596..00000000000 --- a/sdk/lib/_internal/pub_generated/test/descriptor.dart +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Pub-specific scheduled_test descriptors. -library descriptor; - -import 'package:oauth2/oauth2.dart' as oauth2; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/descriptor.dart'; - -import '../lib/src/io.dart'; -import '../lib/src/utils.dart'; -import 'descriptor/git.dart'; -import 'descriptor/tar.dart'; -import 'test_pub.dart'; - -export 'package:scheduled_test/descriptor.dart'; -export 'descriptor/git.dart'; -export 'descriptor/tar.dart'; - -/// Creates a new [GitRepoDescriptor] with [name] and [contents]. -GitRepoDescriptor git(String name, [Iterable contents]) => - new GitRepoDescriptor(name, contents == null ? [] : contents); - -/// Creates a new [TarRepoDescriptor] with [name] and [contents]. -TarFileDescriptor tar(String name, [Iterable contents]) => - new TarFileDescriptor(name, contents == null ? [] : contents); - -/// Describes a package that passes all validation. -Descriptor get validPackage => - dir( - appPath, - [ - libPubspec("test_pkg", "1.0.0"), - file("LICENSE", "Eh, do what you want."), - dir("lib", [file("test_pkg.dart", "int i = 1;")])]); - -/// Returns a descriptor of a snapshot that can't be run by the current VM. -/// -/// This snapshot was generated by the VM on r39611, the revision immediately -/// before snapshot versioning was added. -FileDescriptor outOfDateSnapshot(String name) => - binaryFile(name, readBinaryFile(testAssetPath('out-of-date.snapshot'))); - -/// Describes a file named `pubspec.yaml` with the given YAML-serialized -/// [contents], which should be a serializable object. -/// -/// [contents] may contain [Future]s that resolve to serializable objects, -/// which may in turn contain [Future]s recursively. -Descriptor pubspec(Map contents) { - return async( - awaitObject( - contents).then( - (resolvedContents) => file("pubspec.yaml", yaml(resolvedContents)))); -} - -/// Describes a file named `pubspec.yaml` for an application package with the -/// given [dependencies]. -Descriptor appPubspec([Map dependencies]) { - var map = { - "name": "myapp" - }; - if (dependencies != null) map["dependencies"] = dependencies; - return pubspec(map); -} - -/// Describes a file named `pubspec.yaml` for a library package with the given -/// [name], [version], and [deps]. If "sdk" is given, then it adds an SDK -/// constraint on that version. -Descriptor libPubspec(String name, String version, {Map deps, String sdk}) { - var map = packageMap(name, version, deps); - if (sdk != null) map["environment"] = { - "sdk": sdk - }; - return pubspec(map); -} - -/// Describes a directory named `lib` containing a single dart file named -/// `.dart` that contains a line of Dart code. -Descriptor libDir(String name, [String code]) { - // Default to printing the name if no other code was given. - if (code == null) code = name; - return dir("lib", [file("$name.dart", 'main() => "$code";')]); -} - -/// Describes a directory for a Git package. This directory is of the form -/// found in the revision cache of the global package cache. -Descriptor gitPackageRevisionCacheDir(String name, [int modifier]) { - var value = name; - if (modifier != null) value = "$name $modifier"; - return pattern( - new RegExp("$name${r'-[a-f0-9]+'}"), - (dirName) => dir(dirName, [libDir(name, value)])); -} - -/// Describes a directory for a Git package. This directory is of the form -/// found in the repo cache of the global package cache. -Descriptor gitPackageRepoCacheDir(String name) { - return pattern( - new RegExp("$name${r'-[a-f0-9]+'}"), - (dirName) => - dir(dirName, [dir('hooks'), dir('info'), dir('objects'), dir('refs')])); -} - -/// Describes the `packages/` directory containing all the given [packages], -/// which should be name/version pairs. The packages will be validated against -/// the format produced by the mock package server. -/// -/// A package with a null version should not be downloaded. -Descriptor packagesDir(Map packages) { - var contents = []; - packages.forEach((name, version) { - if (version == null) { - contents.add(nothing(name)); - } else { - contents.add( - dir(name, [file("$name.dart", 'main() => "$name $version";')])); - } - }); - return dir(packagesPath, contents); -} - -/// Describes the global package cache directory containing all the given -/// [packages], which should be name/version pairs. The packages will be -/// validated against the format produced by the mock package server. -/// -/// A package's value may also be a list of versions, in which case all -/// versions are expected to be downloaded. -/// -/// If [includePubspecs] is `true`, then pubspecs will be created for each -/// package. Defaults to `false` so that the contents of pubspecs are not -/// validated since they will often lack the dependencies section that the -/// real pubspec being compared against has. You usually only need to pass -/// `true` for this if you plan to call [create] on the resulting descriptor. -Descriptor cacheDir(Map packages, {bool includePubspecs: false}) { - var contents = []; - packages.forEach((name, versions) { - if (versions is! List) versions = [versions]; - for (var version in versions) { - var packageContents = [libDir(name, '$name $version')]; - if (includePubspecs) { - packageContents.add(libPubspec(name, version)); - } - contents.add(dir("$name-$version", packageContents)); - } - }); - - return hostedCache(contents); -} - -/// Describes the main cache directory containing cached hosted packages -/// downloaded from the mock package server. -Descriptor hostedCache(Iterable contents) { - return dir( - cachePath, - [dir('hosted', [async(port.then((p) => dir('localhost%58$p', contents)))])]); -} - -/// Describes the file in the system cache that contains the client's OAuth2 -/// credentials. The URL "/token" on [server] will be used as the token -/// endpoint for refreshing the access token. -Descriptor credentialsFile(ScheduledServer server, String accessToken, - {String refreshToken, DateTime expiration}) { - return async(server.url.then((url) { - return dir( - cachePath, - [ - file( - 'credentials.json', - new oauth2.Credentials( - accessToken, - refreshToken, - url.resolve('/token'), - ['https://www.googleapis.com/auth/userinfo.email'], - expiration).toJson())]); - })); -} - -/// Describes the application directory, containing only a pubspec specifying -/// the given [dependencies]. -DirectoryDescriptor appDir([Map dependencies]) => - dir(appPath, [appPubspec(dependencies)]); diff --git a/sdk/lib/_internal/pub_generated/test/descriptor/git.dart b/sdk/lib/_internal/pub_generated/test/descriptor/git.dart deleted file mode 100644 index 38ecdfa2167..00000000000 --- a/sdk/lib/_internal/pub_generated/test/descriptor/git.dart +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library descriptor.git; - -import 'dart:async'; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/descriptor.dart'; - -import '../../lib/src/git.dart' as git; - -/// Describes a Git repository and its contents. -class GitRepoDescriptor extends DirectoryDescriptor { - GitRepoDescriptor(String name, List contents) - : super(name, contents); - - /// Creates the Git repository and commits the contents. - Future create([String parent]) => schedule(() { - return super.create(parent).then((_) { - return _runGitCommands( - parent, - [['init'], ['add', '.'], ['commit', '-m', 'initial commit']]); - }); - }, 'creating Git repo:\n${describe()}'); - - /// Writes this descriptor to the filesystem, than commits any changes from - /// the previous structure to the Git repo. - /// - /// [parent] defaults to [defaultRoot]. - Future commit([String parent]) => schedule(() { - return super.create(parent).then((_) { - return _runGitCommands( - parent, - [['add', '.'], ['commit', '-m', 'update']]); - }); - }, 'committing Git repo:\n${describe()}'); - - /// Return a Future that completes to the commit in the git repository - /// referred to by [ref] at the current point in the scheduled test run. - /// - /// [parent] defaults to [defaultRoot]. - Future revParse(String ref, [String parent]) => schedule(() { - return _runGit(['rev-parse', ref], parent).then((output) => output[0]); - }, 'parsing revision $ref for Git repo:\n${describe()}'); - - /// Schedule a Git command to run in this repository. - /// - /// [parent] defaults to [defaultRoot]. - Future runGit(List args, [String parent]) => schedule(() { - return _runGit(args, parent); - }, "running 'git ${args.join(' ')}' in Git repo:\n${describe()}"); - - Future _runGitCommands(String parent, List> commands) => - Future.forEach(commands, (command) => _runGit(command, parent)); - - Future> _runGit(List args, String parent) { - // Explicitly specify the committer information. Git needs this to commit - // and we don't want to rely on the buildbots having this already set up. - var environment = { - 'GIT_AUTHOR_NAME': 'Pub Test', - 'GIT_AUTHOR_EMAIL': 'pub@dartlang.org', - 'GIT_COMMITTER_NAME': 'Pub Test', - 'GIT_COMMITTER_EMAIL': 'pub@dartlang.org' - }; - - if (parent == null) parent = defaultRoot; - return git.run( - args, - workingDir: path.join(parent, name), - environment: environment); - } -} - diff --git a/sdk/lib/_internal/pub_generated/test/descriptor/tar.dart b/sdk/lib/_internal/pub_generated/test/descriptor/tar.dart deleted file mode 100644 index 19280dc8b67..00000000000 --- a/sdk/lib/_internal/pub_generated/test/descriptor/tar.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library descriptor.tar; - -import 'dart:async'; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/descriptor.dart'; - -import '../../lib/src/io.dart'; - -/// Describes a tar file and its contents. -class TarFileDescriptor extends DirectoryDescriptor implements - ReadableDescriptor { - TarFileDescriptor(String name, List contents) - : super(name, contents); - - /// Creates the files and directories within this tar file, then archives - /// them, compresses them, and saves the result to [parentDir]. - Future create([String parent]) => schedule(() { - if (parent == null) parent = defaultRoot; - return withTempDir((tempDir) { - return Future.wait(contents.map((entry) { - return entry.create(tempDir); - })).then((_) { - var createdContents = - listDir(tempDir, recursive: true, includeHidden: true); - return createTarGz(createdContents, baseDir: tempDir).toBytes(); - }).then((bytes) { - var file = path.join(parent, name); - writeBinaryFile(file, bytes); - return file; - }); - }); - }, 'creating tar file:\n${describe()}'); - - /// Validates that the `.tar.gz` file at [path] contains the expected - /// contents. - Future validate([String parent]) { - throw new UnimplementedError("TODO(nweiz): implement this"); - } - - Stream> read() { - return new Stream>.fromFuture(withTempDir((tempDir) { - return create( - tempDir).then((_) => readBinaryFile(path.join(tempDir, name))); - })); - } -} diff --git a/sdk/lib/_internal/pub_generated/test/dev_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/dev_dependency_test.dart deleted file mode 100644 index 31b181e7532..00000000000 --- a/sdk/lib/_internal/pub_generated/test/dev_dependency_test.dart +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -main() { - initConfig(); - integration("includes root package's dev dependencies", () { - d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create(); - - d.dir('bar', [d.libDir('bar'), d.libPubspec('bar', '0.0.1')]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dev_dependencies": { - "foo": { - "path": "../foo" - }, - "bar": { - "path": "../bar" - }, - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.dir("bar", [d.file("bar.dart", 'main() => "bar";')])]).validate(); - }); - - integration("includes dev dependency's transitive dependencies", () { - d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1', deps: { - "bar": { - "path": "../bar" - } - })]).create(); - - d.dir('bar', [d.libDir('bar'), d.libPubspec('bar', '0.0.1')]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dev_dependencies": { - "foo": { - "path": "../foo" - } - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.dir("bar", [d.file("bar.dart", 'main() => "bar";')])]).validate(); - }); - - integration("ignores transitive dependency's dev dependencies", () { - d.dir('foo', [d.libDir('foo'), d.pubspec({ - "name": "foo", - "version": "0.0.1", - "dev_dependencies": { - "bar": { - "path": "../bar" - } - } - })]).create(); - - d.dir('bar', [d.libDir('bar'), d.libPubspec('bar', '0.0.1')]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.nothing("bar")]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/does_not_show_other_versions_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/does_not_show_other_versions_test.dart deleted file mode 100644 index 2c49d31e6a1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/downgrade/does_not_show_other_versions_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("does not show how many other versions are available", () { - servePackages((builder) { - builder.serve("downgraded", "1.0.0"); - builder.serve("downgraded", "2.0.0"); - builder.serve("downgraded", "3.0.0-dev"); - }); - - d.appDir({ - "downgraded": "3.0.0-dev" - }).create(); - - pubGet(); - - // Loosen the constraints. - d.appDir({ - "downgraded": ">=2.0.0" - }).create(); - - pubDowngrade(output: contains("downgraded 2.0.0 (was 3.0.0-dev)")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/doesnt_change_git_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/doesnt_change_git_dependencies_test.dart deleted file mode 100644 index 9d7b9833c0e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/downgrade/doesnt_change_git_dependencies_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("doesn't change git dependencies", () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - pubDowngrade(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/dry_run_does_not_apply_changes_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/dry_run_does_not_apply_changes_test.dart deleted file mode 100644 index 3b0c9d1e4a4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/downgrade/dry_run_does_not_apply_changes_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("--dry-run shows report but does not apply changes", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "2.0.0"); - }); - - // Create the first lockfile. - d.appDir({ - "foo": "2.0.0" - }).create(); - - pubGet(); - - // Change the pubspec. - d.appDir({ - "foo": "any" - }).create(); - - // Also delete the "packages" directory. - schedule(() { - deleteEntry(path.join(sandboxDir, appPath, "packages")); - }); - - // Do the dry run. - pubDowngrade( - args: ["--dry-run"], - output: allOf( - [contains("< foo 1.0.0"), contains("Would change 1 dependency.")])); - - d.dir(appPath, [// The lockfile should be unmodified. - d.matcherFile("pubspec.lock", contains("2.0.0")), - // The "packages" directory should not have been regenerated. - d.nothing("packages")]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_dependers_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/unlock_dependers_test.dart deleted file mode 100644 index 4140a5fde51..00000000000 --- a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_dependers_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "downgrades a locked package's dependers in order to get it to " "min version", - () { - servePackages((builder) { - builder.serve("foo", "2.0.0", deps: { - "bar": ">1.0.0" - }); - builder.serve("bar", "2.0.0"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "2.0.0", - "bar": "2.0.0" - }).validate(); - - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "bar": "any" - }); - builder.serve("bar", "1.0.0"); - }); - - pubDowngrade(args: ['bar']); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_if_necessary_test.dart b/sdk/lib/_internal/pub_generated/test/downgrade/unlock_if_necessary_test.dart deleted file mode 100644 index 6eab79a1b81..00000000000 --- a/sdk/lib/_internal/pub_generated/test/downgrade/unlock_if_necessary_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "downgrades one locked hosted package's dependencies if it's " "necessary", - () { - servePackages((builder) { - builder.serve("foo", "2.0.0", deps: { - "foo_dep": "any" - }); - builder.serve("foo_dep", "2.0.0"); - }); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "2.0.0", - "foo_dep": "2.0.0" - }).validate(); - - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "foo_dep": "<2.0.0" - }); - builder.serve("foo_dep", "1.0.0"); - }); - - pubDowngrade(args: ['foo']); - - d.packagesDir({ - "foo": "1.0.0", - "foo_dep": "1.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/error_group_test.dart b/sdk/lib/_internal/pub_generated/test/error_group_test.dart deleted file mode 100644 index 3589b3eb549..00000000000 --- a/sdk/lib/_internal/pub_generated/test/error_group_test.dart +++ /dev/null @@ -1,520 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library error_group_test; - -import 'dart:async'; - -import 'package:unittest/unittest.dart'; - -import '../lib/src/error_group.dart'; -import '../lib/src/utils.dart'; - -ErrorGroup errorGroup; - -// TODO(nweiz): once there's a global error handler, we should test that it does -// and does not get called at appropriate times. See issue 5958. -// -// One particular thing we should test that has no tests now is that a stream -// that has a subscription added and subsequently canceled counts as having no -// listeners. - -main() { - group('with no futures or streams', () { - setUp(() { - errorGroup = new ErrorGroup(); - }); - - test('should pass signaled errors to .done', () { - expect(errorGroup.done, throwsFormatException); - errorGroup.signalError(new FormatException()); - }); - - test( - "shouldn't allow additional futures or streams once an error has been " - "signaled", - () { - expect(errorGroup.done, throwsFormatException); - errorGroup.signalError(new FormatException()); - - expect( - () => errorGroup.registerFuture(new Future.value()), - throwsStateError); - expect( - () => errorGroup.registerStream(new StreamController(sync: true).stream), - throwsStateError); - }); - }); - - group('with a single future', () { - Completer completer; - Future future; - - setUp(() { - errorGroup = new ErrorGroup(); - completer = new Completer(); - future = errorGroup.registerFuture(completer.future); - }); - - test('should pass through a value from the future', () { - expect(future, completion(equals('value'))); - expect(errorGroup.done, completes); - completer.complete('value'); - }); - - test( - "shouldn't allow additional futures or streams once .done has " "been called", - () { - completer.complete('value'); - - expect( - completer.future.then((_) => errorGroup.registerFuture(new Future.value())), - throwsStateError); - expect( - completer.future.then( - (_) => errorGroup.registerStream(new StreamController(sync: true).stream)), - throwsStateError); - }); - - test( - 'should pass through an exception from the future if it has a ' 'listener', - () { - expect(future, throwsFormatException); - // errorGroup shouldn't top-level the exception - completer.completeError(new FormatException()); - }); - - test( - 'should notify the error group of an exception from the future even ' - 'if it has a listener', - () { - expect(future, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - completer.completeError(new FormatException()); - }); - - test( - 'should pass a signaled exception to the future if it has a listener ' - 'and should ignore a subsequent value from that future', - () { - expect(future, throwsFormatException); - // errorGroup shouldn't top-level the exception - errorGroup.signalError(new FormatException()); - completer.complete('value'); - }); - - test( - 'should pass a signaled exception to the future if it has a listener ' - 'and should ignore a subsequent exception from that future', - () { - expect(future, throwsFormatException); - // errorGroup shouldn't top-level the exception - errorGroup.signalError(new FormatException()); - completer.completeError(new ArgumentError()); - }); - - test( - 'should notify the error group of a signaled exception even if the ' - 'future has a listener', - () { - expect(future, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - errorGroup.signalError(new FormatException()); - }); - - test( - "should complete .done if the future receives a value even if the " - "future doesn't have a listener", - () { - expect(errorGroup.done, completes); - completer.complete('value'); - - // A listener added afterwards should receive the value - expect(errorGroup.done.then((_) => future), completion(equals('value'))); - }); - - test( - "should pipe an exception from the future to .done if the future " - "doesn't have a listener", - () { - expect(errorGroup.done, throwsFormatException); - completer.completeError(new FormatException()); - - // A listener added afterwards should receive the exception - expect(errorGroup.done.catchError((_) { - expect(future, throwsFormatException); - }), completes); - }); - - test( - "should pass a signaled exception to .done if the future doesn't have " - "a listener", - () { - expect(errorGroup.done, throwsFormatException); - errorGroup.signalError(new FormatException()); - - // A listener added afterwards should receive the exception - expect(errorGroup.done.catchError((_) { - completer.complete('value'); // should be ignored - expect(future, throwsFormatException); - }), completes); - }); - }); - - group('with multiple futures', () { - Completer completer1; - Completer completer2; - Future future1; - Future future2; - - setUp(() { - errorGroup = new ErrorGroup(); - completer1 = new Completer(); - completer2 = new Completer(); - future1 = errorGroup.registerFuture(completer1.future); - future2 = errorGroup.registerFuture(completer2.future); - }); - - test( - "should pipe exceptions from one future to the other and to " ".complete", - () { - expect(future1, throwsFormatException); - expect(future2, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - - completer1.completeError(new FormatException()); - }); - - test( - "each future should be able to complete with a value " "independently", - () { - expect(future1, completion(equals('value1'))); - expect(future2, completion(equals('value2'))); - expect(errorGroup.done, completes); - - completer1.complete('value1'); - completer2.complete('value2'); - }); - - test( - "shouldn't throw a top-level exception if a future receives an error " - "after the other listened future completes", - () { - expect(future1, completion(equals('value'))); - completer1.complete('value'); - - expect(future1.then((_) { - // shouldn't cause a top-level exception - completer2.completeError(new FormatException()); - }), completes); - }); - - test( - "shouldn't throw a top-level exception if an error is signaled after " - "one listened future completes", - () { - expect(future1, completion(equals('value'))); - completer1.complete('value'); - - expect(future1.then((_) { - // shouldn't cause a top-level exception - errorGroup.signalError(new FormatException()); - }), completes); - }); - }); - - group('with a single stream', () { - StreamController controller; - Stream stream; - - setUp(() { - errorGroup = new ErrorGroup(); - controller = new StreamController.broadcast(sync: true); - stream = errorGroup.registerStream(controller.stream); - }); - - test('should pass through values from the stream', () { - StreamIterator iter = new StreamIterator(stream); - iter.moveNext().then((hasNext) { - expect(hasNext, isTrue); - expect(iter.current, equals(1)); - iter.moveNext().then((hasNext) { - expect(hasNext, isTrue); - expect(iter.current, equals(2)); - expect(iter.moveNext(), completion(isFalse)); - }); - }); - expect(errorGroup.done, completes); - - controller - ..add(1) - ..add(2) - ..close(); - }); - - test( - 'should pass through an error from the stream if it has a ' 'listener', - () { - expect(stream.first, throwsFormatException); - // errorGroup shouldn't top-level the exception - controller.addError(new FormatException()); - }); - - test( - 'should notify the error group of an exception from the stream even ' - 'if it has a listener', - () { - expect(stream.first, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - controller.addError(new FormatException()); - }); - - test( - 'should pass a signaled exception to the stream if it has a listener ' - 'and should unsubscribe that stream', - () { - // errorGroup shouldn't top-level the exception - expect(stream.first, throwsFormatException); - errorGroup.signalError(new FormatException()); - - expect(newFuture(() { - controller.add('value'); - }), completes); - }); - - test( - 'should notify the error group of a signaled exception even if the ' - 'stream has a listener', - () { - expect(stream.first, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - errorGroup.signalError(new FormatException()); - }); - - test( - "should see one value and complete .done when the stream is done even " - "if the stream doesn't have a listener", - () { - expect(errorGroup.done, completes); - controller.add('value'); - controller.close(); - - // Now that broadcast controllers have been removed a listener should - // see the value that has been put into the controller. - expect( - errorGroup.done.then((_) => stream.toList()), - completion(equals(['value']))); - }); - - }); - - group('with a single single-subscription stream', () { - StreamController controller; - Stream stream; - - setUp(() { - errorGroup = new ErrorGroup(); - controller = new StreamController(sync: true); - stream = errorGroup.registerStream(controller.stream); - }); - - test( - "should complete .done when the stream is done even if the stream " - "doesn't have a listener", - () { - expect(errorGroup.done, completes); - controller.add('value'); - controller.close(); - - // A listener added afterwards should receive the value - expect( - errorGroup.done.then((_) => stream.toList()), - completion(equals(['value']))); - }); - - test( - "should pipe an exception from the stream to .done if the stream " - "doesn't have a listener", - () { - expect(errorGroup.done, throwsFormatException); - controller.addError(new FormatException()); - - // A listener added afterwards should receive the exception - expect(errorGroup.done.catchError((_) { - controller.add('value'); // should be ignored - expect(stream.first, throwsFormatException); - }), completes); - }); - - test( - "should pass a signaled exception to .done if the stream doesn't " - "have a listener", - () { - expect(errorGroup.done, throwsFormatException); - errorGroup.signalError(new FormatException()); - - // A listener added afterwards should receive the exception - expect(errorGroup.done.catchError((_) { - controller.add('value'); // should be ignored - expect(stream.first, throwsFormatException); - }), completes); - }); - }); - - group('with multiple streams', () { - StreamController controller1; - StreamController controller2; - Stream stream1; - Stream stream2; - - setUp(() { - errorGroup = new ErrorGroup(); - controller1 = new StreamController.broadcast(sync: true); - controller2 = new StreamController.broadcast(sync: true); - stream1 = errorGroup.registerStream(controller1.stream); - stream2 = errorGroup.registerStream(controller2.stream); - }); - - test( - "should pipe exceptions from one stream to the other and to .done", - () { - expect(stream1.first, throwsFormatException); - expect(stream2.first, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - - controller1.addError(new FormatException()); - }); - - test("each future should be able to emit values independently", () { - expect(stream1.toList(), completion(equals(['value1.1', 'value1.2']))); - expect(stream2.toList(), completion(equals(['value2.1', 'value2.2']))); - expect(errorGroup.done, completes); - - controller1 - ..add('value1.1') - ..add('value1.2') - ..close(); - controller2 - ..add('value2.1') - ..add('value2.2') - ..close(); - }); - - test( - "shouldn't throw a top-level exception if a stream receives an error " - "after the other listened stream completes", - () { - var signal = new Completer(); - expect( - stream1.toList().whenComplete(signal.complete), - completion(equals(['value1', 'value2']))); - controller1 - ..add('value1') - ..add('value2') - ..close(); - - expect(signal.future.then((_) { - // shouldn't cause a top-level exception - controller2.addError(new FormatException()); - }), completes); - }); - - test( - "shouldn't throw a top-level exception if an error is signaled after " - "one listened stream completes", - () { - var signal = new Completer(); - expect( - stream1.toList().whenComplete(signal.complete), - completion(equals(['value1', 'value2']))); - controller1 - ..add('value1') - ..add('value2') - ..close(); - - expect(signal.future.then((_) { - // shouldn't cause a top-level exception - errorGroup.signalError(new FormatException()); - }), completes); - }); - }); - - group('with a stream and a future', () { - StreamController controller; - Stream stream; - Completer completer; - Future future; - - setUp(() { - errorGroup = new ErrorGroup(); - controller = new StreamController.broadcast(sync: true); - stream = errorGroup.registerStream(controller.stream); - completer = new Completer(); - future = errorGroup.registerFuture(completer.future); - }); - - test("should pipe exceptions from the stream to the future", () { - expect(stream.first, throwsFormatException); - expect(future, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - - controller.addError(new FormatException()); - }); - - test("should pipe exceptions from the future to the stream", () { - expect(stream.first, throwsFormatException); - expect(future, throwsFormatException); - expect(errorGroup.done, throwsFormatException); - - completer.completeError(new FormatException()); - }); - - test( - "the stream and the future should be able to complete/emit values " - "independently", - () { - expect(stream.toList(), completion(equals(['value1.1', 'value1.2']))); - expect(future, completion(equals('value2.0'))); - expect(errorGroup.done, completes); - - controller - ..add('value1.1') - ..add('value1.2') - ..close(); - completer.complete('value2.0'); - }); - - test( - "shouldn't throw a top-level exception if the stream receives an error " - "after the listened future completes", - () { - expect(future, completion(equals('value'))); - completer.complete('value'); - - expect(future.then((_) { - // shouldn't cause a top-level exception - controller.addError(new FormatException()); - }), completes); - }); - - test( - "shouldn't throw a top-level exception if the future receives an " - "error after the listened stream completes", - () { - var signal = new Completer(); - expect( - stream.toList().whenComplete(signal.complete), - completion(equals(['value1', 'value2']))); - controller - ..add('value1') - ..add('value2') - ..close(); - - expect(signal.future.then((_) { - // shouldn't cause a top-level exception - completer.completeError(new FormatException()); - }), completes); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/broken_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/broken_symlink_test.dart deleted file mode 100644 index eb3646ced51..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/broken_symlink_test.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('replaces a broken "packages" symlink', () { - d.dir(appPath, [d.appPubspec(), d.libDir('foo'), d.dir("bin")]).create(); - - // Create a broken "packages" symlink in "bin". - scheduleSymlink("nonexistent", path.join(appPath, "packages")); - - pubGet(); - - d.dir( - appPath, - [ - d.dir( - "bin", - [ - d.dir( - "packages", - [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])])]).validate(); - }); - - integration('replaces a broken secondary "packages" symlink', () { - d.dir(appPath, [d.appPubspec(), d.libDir('foo'), d.dir("bin")]).create(); - - // Create a broken "packages" symlink in "bin". - scheduleSymlink("nonexistent", path.join(appPath, "bin", "packages")); - - pubGet(); - - d.dir( - appPath, - [ - d.dir( - "bin", - [ - d.dir( - "packages", - [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/cache_transformed_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/get/cache_transformed_dependency_test.dart deleted file mode 100644 index 222e9747ab2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/cache_transformed_dependency_test.dart +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const MODE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ModeTransformer extends Transformer { - final BarbackSettings _settings; - - ModeTransformer.asPlugin(this._settings); - - String get allowedExtensions => '.dart'; - - void apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - transform.addOutput(new Asset.fromString( - transform.primaryInput.id, - contents.replaceAll("MODE", _settings.mode.name))); - }); - } -} -"""; - -const HAS_INPUT_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class HasInputTransformer extends Transformer { - HasInputTransformer.asPlugin(); - - bool get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return Future.wait([ - transform.hasInput(new AssetId("foo", "lib/foo.dart")), - transform.hasInput(new AssetId("foo", "lib/does/not/exist.dart")) - ]).then((results) { - transform.addOutput(new Asset.fromString( - transform.primaryInput.id, - "lib/foo.dart: \${results.first}, " - "lib/does/not/exist.dart: \${results.last}")); - }); - } -} -"""; - -main() { - initConfig(); - - integration("caches a transformed dependency", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "final message = 'Hello!';")])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: contains("Precompiled foo.")); - - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate(); - }); - - integration("caches a dependency transformed by its dependency", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'bar': '1.2.3' - }, pubspec: { - 'transformers': ['bar'] - }, - contents: [d.dir("lib", [d.file("foo.dart", "final message = 'Hello!';")])]); - - builder.serve("bar", "1.2.3", deps: { - 'barback': 'any' - }, - contents: [ - d.dir( - "lib", - [d.file("transformer.dart", replaceTransformer("Hello", "Goodbye"))])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: contains("Precompiled foo.")); - - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate(); - }); - - integration("doesn't cache an untransformed dependency", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve( - "foo", - "1.2.3", - contents: [d.dir("lib", [d.file("foo.dart", "final message = 'Hello!';")])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: isNot(contains("Precompiled foo."))); - - d.dir(appPath, [d.nothing(".pub/deps")]).validate(); - }); - - integration("recaches when the dependency is updated", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "final message = 'Hello!';")])]); - - builder.serve("foo", "1.2.4", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "See ya")), - d.file("foo.dart", "final message = 'Hello!';")])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: contains("Precompiled foo.")); - - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate(); - - // Upgrade to the new version of foo. - d.appDir({ - "foo": "1.2.4" - }).create(); - - pubGet(output: contains("Precompiled foo.")); - - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final message = 'See ya!';")])]).validate(); - }); - - integration("recaches when a transitive dependency is updated", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any', - 'bar': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "final message = 'Hello!';")])]); - - builder.serve("bar", "5.6.7"); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - pubGet(output: contains("Precompiled foo.")); - - servePackages((builder) => builder.serve("bar", "6.0.0")); - pubUpgrade(output: contains("Precompiled foo.")); - }); - - integration("doesn't recache when an unrelated dependency is updated", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "final message = 'Hello!';")])]); - - builder.serve("bar", "5.6.7"); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - pubGet(output: contains("Precompiled foo.")); - - servePackages((builder) => builder.serve("bar", "6.0.0")); - pubUpgrade(output: isNot(contains("Precompiled foo."))); - }); - - integration("caches the dependency in debug mode", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", MODE_TRANSFORMER), - d.file("foo.dart", "final mode = 'MODE';")])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: contains("Precompiled foo.")); - - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final mode = 'debug';")])]).validate(); - }); - - integration("loads code from the cache", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "final message = 'Hello!';")])]); - }); - - d.dir(appPath, [d.appPubspec({ - "foo": "1.2.3" - }), d.dir('bin', [d.file('script.dart', """ - import 'package:foo/foo.dart'; - - void main() => print(message);""")])]).create(); - - pubGet(output: contains("Precompiled foo.")); - - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final message = 'Modified!';")])]).create(); - - var pub = pubRun(args: ["script"]); - pub.stdout.expect("Modified!"); - pub.shouldExit(); - }); - - integration("doesn't re-transform code loaded from the cache", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "final message = 'Hello!';")])]); - }); - - d.dir(appPath, [d.appPubspec({ - "foo": "1.2.3" - }), d.dir('bin', [d.file('script.dart', """ - import 'package:foo/foo.dart'; - - void main() => print(message);""")])]).create(); - - pubGet(output: contains("Precompiled foo.")); - - // Manually reset the cache to its original state to prove that the - // transformer won't be run again on it. - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final message = 'Hello!';")])]).create(); - - var pub = pubRun(args: ["script"]); - pub.stdout.expect("Hello!"); - pub.shouldExit(); - }); - - // Regression test for issue 21087. - integration("hasInput works for static packages", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "void main() => print('Hello!');")])]); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "1.2.3" - }, - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [d.dir("src", [d.file("transformer.dart", HAS_INPUT_TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - pubGet(output: contains("Precompiled foo.")); - - pubServe(); - requestShouldSucceed( - "foo.txt", - "lib/foo.dart: true, lib/does/not/exist.dart: false"); - endPubServe(); - }); - - // Regression test for issue 21810. - integration( - "decaches when the dependency is updated to something " "untransformed", - () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir( - "lib", - [ - d.file("transformer.dart", replaceTransformer("Hello", "Goodbye")), - d.file("foo.dart", "final message = 'Hello!';")])]); - - builder.serve("foo", "1.2.4", deps: { - 'barback': 'any' - }, - contents: [d.dir("lib", [d.file("foo.dart", "final message = 'Hello!';")])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: contains("Precompiled foo.")); - - d.dir( - appPath, - [ - d.dir( - ".pub/deps/debug/foo/lib", - [d.file("foo.dart", "final message = 'Goodbye!';")])]).validate(); - - // Upgrade to the new version of foo. - d.appDir({ - "foo": "1.2.4" - }).create(); - - pubGet(output: isNot(contains("Precompiled foo."))); - - d.dir(appPath, [d.nothing(".pub/deps/debug/foo")]).validate(); - }); -} - -String replaceTransformer(String input, String output) { - return """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ReplaceTransformer extends Transformer { - ReplaceTransformer.asPlugin(); - - String get allowedExtensions => '.dart'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - transform.addOutput(new Asset.fromString( - transform.primaryInput.id, - contents.replaceAll("$input", "$output"))); - }); - } -} -"""; -} diff --git a/sdk/lib/_internal/pub_generated/test/get/dry_run_does_not_apply_changes_test.dart b/sdk/lib/_internal/pub_generated/test/get/dry_run_does_not_apply_changes_test.dart deleted file mode 100644 index a23d6bdcd08..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/dry_run_does_not_apply_changes_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("--dry-run shows but does not apply changes", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - }); - - d.appDir({ - "foo": "1.0.0" - }).create(); - - pubGet( - args: ["--dry-run"], - output: allOf( - [contains("+ foo 1.0.0"), contains("Would change 1 dependency.")])); - - d.dir(appPath, [// The lockfile should not be created. - d.nothing("pubspec.lock"), - // The "packages" directory should not have been generated. - d.nothing("packages")]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_and_upgrade_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_and_upgrade_test.dart deleted file mode 100644 index 99366642bac..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_and_upgrade_test.dart +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('checks out and upgrades a package from Git', () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir('cache', [d.gitPackageRepoCacheDir('foo')]), - d.gitPackageRevisionCacheDir('foo')])]).validate(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - pubUpgrade(output: contains("Changed 1 dependency!")); - - // When we download a new version of the git package, we should re-use the - // git/cache directory but create a new git/ directory. - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir('cache', [d.gitPackageRepoCacheDir('foo')]), - d.gitPackageRevisionCacheDir('foo'), - d.gitPackageRevisionCacheDir('foo', 2)])]).validate(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_branch_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_branch_test.dart deleted file mode 100644 index bc40b990089..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_branch_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('checks out a package at a specific branch from Git', () { - ensureGit(); - - var repo = - d.git('foo.git', [d.libDir('foo', 'foo 1'), d.libPubspec('foo', '1.0.0')]); - repo.create(); - repo.runGit(["branch", "old"]); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - d.appDir({ - "foo": { - "git": { - "url": "../foo.git", - "ref": "old" - } - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_revision_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_revision_test.dart deleted file mode 100644 index 3f65f8df220..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_revision_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('checks out a package at a specific revision from Git', () { - ensureGit(); - - var repo = - d.git('foo.git', [d.libDir('foo', 'foo 1'), d.libPubspec('foo', '1.0.0')]); - repo.create(); - var commit = repo.revParse('HEAD'); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - d.appDir({ - "foo": { - "git": { - "url": "../foo.git", - "ref": commit - } - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_test.dart deleted file mode 100644 index 9e25aad0911..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('checks out a package from Git', () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir('cache', [d.gitPackageRepoCacheDir('foo')]), - d.gitPackageRevisionCacheDir('foo')])]).validate(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_transitive_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_transitive_test.dart deleted file mode 100644 index b2b10475f49..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_transitive_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('checks out packages transitively from Git', () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0', deps: { - "bar": { - "git": "../bar.git" - } - })]).create(); - - d.git('bar.git', [d.libDir('bar'), d.libPubspec('bar', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir( - 'cache', - [d.gitPackageRepoCacheDir('foo'), d.gitPackageRepoCacheDir('bar')]), - d.gitPackageRevisionCacheDir('foo'), - d.gitPackageRevisionCacheDir('bar')])]).validate(); - - d.dir( - packagesPath, - [ - d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]), - d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_twice_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_twice_test.dart deleted file mode 100644 index 6a7c9c7e1d0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_twice_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('checks out a package from Git twice', () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir('cache', [d.gitPackageRepoCacheDir('foo')]), - d.gitPackageRevisionCacheDir('foo')])]).validate(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - // Verify that nothing breaks if we get a Git revision that's already - // in the cache. - pubUpgrade(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_unfetched_revision_of_cached_repo_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_unfetched_revision_of_cached_repo_test.dart deleted file mode 100644 index 277f2d189a6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_unfetched_revision_of_cached_repo_test.dart +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - // Regression test for issue 20947. - integration( - 'checks out an unfetched and locked revision of a cached ' 'repository', - () { - ensureGit(); - - // In order to get a lockfile that refers to a newer revision than is in the - // cache, we'll switch between two caches. First we ensure that the repo is - // in the first cache. - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - // Switch to a new cache. - schedule( - () => - renameDir(p.join(sandboxDir, cachePath), p.join(sandboxDir, "$cachePath.old"))); - - // Make the lockfile point to a new revision of the git repository. - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - pubUpgrade(output: contains("Changed 1 dependency!")); - - // Switch back to the old cache. - schedule(() { - var cacheDir = p.join(sandboxDir, cachePath); - deleteEntry(cacheDir); - renameDir(p.join(sandboxDir, "$cachePath.old"), cacheDir); - }); - - // Get the updated version of the git dependency based on the lockfile. - pubGet(); - - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir('cache', [d.gitPackageRepoCacheDir('foo')]), - d.gitPackageRevisionCacheDir('foo'), - d.gitPackageRevisionCacheDir('foo', 2)])]).validate(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/check_out_with_trailing_slash_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/check_out_with_trailing_slash_test.dart deleted file mode 100644 index 345ff4fbae8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/check_out_with_trailing_slash_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - group("(regression)", () { - integration('checks out a package from Git with a trailing slash', () { - ensureGit(); - - d.git( - 'foo.git', - [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git/" - } - }).create(); - - pubGet(); - - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir('cache', [d.gitPackageRepoCacheDir('foo')]), - d.gitPackageRevisionCacheDir('foo')])]).validate(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/dependency_name_match_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/dependency_name_match_pubspec_test.dart deleted file mode 100644 index 86b3a2e3f7e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/dependency_name_match_pubspec_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'requires the dependency name to match the remote pubspec ' 'name', - () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.dir(appPath, [d.appPubspec({ - "weirdname": { - "git": "../foo.git" - } - })]).create(); - - pubGet( - error: contains('"name" field doesn\'t match expected name ' '"weirdname".'), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/different_repo_name_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/different_repo_name_test.dart deleted file mode 100644 index e6e01736410..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/different_repo_name_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'doesn\'t require the repository name to match the name in the ' 'pubspec', - () { - ensureGit(); - - d.git( - 'foo.git', - [d.libDir('weirdname'), d.libPubspec('weirdname', '1.0.0')]).create(); - - d.dir(appPath, [d.appPubspec({ - "weirdname": { - "git": "../foo.git" - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir( - 'weirdname', - [d.file('weirdname.dart', 'main() => "weirdname";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/doesnt_fetch_if_nothing_changes_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/doesnt_fetch_if_nothing_changes_test.dart deleted file mode 100644 index c776a751131..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/doesnt_fetch_if_nothing_changes_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("doesn't re-fetch a repository if nothing changes", () { - ensureGit(); - - var repo = - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]); - repo.create(); - - d.appDir({ - "foo": { - "git": { - "url": "../foo.git" - } - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - // Delete the repo. This will cause "pub get" to fail if it tries to - // re-fetch. - schedule(() => deleteEntry(p.join(sandboxDir, 'foo.git'))); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/lock_version_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/lock_version_test.dart deleted file mode 100644 index 63acc2cb3c4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/lock_version_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('keeps a Git package locked to the version in the lockfile', () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - // This get should lock the foo.git dependency to the current revision. - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - // Delete the packages path to simulate a new checkout of the application. - schedule(() => deleteEntry(path.join(sandboxDir, packagesPath))); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - // This get shouldn't upgrade the foo.git dependency due to the lockfile. - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/locked_revision_without_repo_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/locked_revision_without_repo_test.dart deleted file mode 100644 index ef31eb45db0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/locked_revision_without_repo_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -// Regression test for issue 16470. - -main() { - initConfig(); - integration('checks out the repository for a locked revision', () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - // This get should lock the foo.git dependency to the current revision. - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - // Delete the packages path and the cache to simulate a brand new checkout - // of the application. - schedule(() => deleteEntry(path.join(sandboxDir, packagesPath))); - schedule(() => deleteEntry(path.join(sandboxDir, cachePath))); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - // This get shouldn't upgrade the foo.git dependency due to the lockfile. - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_name_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_name_test.dart deleted file mode 100644 index 2b0acbfb84e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_name_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'requires the dependency to have a pubspec with a name ' 'field', - () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.pubspec({})]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet( - error: contains('Missing the required "name" field.'), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_test.dart deleted file mode 100644 index a81e3761a80..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/require_pubspec_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('requires the dependency to have a pubspec', () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet( - error: new RegExp( - r'Could not find a file named "pubspec\.yaml" ' r'in "[^\n]*"\.')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/stay_locked_if_compatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/stay_locked_if_compatible_test.dart deleted file mode 100644 index 962efb221a8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/stay_locked_if_compatible_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't upgrade a locked Git package with a new compatible " "constraint", - () { - ensureGit(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 1.0.0'), d.libPubspec("foo", "1.0.0")]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1.0.0";')])]).validate(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 1.0.1'), d.libPubspec("foo", "1.0.1")]).commit(); - - d.appDir({ - "foo": { - "git": "../foo.git", - "version": ">=1.0.0" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1.0.0";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/git/unlock_if_incompatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/git/unlock_if_incompatible_test.dart deleted file mode 100644 index 588ee28b205..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/git/unlock_if_incompatible_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'upgrades a locked Git package with a new incompatible ' 'constraint', - () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '0.5.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 1.0.0'), d.libPubspec("foo", "1.0.0")]).commit(); - - d.appDir({ - "foo": { - "git": "../foo.git", - "version": ">=1.0.0" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo 1.0.0";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/avoid_network_requests_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/avoid_network_requests_test.dart deleted file mode 100644 index 3421e8fc557..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/avoid_network_requests_test.dart +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - - integration('only requests versions that are needed during solving', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "1.1.0"); - builder.serve("foo", "1.2.0"); - builder.serve("bar", "1.0.0"); - builder.serve("bar", "1.1.0"); - builder.serve("bar", "1.2.0"); - }); - - d.appDir({ - "foo": "any" - }).create(); - - // Get once so it gets cached. - pubGet(); - - // Clear the cache. We don't care about anything that was served during - // the initial get. - getRequestedPaths(); - - // Add "bar" to the dependencies. - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - // Run the solver again. - pubGet(); - - d.packagesDir({ - "foo": "1.2.0", - "bar": "1.2.0" - }).validate(); - - // The get should not have done any network requests since the lock file is - // up to date. - getRequestedPaths().then((paths) { - expect( - paths, - unorderedEquals([// Bar should be requested because it's new, but not foo. - "api/packages/bar", // Should only request the most recent version. - "api/packages/bar/versions/1.2.0", // Need to download it. - "packages/bar/versions/1.2.0.tar.gz"])); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/cached_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/cached_pubspec_test.dart deleted file mode 100644 index 750ef6df2ab..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/cached_pubspec_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - - integration('does not request a pubspec for a cached package', () { - servePackages((builder) => builder.serve("foo", "1.2.3")); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - // Get once so it gets cached. - pubGet(); - - // Clear the cache. We don't care about anything that was served during - // the initial get. - getRequestedPaths(); - - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - d.packagesDir({ - "foo": "1.2.3" - }).validate(); - - // Run the solver again now that it's cached. - pubGet(); - - // The get should not have requested the pubspec since it's local already. - getRequestedPaths().then((paths) { - expect(paths, isNot(contains("packages/foo/versions/1.2.3.yaml"))); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/do_not_upgrade_on_removed_constraints_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/do_not_upgrade_on_removed_constraints_test.dart deleted file mode 100644 index b3da83d5738..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/do_not_upgrade_on_removed_constraints_test.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't upgrade dependencies whose constraints have been " "removed", - () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "shared-dep": "any" - }); - builder.serve("bar", "1.0.0", deps: { - "shared-dep": "<2.0.0" - }); - builder.serve("shared-dep", "1.0.0"); - builder.serve("shared-dep", "2.0.0"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0", - "shared-dep": "1.0.0" - }).validate(); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": null, - "shared-dep": "1.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/does_no_network_requests_when_possible_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/does_no_network_requests_when_possible_test.dart deleted file mode 100644 index 7ff76c0b04f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/does_no_network_requests_when_possible_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - - integration('does not request versions if the lockfile is up to date', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "1.1.0"); - builder.serve("foo", "1.2.0"); - }); - - d.appDir({ - "foo": "any" - }).create(); - - // Get once so it gets cached. - pubGet(); - - // Clear the cache. We don't care about anything that was served during - // the initial get. - getRequestedPaths(); - - // Run the solver again now that it's cached. - pubGet(); - - d.cacheDir({ - "foo": "1.2.0" - }).validate(); - d.packagesDir({ - "foo": "1.2.0" - }).validate(); - - // The get should not have done any network requests since the lock file is - // up to date. - getRequestedPaths().then((paths) { - expect(paths, isEmpty); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/get_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/get_test.dart deleted file mode 100644 index 97b56308138..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/get_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('gets a package from a pub server', () { - servePackages((builder) => builder.serve("foo", "1.2.3")); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(); - - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - d.packagesDir({ - "foo": "1.2.3" - }).validate(); - }); - - integration('URL encodes the package name', () { - serveNoPackages(); - - d.appDir({ - "bad name!": "1.2.3" - }).create(); - - pubGet( - error: new RegExp( - r"Could not find package bad name! at http://localhost:\d+\."), - exitCode: exit_codes.UNAVAILABLE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/get_transitive_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/get_transitive_test.dart deleted file mode 100644 index ad984b5c19a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/get_transitive_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('gets packages transitively from a pub server', () { - servePackages((builder) { - builder.serve("foo", "1.2.3", deps: { - "bar": "2.0.4" - }); - builder.serve("bar", "2.0.3"); - builder.serve("bar", "2.0.4"); - builder.serve("bar", "2.0.5"); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(); - - d.cacheDir({ - "foo": "1.2.3", - "bar": "2.0.4" - }).validate(); - d.packagesDir({ - "foo": "1.2.3", - "bar": "2.0.4" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/gets_a_package_with_busted_dev_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/gets_a_package_with_busted_dev_dependencies_test.dart deleted file mode 100644 index 1ca31ecaf25..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/gets_a_package_with_busted_dev_dependencies_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - - // Regression test for issue 22194. - integration( - 'gets a dependency with broken dev dependencies from a pub ' 'server', - () { - servePackages((builder) { - builder.serve("foo", "1.2.3", pubspec: { - "dev_dependencies": { - "busted": { - "not a real source": null - } - } - }); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(); - - d.cacheDir({ - "foo": "1.2.3" - }).validate(); - d.packagesDir({ - "foo": "1.2.3" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/resolve_constraints_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/resolve_constraints_test.dart deleted file mode 100644 index 0fc93c5d082..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/resolve_constraints_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('resolves version constraints from a pub server', () { - servePackages((builder) { - builder.serve("foo", "1.2.3", deps: { - "baz": ">=2.0.0" - }); - builder.serve("bar", "2.3.4", deps: { - "baz": "<3.0.0" - }); - builder.serve("baz", "2.0.3"); - builder.serve("baz", "2.0.4"); - builder.serve("baz", "3.0.1"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubGet(); - - d.cacheDir({ - "foo": "1.2.3", - "bar": "2.3.4", - "baz": "2.0.4" - }).validate(); - - d.packagesDir({ - "foo": "1.2.3", - "bar": "2.3.4", - "baz": "2.0.4" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_compatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_compatible_test.dart deleted file mode 100644 index a5915b0b161..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_compatible_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't upgrade a locked pub server package with a new " - "compatible constraint", - () { - servePackages((builder) => builder.serve("foo", "1.0.0")); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0" - }).validate(); - - servePackages((builder) => builder.serve("foo", "1.0.1")); - - d.appDir({ - "foo": ">=1.0.0" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_new_is_satisfied_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_new_is_satisfied_test.dart deleted file mode 100644 index e35d0c1e930..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_if_new_is_satisfied_test.dart +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't unlock dependencies if a new dependency is already " "satisfied", - () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "bar": "<2.0.0" - }); - builder.serve("bar", "1.0.0", deps: { - "baz": "<2.0.0" - }); - builder.serve("baz", "1.0.0"); - }); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0", - "baz": "1.0.0" - }).validate(); - - servePackages((builder) { - builder.serve("foo", "2.0.0", deps: { - "bar": "<3.0.0" - }); - builder.serve("bar", "2.0.0", deps: { - "baz": "<3.0.0" - }); - builder.serve("baz", "2.0.0"); - builder.serve("newdep", "2.0.0", deps: { - "baz": ">=1.0.0" - }); - }); - - d.appDir({ - "foo": "any", - "newdep": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0", - "baz": "1.0.0", - "newdep": "2.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_test.dart deleted file mode 100644 index befc73a81b4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/stay_locked_test.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'keeps a pub server package locked to the version in the ' 'lockfile', - () { - servePackages((builder) => builder.serve("foo", "1.0.0")); - - d.appDir({ - "foo": "any" - }).create(); - - // This should lock the foo dependency to version 1.0.0. - pubGet(); - - d.packagesDir({ - "foo": "1.0.0" - }).validate(); - - // Delete the packages path to simulate a new checkout of the application. - schedule(() => deleteEntry(path.join(sandboxDir, packagesPath))); - - // Start serving a newer package as well. - servePackages((builder) => builder.serve("foo", "1.0.1")); - - // This shouldn't upgrade the foo dependency due to the lockfile. - pubGet(); - - d.packagesDir({ - "foo": "1.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_incompatible_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_incompatible_test.dart deleted file mode 100644 index d1c2f2131ca..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_incompatible_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'upgrades a locked pub server package with a new incompatible ' 'constraint', - () { - servePackages((builder) => builder.serve("foo", "1.0.0")); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0" - }).validate(); - servePackages((builder) => builder.serve("foo", "1.0.1")); - d.appDir({ - "foo": ">1.0.0" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.1" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_new_is_unsatisfied_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_new_is_unsatisfied_test.dart deleted file mode 100644 index dc58adcfad1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_new_is_unsatisfied_test.dart +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "unlocks dependencies if necessary to ensure that a new " - "dependency is satisfied", - () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "bar": "<2.0.0" - }); - builder.serve("bar", "1.0.0", deps: { - "baz": "<2.0.0" - }); - builder.serve("baz", "1.0.0", deps: { - "qux": "<2.0.0" - }); - builder.serve("qux", "1.0.0"); - }); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0", - "baz": "1.0.0", - "qux": "1.0.0" - }).validate(); - - servePackages((builder) { - builder.serve("foo", "2.0.0", deps: { - "bar": "<3.0.0" - }); - builder.serve("bar", "2.0.0", deps: { - "baz": "<3.0.0" - }); - builder.serve("baz", "2.0.0", deps: { - "qux": "<3.0.0" - }); - builder.serve("qux", "2.0.0"); - builder.serve("newdep", "2.0.0", deps: { - "baz": ">=1.5.0" - }); - }); - - d.appDir({ - "foo": "any", - "newdep": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "2.0.0", - "bar": "2.0.0", - "baz": "2.0.0", - "qux": "1.0.0", - "newdep": "2.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_version_doesnt_exist_test.dart b/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_version_doesnt_exist_test.dart deleted file mode 100644 index 76ba6a26743..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/hosted/unlock_if_version_doesnt_exist_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - 'upgrades a locked pub server package with a nonexistent version', - () { - servePackages((builder) => builder.serve("foo", "1.0.0")); - - d.appDir({ - "foo": "any" - }).create(); - pubGet(); - d.packagesDir({ - "foo": "1.0.0" - }).validate(); - - schedule(() => deleteEntry(p.join(sandboxDir, cachePath))); - - servePackages((builder) => builder.serve("foo", "1.0.1"), replace: true); - pubGet(); - d.packagesDir({ - "foo": "1.0.1" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/absolute_path_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/absolute_path_test.dart deleted file mode 100644 index 2f0a0f32c8e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/absolute_path_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('path dependency with absolute path', () { - d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": path.join(sandboxDir, "foo") - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate(); - - // Move the packages directory and ensure the symlink still works. That - // will validate that we actually created an absolute symlink. - d.dir("moved").create(); - scheduleRename(packagesPath, "moved/packages"); - - d.dir( - "moved/packages", - [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/absolute_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/absolute_symlink_test.dart deleted file mode 100644 index 82a2336323e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/absolute_symlink_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "generates a symlink with an absolute path if the dependency " - "path was absolute", - () { - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": path.join(sandboxDir, "foo") - } - })]).create(); - - pubGet(); - - d.dir("moved").create(); - - // Move the app but not the package. Since the symlink is absolute, it - // should still be able to find it. - scheduleRename(appPath, path.join("moved", appPath)); - - d.dir( - "moved", - [ - d.dir( - packagesPath, - [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/empty_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/empty_pubspec_test.dart deleted file mode 100644 index 4c3c78f7f42..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/empty_pubspec_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - // Regression test for issue 20103. - integration('path dependency to an empty pubspec', () { - d.dir('foo', [d.libDir('foo'), d.file('pubspec.yaml', '')]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet( - exitCode: exit_codes.DATA, - error: 'Error on line 1, column 1 of ${p.join('..', 'foo', 'pubspec.yaml')}: ' - 'Missing the required "name" field.'); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/no_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/no_pubspec_test.dart deleted file mode 100644 index 5e0ae1e6fad..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/no_pubspec_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('path dependency to non-package directory', () { - // Make an empty directory. - d.dir('foo').create(); - var fooPath = path.join(sandboxDir, "foo"); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": fooPath - } - })]).create(); - - pubGet( - error: new RegExp( - r'Could not find a file named "pubspec.yaml" ' r'in "[^\n]*"\.')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/nonexistent_dir_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/nonexistent_dir_test.dart deleted file mode 100644 index 8496cba3399..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/nonexistent_dir_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('path dependency to non-existent directory', () { - var badPath = path.join(sandboxDir, "bad_path"); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": badPath - } - })]).create(); - - pubGet(error: """ - Could not find package foo at "$badPath". - Depended on by: - - myapp 0.0.0""", exitCode: exit_codes.UNAVAILABLE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/path_is_file_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/path_is_file_test.dart deleted file mode 100644 index d88df0fd3a7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/path_is_file_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('path dependency when path is a file', () { - d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create(); - - d.file('dummy.txt', '').create(); - var dummyPath = path.join(sandboxDir, 'dummy.txt'); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": dummyPath - } - })]).create(); - - pubGet( - error: 'Path dependency for package foo must refer to a ' - 'directory, not a file. Was "$dummyPath".'); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/relative_path_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/relative_path_test.dart deleted file mode 100644 index b5f2a143a85..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/relative_path_test.dart +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:unittest/unittest.dart'; - -import '../../../lib/src/lock_file.dart'; -import '../../../lib/src/source_registry.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("can use relative path", () { - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate(); - }); - - integration("path is relative to containing d.pubspec", () { - d.dir( - "relative", - [d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: { - "bar": { - "path": "../bar" - } - })]), - d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../relative/foo" - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.dir("bar", [d.file("bar.dart", 'main() => "bar";')])]).validate(); - }); - - integration("relative path preserved in the lockfile", () { - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet(); - - schedule(() { - var lockfilePath = path.join(sandboxDir, appPath, "pubspec.lock"); - var lockfile = new LockFile.load(lockfilePath, new SourceRegistry()); - var description = lockfile.packages["foo"].description; - - expect(path.isRelative(description["path"]), isTrue); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/relative_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/relative_symlink_test.dart deleted file mode 100644 index f5ec3a3941a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/relative_symlink_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'dart:io'; - -import 'package:path/path.dart' as path; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - // Pub uses NTFS junction points to create links in the packages directory. - // These (unlike the symlinks that are supported in Vista and later) do not - // support relative paths. So this test, by design, will not pass on Windows. - // So just skip it. - if (Platform.operatingSystem == "windows") return; - - initConfig(); - integration( - "generates a symlink with a relative path if the dependency " - "path was relative", - () { - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet(); - - d.dir("moved").create(); - - // Move the app and package. Since they are still next to each other, it - // should still be found. - scheduleRename("foo", path.join("moved", "foo")); - scheduleRename(appPath, path.join("moved", appPath)); - - d.dir( - "moved", - [ - d.dir( - packagesPath, - [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_symlink_test.dart deleted file mode 100644 index f5cb84bed3f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_symlink_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("shared dependency with symlink", () { - d.dir( - "shared", - [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create(); - - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: { - "shared": { - "path": "../shared" - } - })]).create(); - - d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: { - "shared": { - "path": "../link/shared" - } - })]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - }, - "bar": { - "path": "../bar" - } - })]).create(); - - d.dir("link").create(); - scheduleSymlink("shared", path.join("link", "shared")); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]), - d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_test.dart deleted file mode 100644 index 951676543a8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/path/shared_dependency_test.dart +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("shared dependency with same path", () { - d.dir( - "shared", - [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create(); - - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: { - "shared": { - "path": "../shared" - } - })]).create(); - - d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: { - "shared": { - "path": "../shared" - } - })]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - }, - "bar": { - "path": "../bar" - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]), - d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate(); - }); - - integration("shared dependency with paths that normalize the same", () { - d.dir( - "shared", - [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create(); - - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: { - "shared": { - "path": "../shared" - } - })]).create(); - - d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: { - "shared": { - "path": "../././shared" - } - })]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - }, - "bar": { - "path": "../bar" - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]), - d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate(); - }); - - integration("shared dependency with absolute and relative path", () { - d.dir( - "shared", - [d.libDir("shared"), d.libPubspec("shared", "0.0.1")]).create(); - - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1", deps: { - "shared": { - "path": "../shared" - } - })]).create(); - - d.dir("bar", [d.libDir("bar"), d.libPubspec("bar", "0.0.1", deps: { - "shared": { - "path": path.join(sandboxDir, "shared") - } - })]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - }, - "bar": { - "path": "../bar" - } - })]).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir("foo", [d.file("foo.dart", 'main() => "foo";')]), - d.dir("bar", [d.file("bar.dart", 'main() => "bar";')]), - d.dir("shared", [d.file("shared.dart", 'main() => "shared";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/relative_symlink_test.dart b/sdk/lib/_internal/pub_generated/test/get/relative_symlink_test.dart deleted file mode 100644 index a413c3aec5a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/relative_symlink_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:io'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - // Pub uses NTFS junction points to create links in the packages directory. - // These (unlike the symlinks that are supported in Vista and later) do not - // support relative paths. So this test, by design, will not pass on Windows. - // So just skip it. - if (Platform.operatingSystem == "windows") return; - - initConfig(); - integration('uses a relative symlink for the self link', () { - d.dir(appPath, [d.appPubspec(), d.libDir('foo')]).create(); - - pubGet(); - - scheduleRename(appPath, "moved"); - - d.dir( - "moved", - [ - d.dir( - "packages", - [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])]).validate(); - }); - - integration('uses a relative symlink for secondary packages directory', () { - d.dir(appPath, [d.appPubspec(), d.libDir('foo'), d.dir("bin")]).create(); - - pubGet(); - - scheduleRename(appPath, "moved"); - - d.dir( - "moved", - [ - d.dir( - "bin", - [ - d.dir( - "packages", - [d.dir("myapp", [d.file('foo.dart', 'main() => "foo";')])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/get/switch_source_test.dart b/sdk/lib/_internal/pub_generated/test/get/switch_source_test.dart deleted file mode 100644 index 4ddee5c068b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/get/switch_source_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('re-gets a package if its source has changed', () { - servePackages((builder) => builder.serve("foo", "1.2.3")); - - d.dir( - 'foo', - [d.libDir('foo', 'foo 0.0.1'), d.libPubspec('foo', '0.0.1')]).create(); - - d.appDir({ - "foo": { - "path": "../foo" - } - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "0.0.1" - }).validate(); - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.2.3" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_git_after_hosted_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_git_after_hosted_test.dart deleted file mode 100644 index 6be9b071ab1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_git_after_hosted_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activating a Git package deactivates the hosted one', () { - ensureGit(); - - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]); - }); - - d.git( - 'foo.git', - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('git');")])]).create(); - - schedulePub(args: ["global", "activate", "foo"]); - - schedulePub( - args: ["global", "activate", "-sgit", "../foo.git"], - output: allOf( - startsWith( - 'Package foo is currently active at version 1.0.0.\n' - 'Resolving dependencies...\n' '+ foo 1.0.0 from git ../foo.git at '), - // Specific revision number goes here. - endsWith( - 'Precompiling executables...\n' 'Loading source assets...\n' - 'Precompiled foo:foo.\n' - 'Activated foo 1.0.0 from Git repository "../foo.git".'))); - - // Should now run the git one. - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("git"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_git_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_git_test.dart deleted file mode 100644 index 29d56b4589c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_git_test.dart +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activating a hosted package deactivates the Git one', () { - servePackages((builder) { - builder.serve( - "foo", - "2.0.0", - contents: [ - d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]); - }); - - d.git( - 'foo.git', - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('git');")])]).create(); - - schedulePub(args: ["global", "activate", "-sgit", "../foo.git"]); - - var path = canonicalize(p.join(sandboxDir, "foo")); - schedulePub(args: ["global", "activate", "foo"], output: """ - Package foo is currently active from Git repository "../foo.git". - Resolving dependencies... - + foo 2.0.0 - Downloading foo 2.0.0... - Precompiling executables... - Loading source assets... - Precompiled foo:foo. - Activated foo 2.0.0."""); - - // Should now run the hosted one. - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("hosted"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_path_test.dart deleted file mode 100644 index 05e2d79a083..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_hosted_after_path_test.dart +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activating a hosted package deactivates the path one', () { - servePackages((builder) { - builder.serve( - "foo", - "2.0.0", - contents: [ - d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]); - }); - - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('path');")])]).create(); - - schedulePub(args: ["global", "activate", "-spath", "../foo"]); - - var path = canonicalize(p.join(sandboxDir, "foo")); - schedulePub(args: ["global", "activate", "foo"], output: """ - Package foo is currently active at path "$path". - Resolving dependencies... - + foo 2.0.0 - Downloading foo 2.0.0... - Precompiling executables... - Loading source assets... - Precompiled foo:foo. - Activated foo 2.0.0."""); - - // Should now run the hosted one. - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("hosted"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/activate_path_after_hosted_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/activate_path_after_hosted_test.dart deleted file mode 100644 index 50d077ef6d1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/activate_path_after_hosted_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activating a hosted package deactivates the path one', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("bin", [d.file("foo.dart", "main(args) => print('hosted');")])]); - }); - - d.dir( - "foo", - [ - d.libPubspec("foo", "2.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('path');")])]).create(); - - schedulePub(args: ["global", "activate", "foo"]); - - var path = canonicalize(p.join(sandboxDir, "foo")); - schedulePub(args: ["global", "activate", "-spath", "../foo"], output: """ - Package foo is currently active at version 1.0.0. - Activated foo 2.0.0 at path "$path"."""); - - // Should now run the path one. - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("path"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/bad_version_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/bad_version_test.dart deleted file mode 100644 index d915658bd5f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/bad_version_test.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if the version constraint cannot be parsed', () { - schedulePub( - args: ["global", "activate", "foo", "1.0"], - error: contains('Could not parse version "1.0". Unknown text at "1.0".'), - exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/cached_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/cached_package_test.dart deleted file mode 100644 index e3a1f83f40d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/cached_package_test.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('can activate an already cached package', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - }); - - schedulePub(args: ["cache", "add", "foo"]); - - schedulePub(args: ["global", "activate", "foo"], output: """ - Resolving dependencies... - + foo 1.0.0 - Precompiling executables... - Loading source assets... - Activated foo 1.0.0."""); - - // Should be in global package cache. - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.0'))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/constraint_test.dart deleted file mode 100644 index c4a07839908..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('chooses the highest version that matches the constraint', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "1.0.1"); - builder.serve("foo", "1.1.0"); - builder.serve("foo", "1.2.3"); - }); - - schedulePub(args: ["global", "activate", "foo", "<1.1.0"]); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.1'))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_with_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/constraint_with_path_test.dart deleted file mode 100644 index 91de56f7eeb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/constraint_with_path_test.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if a version is passed with the path source', () { - schedulePub( - args: ["global", "activate", "-spath", "foo", "1.2.3"], - error: contains('Unexpected argument "1.2.3".'), - exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/different_version_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/different_version_test.dart deleted file mode 100644 index 3c4b9fcdc83..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/different_version_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "discards the previous active version if it doesn't match the " "constraint", - () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "2.0.0"); - }); - - // Activate 1.0.0. - schedulePub(args: ["global", "activate", "foo", "1.0.0"]); - - // Activating it again with a different constraint changes the version. - schedulePub(args: ["global", "activate", "foo", ">1.0.0"], output: """ - Package foo is currently active at version 1.0.0. - Resolving dependencies... - + foo 2.0.0 - Downloading foo 2.0.0... - Precompiling executables... - Loading source assets... - Activated foo 2.0.0."""); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/doesnt_snapshot_path_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/doesnt_snapshot_path_executables_test.dart deleted file mode 100644 index 4ee9c7b15f2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/doesnt_snapshot_path_executables_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("doesn't snapshots the executables for a path package", () { - d.dir( - 'foo', - [ - d.libPubspec("foo", "1.0.0"), - d.dir( - "bin", - [d.file("hello.dart", "void main() => print('hello!');")])]).create(); - - schedulePub( - args: ["global", "activate", "-spath", "../foo"], - output: isNot(contains('Precompiled foo:hello.'))); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir( - 'foo', - [ - d.matcherFile('pubspec.lock', contains('1.0.0')), - d.nothing('bin')])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/empty_constraint_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/empty_constraint_test.dart deleted file mode 100644 index 38302fb41ac..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/empty_constraint_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('errors if the constraint matches no versions', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "1.0.1"); - }); - - schedulePub(args: ["global", "activate", "foo", ">1.1.0"], error: """ - Package foo has no versions that match >1.1.0 derived from: - - pub global activate depends on version >1.1.0""", - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/git_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/git_package_test.dart deleted file mode 100644 index 2239576e278..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/git_package_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activates a package from a Git repo', () { - ensureGit(); - - d.git( - 'foo.git', - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub( - args: ["global", "activate", "-sgit", "../foo.git"], - output: allOf( - startsWith('Resolving dependencies...\n' '+ foo 1.0.0 from git ../foo.git at '), - // Specific revision number goes here. - endsWith( - 'Precompiling executables...\n' 'Loading source assets...\n' - 'Precompiled foo:foo.\n' - 'Activated foo 1.0.0 from Git repository "../foo.git".'))); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/ignores_active_version_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/ignores_active_version_test.dart deleted file mode 100644 index 50f8ec907f9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/ignores_active_version_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('ignores previously activated version', () { - servePackages((builder) { - builder.serve("foo", "1.2.3"); - builder.serve("foo", "1.3.0"); - }); - - // Activate 1.2.3. - schedulePub(args: ["global", "activate", "foo", "1.2.3"]); - - // Activating it again resolves to the new best version. - schedulePub(args: ["global", "activate", "foo", ">1.0.0"], output: """ - Package foo is currently active at version 1.2.3. - Resolving dependencies... - + foo 1.3.0 - Downloading foo 1.3.0... - Precompiling executables... - Loading source assets... - Activated foo 1.3.0."""); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_git_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_git_test.dart deleted file mode 100644 index 6bebaf46b4b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_git_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activating a Git package installs its dependencies', () { - servePackages((builder) { - builder.serve("bar", "1.0.0", deps: { - "baz": "any" - }); - builder.serve("baz", "1.0.0"); - }); - - d.git('foo.git', [d.libPubspec("foo", "1.0.0", deps: { - "bar": "any" - }), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub( - args: ["global", "activate", "-sgit", "../foo.git"], - output: allOf( - [contains("Downloading bar 1.0.0..."), contains("Downloading baz 1.0.0...")])); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_path_test.dart deleted file mode 100644 index 151ae8693d3..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_for_path_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activating a path package installs dependencies', () { - servePackages((builder) { - builder.serve("bar", "1.0.0", deps: { - "baz": "any" - }); - builder.serve("baz", "2.0.0"); - }); - - d.dir("foo", [d.libPubspec("foo", "0.0.0", deps: { - "bar": "any" - }), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - var pub = startPub(args: ["global", "activate", "-spath", "../foo"]); - pub.stdout.expect(consumeThrough("Resolving dependencies...")); - pub.stdout.expect(consumeThrough("Downloading bar 1.0.0...")); - pub.stdout.expect(consumeThrough("Downloading baz 2.0.0...")); - pub.stdout.expect( - consumeThrough(startsWith("Activated foo 0.0.0 at path"))); - pub.shouldExit(); - - // Puts the lockfile in the linked package itself. - d.dir( - "foo", - [ - d.matcherFile( - "pubspec.lock", - allOf( - [ - contains("bar"), - contains("1.0.0"), - contains("baz"), - contains("2.0.0")]))]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_test.dart deleted file mode 100644 index f3bc479a415..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/installs_dependencies_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activating a package installs its dependencies', () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "bar": "any" - }); - builder.serve("bar", "1.0.0", deps: { - "baz": "any" - }); - builder.serve("baz", "1.0.0"); - }); - - schedulePub( - args: ["global", "activate", "foo"], - output: allOf( - [contains("Downloading bar 1.0.0..."), contains("Downloading baz 1.0.0...")])); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/missing_git_repo_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/missing_git_repo_test.dart deleted file mode 100644 index 4da5970ca9c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/missing_git_repo_test.dart +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if the Git repo does not exist', () { - ensureGit(); - - schedulePub( - args: ["global", "activate", "-sgit", "../nope.git"], - error: contains("repository '../nope.git' does not exist"), - exitCode: 1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/missing_package_arg_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/missing_package_arg_test.dart deleted file mode 100644 index 965a6dff0a9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/missing_package_arg_test.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if no package was given', () { - schedulePub( - args: ["global", "activate"], - error: contains("No package to activate given."), - exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/outdated_binstub_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/outdated_binstub_test.dart deleted file mode 100644 index 65fd10b80a1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/outdated_binstub_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; -import 'dart:async'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -const _OUTDATED_BINSTUB = """ -#!/usr/bin/env sh -# This file was created by pub v0.1.2-3. -# Package: foo -# Version: 1.0.0 -# Executable: foo-script -# Script: script -dart "/path/to/.pub-cache/global_packages/foo/bin/script.dart.snapshot" "\$@" -"""; - -main() { - initConfig(); - integration("an outdated binstub is replaced", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "foo-script": "script" - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir('bin', [d.file(binStubName('foo-script'), _OUTDATED_BINSTUB)])]).create(); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [d.dir('bin', [// 255 is the VM's exit code upon seeing an out-of-date snapshot. - d.matcherFile( - binStubName('foo-script'), - contains("255"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/path_package_test.dart deleted file mode 100644 index 8d273c914da..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/path_package_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activates a package at a local path', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - var path = canonicalize(p.join(sandboxDir, "foo")); - schedulePub( - args: ["global", "activate", "--source", "path", "../foo"], - output: 'Activated foo 1.0.0 at path "$path".'); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/reactivating_git_upgrades_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/reactivating_git_upgrades_test.dart deleted file mode 100644 index 18b682939e2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/reactivating_git_upgrades_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('ignores previously activated git commit', () { - ensureGit(); - - d.git('foo.git', [d.libPubspec("foo", "1.0.0")]).create(); - - schedulePub( - args: ["global", "activate", "-sgit", "../foo.git"], - output: allOf( - startsWith('Resolving dependencies...\n' '+ foo 1.0.0 from git ../foo.git at '), - // Specific revision number goes here. - endsWith( - 'Precompiling executables...\n' 'Loading source assets...\n' - 'Activated foo 1.0.0 from Git repository "../foo.git".'))); - - d.git('foo.git', [d.libPubspec("foo", "1.0.1")]).commit(); - - // Activating it again pulls down the latest commit. - schedulePub( - args: ["global", "activate", "-sgit", "../foo.git"], - output: allOf( - startsWith( - 'Package foo is currently active from Git repository ' '"../foo.git".\n' - 'Resolving dependencies...\n' '+ foo 1.0.1 from git ../foo.git at '), - // Specific revision number goes here. - endsWith( - 'Precompiling executables...\n' 'Loading source assets...\n' - 'Activated foo 1.0.1 from Git repository "../foo.git".'))); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/removes_old_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/removes_old_lockfile_test.dart deleted file mode 100644 index a9ff5c927d7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/removes_old_lockfile_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('removes the 1.6-style lockfile', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - }); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.file( - 'foo.lock', - 'packages: {foo: {description: foo, source: hosted, ' - 'version: "1.0.0"}}}')])]).create(); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.nothing('foo.lock'), - d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.0'))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_git_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_git_executables_test.dart deleted file mode 100644 index c6b2633bf39..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_git_executables_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('snapshots the executables for a Git repo', () { - ensureGit(); - - d.git( - 'foo.git', - [ - d.libPubspec("foo", "1.0.0"), - d.dir( - "bin", - [ - d.file("hello.dart", "void main() => print('hello!');"), - d.file("goodbye.dart", "void main() => print('goodbye!');"), - d.file("shell.sh", "echo shell"), - d.dir( - "subdir", - [d.file("sub.dart", "void main() => print('sub!');")])])]).create(); - - schedulePub( - args: ["global", "activate", "-sgit", "../foo.git"], - output: allOf( - [contains('Precompiled foo:hello.'), contains("Precompiled foo:goodbye.")])); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir( - 'foo', - [ - d.matcherFile('pubspec.lock', contains('1.0.0')), - d.dir( - 'bin', - [ - d.matcherFile('hello.dart.snapshot', contains('hello!')), - d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')), - d.nothing('shell.sh.snapshot'), - d.nothing('subdir')])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_hosted_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_hosted_executables_test.dart deleted file mode 100644 index 254036e9fcc..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/snapshots_hosted_executables_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('snapshots the executables for a hosted package', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir( - 'bin', - [ - d.file("hello.dart", "void main() => print('hello!');"), - d.file("goodbye.dart", "void main() => print('goodbye!');"), - d.file("shell.sh", "echo shell"), - d.dir("subdir", [d.file("sub.dart", "void main() => print('sub!');")])])]); - }); - - schedulePub( - args: ["global", "activate", "foo"], - output: allOf( - [contains('Precompiled foo:hello.'), contains("Precompiled foo:goodbye.")])); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir( - 'foo', - [ - d.matcherFile('pubspec.lock', contains('1.0.0')), - d.dir( - 'bin', - [ - d.matcherFile('hello.dart.snapshot', contains('hello!')), - d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')), - d.nothing('shell.sh.snapshot'), - d.nothing('subdir')])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/supports_version_solver_backtracking_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/supports_version_solver_backtracking_test.dart deleted file mode 100644 index 1d75605802b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/supports_version_solver_backtracking_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('performs verison solver backtracking if necessary', () { - servePackages((builder) { - builder.serve("foo", "1.1.0", pubspec: { - "environment": { - "sdk": ">=0.1.2 <0.2.0" - } - }); - builder.serve("foo", "1.2.0", pubspec: { - "environment": { - "sdk": ">=0.1.3 <0.2.0" - } - }); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - // foo 1.2.0 won't be picked because its SDK constraint conflicts with the - // dummy SDK version 0.1.2+3. - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.1.0'))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/uncached_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/uncached_package_test.dart deleted file mode 100644 index aa5d456bc68..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/uncached_package_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('installs and activates the best version of a package', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "1.2.3"); - builder.serve("foo", "2.0.0-wildly.unstable"); - }); - - schedulePub(args: ["global", "activate", "foo"], output: """ - Resolving dependencies... - + foo 1.2.3 (2.0.0-wildly.unstable available) - Downloading foo 1.2.3... - Precompiling executables... - Loading source assets... - Activated foo 1.2.3."""); - - // Should be in global package cache. - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.2.3'))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/unexpected_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/unexpected_arguments_test.dart deleted file mode 100644 index a62f356f217..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/unexpected_arguments_test.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if there are extra arguments', () { - schedulePub( - args: ["global", "activate", "foo", "1.0.0", "bar", "baz"], - error: contains('Unexpected arguments "bar" and "baz".'), - exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/activate/unknown_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/activate/unknown_package_test.dart deleted file mode 100644 index d0bc786c942..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/activate/unknown_package_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('errors if the package could not be found', () { - serveNoPackages(); - - schedulePub( - args: ["global", "activate", "foo"], - error: startsWith("Could not find package foo at"), - exitCode: exit_codes.UNAVAILABLE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_executable_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_executable_test.dart deleted file mode 100644 index 314c2e5a85b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_executable_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("the generated binstub runs a snapshotted executable", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "foo-script": "script" - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - var process = new ScheduledProcess.start( - p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")), - ["arg1", "arg2"], - environment: getEnvironment()); - - process.stdout.expect("ok [arg1, arg2]"); - process.shouldExit(); - }); - - integration("the generated binstub runs a non-snapshotted executable", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "foo-script": "script" - } - }), - d.dir( - "bin", - [d.file("script.dart", "main(args) => print('ok \$args');")])]).create(); - - schedulePub(args: ["global", "activate", "-spath", "../foo"]); - - var process = new ScheduledProcess.start( - p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")), - ["arg1", "arg2"], - environment: getEnvironment()); - - process.stdout.expect("ok [arg1, arg2]"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_global_run_if_no_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_global_run_if_no_snapshot_test.dart deleted file mode 100644 index 8b2bf6faf77..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_global_run_if_no_snapshot_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("the binstubs runs pub global run if there is no snapshot", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "foo-script": "script" - } - }), - d.dir("bin", [d.file("script.dart", "main() => print('ok');")])]).create(); - - // Path packages are mutable, so no snapshot is created. - schedulePub( - args: ["global", "activate", "--source", "path", "../foo"], - output: contains("Installed executable foo-script.")); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.matcherFile( - binStubName("foo-script"), - contains("pub global run foo:script"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_precompiled_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_precompiled_snapshot_test.dart deleted file mode 100644 index 1a2115c8141..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/binstub_runs_precompiled_snapshot_test.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("the binstubs runs a precompiled snapshot if present", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "foo-script": "script" - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.matcherFile( - binStubName("foo-script"), - contains("script.dart.snapshot"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/creates_executables_in_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/creates_executables_in_pubspec_test.dart deleted file mode 100644 index 04aaa966613..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/creates_executables_in_pubspec_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("creates binstubs for each executable in the pubspec", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "one": null, - "two-renamed": "second" - } - }, - contents: [ - d.dir( - "bin", - [ - d.file("one.dart", "main(args) => print('one');"), - d.file("second.dart", "main(args) => print('two');"), - d.file("nope.dart", "main(args) => print('nope');")])]); - }); - - schedulePub( - args: ["global", "activate", "foo"], - output: contains("Installed executables one and two-renamed.")); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.matcherFile(binStubName("one"), contains("one")), - d.matcherFile(binStubName("two-renamed"), contains("second")), - d.nothing(binStubName("two")), - d.nothing(binStubName("nope"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_no_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_no_executables_test.dart deleted file mode 100644 index ac6348a1d67..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_no_executables_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("does not warn if the package has no executables", () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]); - }); - - schedulePub( - args: ["global", "activate", "foo"], - output: isNot(contains("is not on your path"))); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_on_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_on_path_test.dart deleted file mode 100644 index 648519cfb3a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/does_not_warn_if_on_path_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("does not warn if the binstub directory is on the path", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "script": null - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]); - }); - - // Add the test's cache bin directory to the path. - var binDir = p.dirname(Platform.executable); - var separator = Platform.operatingSystem == "windows" ? ";" : ":"; - var path = "${Platform.environment["PATH"]}$separator$binDir"; - - schedulePub( - args: ["global", "activate", "foo"], - output: isNot(contains("is not on your path")), - environment: { - "PATH": path - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_and_no_executables_options_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_and_no_executables_options_test.dart deleted file mode 100644 index d93ed56291c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_and_no_executables_options_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("errors if -x and --no-executables are both passed", () { - d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create(); - - schedulePub( - args: [ - "global", - "activate", - "--source", - "path", - "../foo", - "-x", - "anything", - "--no-executables"], - error: contains("Cannot pass both --no-executables and --executable."), - exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_executables_test.dart deleted file mode 100644 index ffac2593ccc..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/explicit_executables_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("only creates binstubs for the listed executables", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "one": "script", - "two": "script", - "three": "script" - } - }), - d.dir("bin", [d.file("script.dart", "main() => print('ok');")])]).create(); - - schedulePub( - args: [ - "global", - "activate", - "--source", - "path", - "../foo", - "-x", - "one", - "--executable", - "three"], - output: contains("Installed executables one and three.")); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.matcherFile(binStubName("one"), contains("pub global run foo:script")), - d.nothing(binStubName("two")), - d.matcherFile( - binStubName("three"), - contains("pub global run foo:script"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/missing_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/missing_script_test.dart deleted file mode 100644 index c8b617adeec..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/missing_script_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("errors if an executable's script can't be found", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "missing": "not_here", - "nope": null - } - })]).create(); - - var pub = startPub(args: ["global", "activate", "-spath", "../foo"]); - - pub.stderr.expect( - 'Warning: Executable "missing" runs ' - '"${p.join('bin', 'not_here.dart')}", which was not found in foo.'); - pub.stderr.expect( - 'Warning: Executable "nope" runs ' - '"${p.join('bin', 'nope.dart')}", which was not found in foo.'); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_test.dart deleted file mode 100644 index 4667065ebfb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("does not overwrite an existing binstub", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "foo": "foo", - "collide1": "foo", - "collide2": "foo" - } - }), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - d.dir("bar", [d.pubspec({ - "name": "bar", - "executables": { - "bar": "bar", - "collide1": "bar", - "collide2": "bar" - } - }), - d.dir("bin", [d.file("bar.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "-spath", "../foo"]); - - var pub = startPub(args: ["global", "activate", "-spath", "../bar"]); - pub.stdout.expect(consumeThrough("Installed executable bar.")); - pub.stderr.expect("Executable collide1 was already installed from foo."); - pub.stderr.expect("Executable collide2 was already installed from foo."); - pub.stderr.expect( - "Deactivate the other package(s) or activate bar using " "--overwrite."); - pub.shouldExit(); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.matcherFile(binStubName("foo"), contains("foo:foo")), - d.matcherFile(binStubName("bar"), contains("bar:bar")), - d.matcherFile(binStubName("collide1"), contains("foo:foo")), - d.matcherFile(binStubName("collide2"), contains("foo:foo"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_with_overwrite_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_with_overwrite_test.dart deleted file mode 100644 index a868a24639f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/name_collision_with_overwrite_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("overwrites an existing binstub if --overwrite is passed", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "foo": "foo", - "collide1": "foo", - "collide2": "foo" - } - }), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - d.dir("bar", [d.pubspec({ - "name": "bar", - "executables": { - "bar": "bar", - "collide1": "bar", - "collide2": "bar" - } - }), - d.dir("bin", [d.file("bar.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "-spath", "../foo"]); - - var pub = - startPub(args: ["global", "activate", "-spath", "../bar", "--overwrite"]); - pub.stdout.expect( - consumeThrough("Installed executables bar, collide1 and collide2.")); - pub.stderr.expect("Replaced collide1 previously installed from foo."); - pub.stderr.expect("Replaced collide2 previously installed from foo."); - pub.shouldExit(); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.matcherFile(binStubName("foo"), contains("foo:foo")), - d.matcherFile(binStubName("bar"), contains("bar:bar")), - d.matcherFile(binStubName("collide1"), contains("bar:bar")), - d.matcherFile(binStubName("collide2"), contains("bar:bar"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/no_executables_flag_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/no_executables_flag_test.dart deleted file mode 100644 index 050868ead9a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/no_executables_flag_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("does not create binstubs if --no-executables is passed", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "one": null - } - }), - d.dir("bin", [d.file("one.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - schedulePub( - args: ["global", "activate", "--source", "path", "../foo", "--no-executables"]); - - // Should still delete old one. - d.dir( - cachePath, - [d.dir("bin", [d.nothing(binStubName("one"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_binstub_runs_pub_global_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_binstub_runs_pub_global_test.dart deleted file mode 100644 index 48da7f985e0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_binstub_runs_pub_global_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("an outdated binstub runs 'pub global run'", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "foo-script": "script" - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir( - 'foo', - [d.dir('bin', [d.outOfDateSnapshot('script.dart.snapshot')])])])]).create(); - - var process = new ScheduledProcess.start( - p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")), - ["arg1", "arg2"], - environment: getEnvironment()); - - process.stdout.expect(consumeThrough("ok")); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_snapshot_test.dart deleted file mode 100644 index 28da4f58d71..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/outdated_snapshot_test.dart +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("a binstub runs 'pub global run' for an outdated snapshot", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "foo-script": "script" - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir( - 'foo', - [d.dir('bin', [d.outOfDateSnapshot('script.dart.snapshot')])])])]).create(); - - var process = new ScheduledProcess.start( - p.join(sandboxDir, cachePath, "bin", binStubName("foo-script")), - ["arg1", "arg2"], - environment: getEnvironment()); - - process.stderr.expect(startsWith("Wrong script snapshot version")); - process.stdout.expect(consumeThrough("ok [arg1, arg2]")); - process.shouldExit(); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages/foo/bin', - [ - d.binaryMatcherFile( - 'script.dart.snapshot', - isNot( - equals(readBinaryFile(testAssetPath('out-of-date.snapshot')))))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/path_package_test.dart deleted file mode 100644 index 49af05c16f9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/path_package_test.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("creates binstubs when activating a path package", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "foo": null - } - }), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub( - args: ["global", "activate", "--source", "path", "../foo"], - output: contains("Installed executable foo.")); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.matcherFile( - binStubName("foo"), - contains("pub global run foo:foo"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/reactivate_removes_old_executables_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/reactivate_removes_old_executables_test.dart deleted file mode 100644 index e6cf443eef2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/reactivate_removes_old_executables_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("removes previous binstubs when reactivating a package", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "one": null, - "two": null - } - }), - d.dir( - "bin", - [ - d.file("one.dart", "main() => print('ok');"), - d.file("two.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - // Remove "one". - "two": null - } - }),]).create(); - - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [ - d.nothing(binStubName("one")), - d.matcherFile(binStubName("two"), contains("two"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_even_if_not_in_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_even_if_not_in_pubspec_test.dart deleted file mode 100644 index 6c471b86719..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_even_if_not_in_pubspec_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("removes all binstubs for package", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "foo": null - } - }), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - // Create the binstub for foo. - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - // Remove it from the pubspec. - d.dir("foo", [d.pubspec({ - "name": "foo" - })]).create(); - - // Deactivate. - schedulePub(args: ["global", "deactivate", "foo"]); - - // It should still be deleted. - d.dir( - cachePath, - [d.dir("bin", [d.nothing(binStubName("foo"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_when_deactivated_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_when_deactivated_test.dart deleted file mode 100644 index 10bee756ced..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/removes_when_deactivated_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("removes binstubs when the package is deactivated", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "one": null, - "two": null - } - }, - contents: [ - d.dir( - "bin", - [ - d.file("one.dart", "main(args) => print('one');"), - d.file("two.dart", "main(args) => print('two');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - schedulePub(args: ["global", "deactivate", "foo"]); - - d.dir( - cachePath, - [ - d.dir( - "bin", - [d.nothing(binStubName("one")), d.nothing(binStubName("two"))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/unknown_explicit_executable_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/unknown_explicit_executable_test.dart deleted file mode 100644 index e272cb6c0cb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/unknown_explicit_executable_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("errors on an unknown explicit executable", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "executables": { - "one": "one" - } - }), - d.dir("bin", [d.file("one.dart", "main() => print('ok');")])]).create(); - - var pub = startPub( - args: [ - "global", - "activate", - "--source", - "path", - "../foo", - "-x", - "who", - "-x", - "one", - "--executable", - "wat"]); - - pub.stdout.expect(consumeThrough("Installed executable one.")); - pub.stderr.expect("Unknown executables wat and who."); - pub.shouldExit(exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/utils.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/utils.dart deleted file mode 100644 index bd2243f4a8c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/utils.dart +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:io'; - -import 'package:path/path.dart' as p; - -import '../../test_pub.dart'; - -/// The buildbots do not have the Dart SDK (containing "dart" and "pub") on -/// their PATH, so we need to spawn the binstub process with a PATH that -/// explicitly includes it. -Future getEnvironment() { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var binDir = p.dirname(Platform.executable); - join0(x0) { - var separator = x0; - var path = "${Platform.environment["PATH"]}${separator}${binDir}"; - new Future.value(getPubTestEnvironment()).then((x1) { - try { - var environment = x1; - environment["PATH"] = path; - completer0.complete(environment); - } catch (e0, s0) { - completer0.completeError(e0, s0); - } - }, onError: completer0.completeError); - } - if (Platform.operatingSystem == "windows") { - join0(";"); - } else { - join0(":"); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; -} diff --git a/sdk/lib/_internal/pub_generated/test/global/binstubs/warns_if_not_on_path_test.dart b/sdk/lib/_internal/pub_generated/test/global/binstubs/warns_if_not_on_path_test.dart deleted file mode 100644 index 8e8c19f83cd..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/binstubs/warns_if_not_on_path_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("warns if the binstub directory is not on the path", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", pubspec: { - "executables": { - "some-dart-script": "script" - } - }, - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok \$args');")])]); - }); - - schedulePub( - args: ["global", "activate", "foo"], - error: contains("is not on your path")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/deactivate_and_reactivate_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/deactivate_and_reactivate_package_test.dart deleted file mode 100644 index b9ea22a6be1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/deactivate_and_reactivate_package_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('activates a different version after deactivating', () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "2.0.0"); - }); - - // Activate an old version. - schedulePub(args: ["global", "activate", "foo", "1.0.0"]); - - schedulePub( - args: ["global", "deactivate", "foo"], - output: "Deactivated package foo 1.0.0."); - - // Activating again should forget the old version. - schedulePub(args: ["global", "activate", "foo"], output: """ - Resolving dependencies... - + foo 2.0.0 - Downloading foo 2.0.0... - Precompiling executables... - Loading source assets... - Activated foo 2.0.0."""); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/git_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/git_package_test.dart deleted file mode 100644 index 68725c7b629..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/git_package_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('deactivates an active Git package', () { - ensureGit(); - - d.git( - 'foo.git', - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "-sgit", "../foo.git"]); - - schedulePub( - args: ["global", "deactivate", "foo"], - output: 'Deactivated package foo 1.0.0 from Git repository "../foo.git".'); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/hosted_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/hosted_package_test.dart deleted file mode 100644 index ec8b985582b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/hosted_package_test.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('deactivates an active hosted package', () { - servePackages((builder) => builder.serve("foo", "1.0.0")); - - schedulePub(args: ["global", "activate", "foo"]); - - schedulePub( - args: ["global", "deactivate", "foo"], - output: "Deactivated package foo 1.0.0."); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/missing_package_arg_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/missing_package_arg_test.dart deleted file mode 100644 index e362ecb1d16..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/missing_package_arg_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if no package was given', () { - schedulePub(args: ["global", "deactivate"], error: """ - No package to deactivate given. - - Usage: pub global deactivate - -h, --help Print this usage information. - - Run "pub help" to see global options. - """, exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/path_package_test.dart deleted file mode 100644 index 788c89d6178..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/path_package_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('deactivates an active path package', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - var path = canonicalize(p.join(sandboxDir, "foo")); - schedulePub( - args: ["global", "deactivate", "foo"], - output: 'Deactivated package foo 1.0.0 at path "$path".'); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/removes_precompiled_snapshots_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/removes_precompiled_snapshots_test.dart deleted file mode 100644 index f4754b40e1c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/removes_precompiled_snapshots_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('removes precompiled snapshots', () { - servePackages((builder) => builder.serve("foo", "1.0.0")); - - schedulePub(args: ["global", "activate", "foo"]); - - schedulePub( - args: ["global", "deactivate", "foo"], - output: "Deactivated package foo 1.0.0."); - - d.dir(cachePath, [d.dir('global_packages', [d.nothing('foo')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/unexpected_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/unexpected_arguments_test.dart deleted file mode 100644 index 7e1e8771e74..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/unexpected_arguments_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if there are extra arguments', () { - schedulePub(args: ["global", "deactivate", "foo", "bar", "baz"], error: """ - Unexpected arguments "bar" and "baz". - - Usage: pub global deactivate - -h, --help Print this usage information. - - Run "pub help" to see global options. - """, exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/deactivate/unknown_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/deactivate/unknown_package_test.dart deleted file mode 100644 index d20eaa006f9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/deactivate/unknown_package_test.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('errors if the package is not activated', () { - serveNoPackages(); - - schedulePub( - args: ["global", "deactivate", "foo"], - error: "No active package foo.", - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/list_test.dart b/sdk/lib/_internal/pub_generated/test/global/list_test.dart deleted file mode 100644 index f11489636f4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/list_test.dart +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - integration('lists an activated hosted package', () { - servePackages((builder) { - builder.serve('foo', '1.0.0'); - }); - - schedulePub(args: ['global', 'activate', 'foo']); - - schedulePub(args: ['global', 'list'], output: 'foo 1.0.0'); - }); - - integration('lists an activated Git package', () { - ensureGit(); - - d.git( - 'foo.git', - [ - d.libPubspec('foo', '1.0.0'), - d.dir('bin', [d.file('foo.dart', 'main() => print("ok");')])]).create(); - - schedulePub(args: ['global', 'activate', '-sgit', '../foo.git']); - - schedulePub( - args: ['global', 'list'], - output: 'foo 1.0.0 from Git repository "../foo.git"'); - }); - - integration('lists an activated Path package', () { - d.dir( - 'foo', - [ - d.libPubspec('foo', '1.0.0'), - d.dir('bin', [d.file('foo.dart', 'main() => print("ok");')])]).create(); - - schedulePub(args: ['global', 'activate', '-spath', '../foo']); - - var path = canonicalize(p.join(sandboxDir, 'foo')); - schedulePub(args: ['global', 'list'], output: 'foo 1.0.0 at path "$path"'); - }); - - integration('lists activated packages in alphabetical order', () { - servePackages((builder) { - builder.serve('aaa', '1.0.0'); - builder.serve('bbb', '1.0.0'); - builder.serve('ccc', '1.0.0'); - }); - - schedulePub(args: ['global', 'activate', 'ccc']); - schedulePub(args: ['global', 'activate', 'aaa']); - schedulePub(args: ['global', 'activate', 'bbb']); - - schedulePub(args: ['global', 'list'], output: ''' -aaa 1.0.0 -bbb 1.0.0 -ccc 1.0.0 -'''); - }); - - integration('lists nothing when no packages activated', () { - schedulePub(args: ['global', 'list'], output: '\n'); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/errors_if_outside_bin_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/errors_if_outside_bin_test.dart deleted file mode 100644 index aedeb489589..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/errors_if_outside_bin_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('errors if the script is in a subdirectory.', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("example", [d.file("script.dart", "main(args) => print('ok');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - schedulePub(args: ["global", "run", "foo:example/script"], error: """ -Cannot run an executable in a subdirectory of a global package. - -Usage: pub global run : [args...] --h, --help Print this usage information. - --mode Mode to run transformers in. - (defaults to "release") - -Run "pub help" to see global options. -""", exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/implicit_executable_name_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/implicit_executable_name_test.dart deleted file mode 100644 index 1e35edaf2b8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/implicit_executable_name_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('defaults to the package name if the script is omitted', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [d.dir("bin", [d.file("foo.dart", "main(args) => print('foo');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("foo"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/missing_executable_arg_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/missing_executable_arg_test.dart deleted file mode 100644 index c655cda6d50..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/missing_executable_arg_test.dart +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('fails if no executable was given', () { - schedulePub(args: ["global", "run"], error: """ - Must specify an executable to run. - - Usage: pub global run : [args...] - -h, --help Print this usage information. - --mode Mode to run transformers in. - (defaults to "release") - - Run "pub help" to see global options. - """, exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/missing_path_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/missing_path_package_test.dart deleted file mode 100644 index 66f10f7cbd2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/missing_path_package_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('errors if the local package does not exist', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - schedule(() => deleteEntry(p.join(sandboxDir, "foo"))); - - var pub = pubRun(global: true, args: ["foo"]); - var path = canonicalize(p.join(sandboxDir, "foo")); - pub.stderr.expect('Could not find a file named "pubspec.yaml" in "$path".'); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/mode_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/mode_test.dart deleted file mode 100644 index fdf4b8a35f2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/mode_test.dart +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class DartTransformer extends Transformer { - final BarbackSettings _settings; - - DartTransformer.asPlugin(this._settings); - - String get allowedExtensions => '.in'; - - void apply(Transform transform) { - transform.addOutput(new Asset.fromString( - new AssetId(transform.primaryInput.id.package, "bin/script.dart"), - "void main() => print('\${_settings.mode.name}');")); - } -} -"""; - -main() { - initConfig(); - integration( - 'runs a script in an activated package with customizable modes', - () { - servePackages((builder) { - builder.serveRepoPackage("barback"); - - builder.serve("foo", "1.0.0", deps: { - "barback": "any" - }, pubspec: { - "transformers": ["foo/src/transformer"] - }, - contents: [ - d.dir( - "lib", - [ - d.dir( - "src", - [d.file("transformer.dart", TRANSFORMER), d.file("primary.in", "")])])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - // By default it should run in release mode. - var pub = pubRun(global: true, args: ["foo:script"]); - pub.stdout.expect("release"); - pub.shouldExit(); - - // A custom mode should be specifiable. - pub = pubRun(global: true, args: ["--mode", "custom-mode", "foo:script"]); - pub.stdout.expect("custom-mode"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/nonexistent_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/nonexistent_script_test.dart deleted file mode 100644 index d69c65ab586..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/nonexistent_script_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('errors if the script does not exist.', () { - servePackages((builder) => builder.serve("foo", "1.0.0")); - - schedulePub(args: ["global", "activate", "foo"]); - - var pub = pubRun(global: true, args: ["foo:script"]); - pub.stderr.expect("Could not find ${p.join("bin", "script.dart")}."); - pub.shouldExit(exit_codes.NO_INPUT); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/recompiles_if_sdk_is_out_of_date_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/recompiles_if_sdk_is_out_of_date_test.dart deleted file mode 100644 index 1579ed58c5c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/recompiles_if_sdk_is_out_of_date_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('recompiles a script if the SDK version is out-of-date', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir( - 'foo', - [d.dir('bin', [d.outOfDateSnapshot('script.dart.snapshot')])])])]).create(); - - var pub = pubRun(global: true, args: ["foo:script"]); - // In the real world this would just print "hello!", but since we collect - // all output we see the precompilation messages as well. - pub.stdout.expect("Precompiling executables..."); - pub.stdout.expect(consumeThrough("ok")); - pub.shouldExit(); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.dir( - 'foo', - [ - d.dir( - 'bin', - [d.matcherFile('script.dart.snapshot', contains('ok'))])])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/reflects_changes_to_local_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/reflects_changes_to_local_package_test.dart deleted file mode 100644 index d4c19ddd220..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/reflects_changes_to_local_package_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('changes in a path package are immediately reflected', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - d.file("foo/bin/foo.dart", "main() => print('changed');").create(); - - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("changed"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_git_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_git_script_test.dart deleted file mode 100644 index ca9a6c36827..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/runs_git_script_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('runs a script in a git package', () { - ensureGit(); - - d.git( - 'foo.git', - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "-sgit", "../foo.git"]); - - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("ok"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_path_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_path_script_test.dart deleted file mode 100644 index 89985e6bb55..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/runs_path_script_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('runs a script in a path package', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("foo.dart", "main() => print('ok');")])]).create(); - - schedulePub(args: ["global", "activate", "--source", "path", "../foo"]); - - var pub = pubRun(global: true, args: ["foo"]); - pub.stdout.expect("ok"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_script_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_script_test.dart deleted file mode 100644 index 3d9f35cb42d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/runs_script_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('runs a script in an activated package', () { - servePackages((builder) { - builder.serve( - "foo", - "1.0.0", - contents: [ - d.dir("bin", [d.file("script.dart", "main(args) => print('ok');")])]); - }); - - schedulePub(args: ["global", "activate", "foo"]); - - var pub = pubRun(global: true, args: ["foo:script"]); - pub.stdout.expect("ok"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/runs_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/runs_transformer_test.dart deleted file mode 100644 index 035b0f0cb8f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/runs_transformer_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class DartTransformer extends Transformer { - DartTransformer.asPlugin(); - - String get allowedExtensions => '.in'; - - void apply(Transform transform) { - transform.addOutput(new Asset.fromString( - new AssetId("foo", "bin/script.dart"), - "void main() => print('generated');")); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration('runs a global script generated by a transformer', () { - makeGlobalPackage("foo", "1.0.0", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": ["foo/src/transformer"] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [d.file("transformer.dart", TRANSFORMER), d.file("primary.in", "")])])], - pkg: ['barback']); - - var pub = pubRun(global: true, args: ["foo:script"]); - - pub.stdout.expect("generated"); - pub.shouldExit(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/unknown_package_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/unknown_package_test.dart deleted file mode 100644 index dedce44cec5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/unknown_package_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('errors if the package is not activated', () { - serveNoPackages(); - - schedulePub( - args: ["global", "run", "foo:bar"], - error: startsWith("No active package foo."), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/global/run/uses_old_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/global/run/uses_old_lockfile_test.dart deleted file mode 100644 index 1bdd6348ec5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/global/run/uses_old_lockfile_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration('uses the 1.6-style lockfile if necessary', () { - servePackages((builder) { - builder.serve("bar", "1.0.0"); - builder.serve("foo", "1.0.0", deps: { - "bar": "any" - }, contents: [d.dir("bin", [d.file("script.dart", """ - import 'package:bar/bar.dart' as bar; - - main(args) => print(bar.main());""")])]); - }); - - schedulePub(args: ["cache", "add", "foo"]); - schedulePub(args: ["cache", "add", "bar"]); - - d.dir(cachePath, [d.dir('global_packages', [d.file('foo.lock', ''' -packages: - foo: - description: foo - source: hosted - version: "1.0.0" - bar: - description: bar - source: hosted - version: "1.0.0"''')])]).create(); - - var pub = pubRun(global: true, args: ["foo:script"]); - pub.stdout.expect("bar 1.0.0"); - pub.shouldExit(); - - d.dir( - cachePath, - [ - d.dir( - 'global_packages', - [ - d.nothing('foo.lock'), - d.dir('foo', [d.matcherFile('pubspec.lock', contains('1.0.0'))])])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_missing_package_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_missing_package_test.dart deleted file mode 100644 index cfb153c6495..00000000000 --- a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_missing_package_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration('fails gracefully if the package does not exist', () { - serveNoPackages(); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubCommand(command, error: new RegExp(r""" -Could not find package foo at http://localhost:\d+\. -Depended on by: -- myapp""", multiLine: true), exitCode: exit_codes.UNAVAILABLE); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_url_resolve_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_url_resolve_test.dart deleted file mode 100644 index b92346f4abb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/hosted/fail_gracefully_on_url_resolve_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration('fails gracefully if the url does not resolve', () { - d.dir(appPath, [d.appPubspec({ - "foo": { - "hosted": { - "name": "foo", - "url": "http://pub.invalid" - } - } - })]).create(); - - pubCommand( - command, - error: 'Could not resolve URL "http://pub.invalid".', - exitCode: exit_codes.UNAVAILABLE); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/hosted/offline_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/offline_test.dart deleted file mode 100644 index 8a3bae5430a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/hosted/offline_test.dart +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration('upgrades a package using the cache', () { - // Run the server so that we know what URL to use in the system cache. - serveNoPackages(); - - d.cacheDir({ - "foo": ["1.2.2", "1.2.3"], - "bar": ["1.2.3"] - }, includePubspecs: true).create(); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - var warning = null; - if (command == RunCommand.upgrade) { - warning = - "Warning: Upgrading when offline may not update you " - "to the latest versions of your dependencies."; - } - - pubCommand(command, args: ['--offline'], warning: warning); - - d.packagesDir({ - "foo": "1.2.3", - "bar": "1.2.3" - }).validate(); - }); - - integration('fails gracefully if a dependency is not cached', () { - // Run the server so that we know what URL to use in the system cache. - serveNoPackages(); - - d.appDir({ - "foo": "any" - }).create(); - - pubCommand( - command, - args: ['--offline'], - error: "Could not find package foo in cache."); - }); - - integration('fails gracefully no cached versions match', () { - // Run the server so that we know what URL to use in the system cache. - serveNoPackages(); - - d.cacheDir({ - "foo": ["1.2.2", "1.2.3"] - }, includePubspecs: true).create(); - - d.appDir({ - "foo": ">2.0.0" - }).create(); - - pubCommand( - command, - args: ['--offline'], - error: "Package foo has no versions that match >2.0.0 derived from:\n" - "- myapp 0.0.0 depends on version >2.0.0"); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_dependency_test.dart deleted file mode 100644 index 1ec05e0d595..00000000000 --- a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_dependency_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration("removes a dependency that's removed from the pubspec", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("bar", "1.0.0"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0" - }).validate(); - - d.appDir({ - "foo": "any" - }).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": "1.0.0", - "bar": null - }).validate(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_transitive_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_transitive_dependency_test.dart deleted file mode 100644 index a5f1a3098ac..00000000000 --- a/sdk/lib/_internal/pub_generated/test/hosted/remove_removed_transitive_dependency_test.dart +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration( - "removes a transitive dependency that's no longer depended " "on", - () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "shared-dep": "any" - }); - builder.serve("bar", "1.0.0", deps: { - "shared-dep": "any", - "bar-dep": "any" - }); - builder.serve("shared-dep", "1.0.0"); - builder.serve("bar-dep", "1.0.0"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0", - "shared-dep": "1.0.0", - "bar-dep": "1.0.0", - }).validate(); - - d.appDir({ - "foo": "any" - }).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": "1.0.0", - "bar": null, - "shared-dep": "1.0.0", - "bar-dep": null, - }).validate(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/hosted/version_negotiation_test.dart b/sdk/lib/_internal/pub_generated/test/hosted/version_negotiation_test.dart deleted file mode 100644 index 7d2914e917e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/hosted/version_negotiation_test.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration('sends the correct Accept header', () { - var server = new ScheduledServer(); - - d.appDir({ - "foo": { - "hosted": { - "name": "foo", - "url": server.url.then((url) => url.toString()) - } - } - }).create(); - - var pub = startPub(args: [command.name]); - - server.handle('GET', '/api/packages/foo', (request) { - expect( - request.headers['accept'], - equals('application/vnd.pub.v2+json')); - return new shelf.Response(200); - }); - - pub.kill(); - }); - - integration('prints a friendly error if the version is out-of-date', () { - var server = new ScheduledServer(); - - d.appDir({ - "foo": { - "hosted": { - "name": "foo", - "url": server.url.then((url) => url.toString()) - } - } - }).create(); - - var pub = startPub(args: [command.name]); - - server.handle( - 'GET', - '/api/packages/foo', - (request) => new shelf.Response(406)); - - pub.shouldExit(1); - - pub.stderr.expect( - emitsLines( - "Pub 0.1.2+3 is incompatible with the current version of localhost.\n" - "Upgrade pub to the latest version and try again.")); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/implicit_barback_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/implicit_barback_dependency_test.dart deleted file mode 100644 index a7257975624..00000000000 --- a/sdk/lib/_internal/pub_generated/test/implicit_barback_dependency_test.dart +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:pub_semver/pub_semver.dart'; - -import 'descriptor.dart' as d; -import 'test_pub.dart'; -import '../lib/src/barback.dart' as barback; - -main() { - initConfig(); - - var constraint = barback.pubConstraints["barback"]; - var current = constraint.min.toString(); - var previous = - new Version(constraint.min.major, constraint.min.minor - 1, 0).toString(); - var nextPatch = constraint.min.nextPatch.toString(); - var max = constraint.max.toString(); - - var sourceSpanVersion = barback.pubConstraints["source_span"].min.toString(); - var stackTraceVersion = barback.pubConstraints["stack_trace"].min.toString(); - - forBothPubGetAndUpgrade((command) { - integration("implicitly constrains barback to versions pub supports", () { - servePackages((builder) { - builder.serve("barback", previous); - builder.serve("barback", current); - builder.serve("barback", nextPatch); - builder.serve("barback", max); - builder.serve("source_span", sourceSpanVersion); - builder.serve("stack_trace", stackTraceVersion); - }); - - d.appDir({ - "barback": "any" - }).create(); - - pubCommand(command); - - d.packagesDir({ - "barback": nextPatch - }).validate(); - }); - - integration("discovers transitive dependency on barback", () { - servePackages((builder) { - builder.serve("barback", previous); - builder.serve("barback", current); - builder.serve("barback", nextPatch); - builder.serve("barback", max); - builder.serve("source_span", sourceSpanVersion); - builder.serve("stack_trace", stackTraceVersion); - }); - - d.dir( - "foo", - [d.libDir("foo", "foo 0.0.1"), d.libPubspec("foo", "0.0.1", deps: { - "barback": "any" - })]).create(); - - d.appDir({ - "foo": { - "path": "../foo" - } - }).create(); - - pubCommand(command); - - d.packagesDir({ - "barback": nextPatch, - "foo": "0.0.1" - }).validate(); - }); - - integration( - "pub's implicit constraint uses the same source and " - "description as a dependency override", - () { - servePackages((builder) { - builder.serve("source_span", sourceSpanVersion); - builder.serve("stack_trace", stackTraceVersion); - }); - - d.dir( - 'barback', - [ - d.libDir('barback', 'barback $current'), - d.libPubspec('barback', current),]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependency_overrides": { - "barback": { - "path": "../barback" - } - } - })]).create(); - - pubCommand(command); - - d.packagesDir({ - "barback": current - }).validate(); - }); - }); - - integration("unlock if the locked version doesn't meet pub's constraint", () { - servePackages((builder) { - builder.serve("barback", previous); - builder.serve("barback", current); - builder.serve("source_span", sourceSpanVersion); - builder.serve("stack_trace", stackTraceVersion); - }); - - d.appDir({ - "barback": "any" - }).create(); - - // Hand-create a lockfile to pin barback to an older version. - createLockFile("myapp", hosted: { - "barback": previous - }); - - pubGet(); - - // It should be upgraded. - d.packagesDir({ - "barback": current - }).validate(); - }); - - integration( - "includes pub in the error if a solve failed because there " - "is no version available", - () { - servePackages((builder) { - builder.serve("barback", previous); - builder.serve("source_span", sourceSpanVersion); - builder.serve("stack_trace", stackTraceVersion); - }); - - d.appDir({ - "barback": "any" - }).create(); - - pubGet(error: """ -Package barback 0.12.0 does not match >=$current <$max derived from: -- myapp 0.0.0 depends on version any -- pub itself depends on version >=$current <$max"""); - }); - - integration( - "includes pub in the error if a solve failed because there " - "is a disjoint constraint", - () { - servePackages((builder) { - builder.serve("barback", previous); - builder.serve("barback", current); - builder.serve("source_span", sourceSpanVersion); - builder.serve("stack_trace", stackTraceVersion); - }); - - d.appDir({ - "barback": previous - }).create(); - - pubGet(error: """ -Incompatible version constraints on barback: -- myapp 0.0.0 depends on version $previous -- pub itself depends on version >=$current <$max"""); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/implicit_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/implicit_dependency_test.dart deleted file mode 100644 index d3c8560f822..00000000000 --- a/sdk/lib/_internal/pub_generated/test/implicit_dependency_test.dart +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:pub_semver/pub_semver.dart'; - -import 'descriptor.dart' as d; -import 'test_pub.dart'; -import '../lib/src/barback.dart' as barback; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration("implicitly constrains it to versions pub supports", () { - servePackages((builder) { - builder.serve("barback", current("barback")); - builder.serve("stack_trace", previous("stack_trace")); - builder.serve("stack_trace", current("stack_trace")); - builder.serve("stack_trace", nextPatch("stack_trace")); - builder.serve("stack_trace", max("stack_trace")); - builder.serve("source_span", current("source_span")); - }); - - d.appDir({ - "barback": "any" - }).create(); - - pubCommand(command); - - d.packagesDir({ - "stack_trace": nextPatch("stack_trace") - }).validate(); - }); - - integration( - "pub's implicit constraint uses the same source and " - "description as a dependency override", - () { - servePackages((builder) { - builder.serve("barback", current("barback")); - builder.serve("stack_trace", nextPatch("stack_trace")); - builder.serve("source_span", current("source_span")); - }); - - d.dir( - "stack_trace", - [ - d.libDir("stack_trace", 'stack_trace ${current("stack_trace")}'), - d.libPubspec("stack_trace", current("stack_trace"))]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "barback": "any" - }, - "dependency_overrides": { - "stack_trace": { - "path": "../stack_trace" - }, - } - })]).create(); - - pubCommand(command); - - // Validate that we're using the path dependency version of stack_trace - // rather than the hosted version. - d.packagesDir({ - "stack_trace": current("stack_trace") - }).validate(); - }); - - integration( - "doesn't add a constraint if barback isn't in the package " "graph", - () { - servePackages((builder) { - builder.serve("stack_trace", previous("stack_trace")); - builder.serve("stack_trace", current("stack_trace")); - builder.serve("stack_trace", nextPatch("stack_trace")); - builder.serve("stack_trace", max("stack_trace")); - builder.serve("source_span", current("source_span")); - }); - - d.appDir({ - "stack_trace": "any" - }).create(); - - pubCommand(command); - - d.packagesDir({ - "stack_trace": max("stack_trace") - }).validate(); - }); - }); - - integration( - "unlocks if the locked version doesn't meet pub's " "constraint", - () { - servePackages((builder) { - builder.serve("barback", current("barback")); - builder.serve("stack_trace", previous("stack_trace")); - builder.serve("stack_trace", current("stack_trace")); - builder.serve("source_span", current("source_span")); - }); - - d.appDir({ - "barback": "any" - }).create(); - - // Hand-create a lockfile to pin the package to an older version. - createLockFile("myapp", hosted: { - "barback": current("barback"), - "stack_trace": previous("stack_trace") - }); - - pubGet(); - - // It should be upgraded. - d.packagesDir({ - "stack_trace": current("stack_trace") - }).validate(); - }); -} - -String current(String packageName) => - barback.pubConstraints[packageName].min.toString(); - -String previous(String packageName) { - var constraint = barback.pubConstraints[packageName]; - return new Version( - constraint.min.major, - constraint.min.minor - 1, - 0).toString(); -} - -String nextPatch(String packageName) => - barback.pubConstraints[packageName].min.nextPatch.toString(); - -String max(String packageName) => - barback.pubConstraints[packageName].max.toString(); diff --git a/sdk/lib/_internal/pub_generated/test/io_test.dart b/sdk/lib/_internal/pub_generated/test/io_test.dart deleted file mode 100644 index 056843fc6de..00000000000 --- a/sdk/lib/_internal/pub_generated/test/io_test.dart +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library io_test; - -import 'dart:async'; -import 'dart:io'; - -import 'package:path/path.dart' as path; -import 'package:unittest/unittest.dart'; - -import '../lib/src/io.dart'; -import 'test_pub.dart'; - -main() { - initConfig(); - - group('listDir', () { - test('ignores hidden files by default', () { - expect(withTempDir((temp) { - writeTextFile(path.join(temp, 'file1.txt'), ''); - writeTextFile(path.join(temp, 'file2.txt'), ''); - writeTextFile(path.join(temp, '.file3.txt'), ''); - createDir(path.join(temp, '.subdir')); - writeTextFile(path.join(temp, '.subdir', 'file3.txt'), ''); - - expect( - listDir(temp, recursive: true), - unorderedEquals([path.join(temp, 'file1.txt'), path.join(temp, 'file2.txt')])); - }), completes); - }); - - test('includes hidden files when told to', () { - expect(withTempDir((temp) { - writeTextFile(path.join(temp, 'file1.txt'), ''); - writeTextFile(path.join(temp, 'file2.txt'), ''); - writeTextFile(path.join(temp, '.file3.txt'), ''); - createDir(path.join(temp, '.subdir')); - writeTextFile(path.join(temp, '.subdir', 'file3.txt'), ''); - - expect( - listDir(temp, recursive: true, includeHidden: true), - unorderedEquals( - [ - path.join(temp, 'file1.txt'), - path.join(temp, 'file2.txt'), - path.join(temp, '.file3.txt'), - path.join(temp, '.subdir'), - path.join(temp, '.subdir', 'file3.txt')])); - }), completes); - }); - - test("doesn't ignore hidden files above the directory being listed", () { - expect(withTempDir((temp) { - var dir = path.join(temp, '.foo', 'bar'); - ensureDir(dir); - writeTextFile(path.join(dir, 'file1.txt'), ''); - writeTextFile(path.join(dir, 'file2.txt'), ''); - writeTextFile(path.join(dir, 'file3.txt'), ''); - - expect( - listDir(dir, recursive: true), - unorderedEquals( - [ - path.join(dir, 'file1.txt'), - path.join(dir, 'file2.txt'), - path.join(dir, 'file3.txt')])); - }), completes); - }); - }); - - group('canonicalize', () { - test('resolves a non-link', () { - expect(withCanonicalTempDir((temp) { - var filePath = path.join(temp, 'file'); - writeTextFile(filePath, ''); - expect(canonicalize(filePath), equals(filePath)); - }), completes); - }); - - test('resolves a non-existent file', () { - expect(withCanonicalTempDir((temp) { - expect( - canonicalize(path.join(temp, 'nothing')), - equals(path.join(temp, 'nothing'))); - }), completes); - }); - - test('resolves a symlink', () { - expect(withCanonicalTempDir((temp) { - createDir(path.join(temp, 'linked-dir')); - createSymlink(path.join(temp, 'linked-dir'), path.join(temp, 'dir')); - expect( - canonicalize(path.join(temp, 'dir')), - equals(path.join(temp, 'linked-dir'))); - }), completes); - }); - - test('resolves a relative symlink', () { - expect(withCanonicalTempDir((temp) { - createDir(path.join(temp, 'linked-dir')); - createSymlink( - path.join(temp, 'linked-dir'), - path.join(temp, 'dir'), - relative: true); - expect( - canonicalize(path.join(temp, 'dir')), - equals(path.join(temp, 'linked-dir'))); - }), completes); - }); - - test('resolves a single-level horizontally recursive symlink', () { - expect(withCanonicalTempDir((temp) { - var linkPath = path.join(temp, 'foo'); - createSymlink(linkPath, linkPath); - expect(canonicalize(linkPath), equals(linkPath)); - }), completes); - }); - - test('resolves a multi-level horizontally recursive symlink', () { - expect(withCanonicalTempDir((temp) { - var fooPath = path.join(temp, 'foo'); - var barPath = path.join(temp, 'bar'); - var bazPath = path.join(temp, 'baz'); - createSymlink(barPath, fooPath); - createSymlink(bazPath, barPath); - createSymlink(fooPath, bazPath); - expect(canonicalize(fooPath), equals(fooPath)); - expect(canonicalize(barPath), equals(barPath)); - expect(canonicalize(bazPath), equals(bazPath)); - - createSymlink(fooPath, path.join(temp, 'outer')); - expect(canonicalize(path.join(temp, 'outer')), equals(fooPath)); - }), completes); - }); - - test('resolves a broken symlink', () { - expect(withCanonicalTempDir((temp) { - createSymlink(path.join(temp, 'nonexistent'), path.join(temp, 'foo')); - expect( - canonicalize(path.join(temp, 'foo')), - equals(path.join(temp, 'nonexistent'))); - }), completes); - }); - - test('resolves multiple nested symlinks', () { - expect(withCanonicalTempDir((temp) { - var dir1 = path.join(temp, 'dir1'); - var dir2 = path.join(temp, 'dir2'); - var subdir1 = path.join(dir1, 'subdir1'); - var subdir2 = path.join(dir2, 'subdir2'); - createDir(dir2); - createDir(subdir2); - createSymlink(dir2, dir1); - createSymlink(subdir2, subdir1); - expect( - canonicalize(path.join(subdir1, 'file')), - equals(path.join(subdir2, 'file'))); - }), completes); - }); - - test('resolves a nested vertical symlink', () { - expect(withCanonicalTempDir((temp) { - var dir1 = path.join(temp, 'dir1'); - var dir2 = path.join(temp, 'dir2'); - var subdir = path.join(dir1, 'subdir'); - createDir(dir1); - createDir(dir2); - createSymlink(dir2, subdir); - expect( - canonicalize(path.join(subdir, 'file')), - equals(path.join(dir2, 'file'))); - }), completes); - }); - - test('resolves a vertically recursive symlink', () { - expect(withCanonicalTempDir((temp) { - var dir = path.join(temp, 'dir'); - var subdir = path.join(dir, 'subdir'); - createDir(dir); - createSymlink(dir, subdir); - expect( - canonicalize( - path.join(temp, 'dir', 'subdir', 'subdir', 'subdir', 'subdir', 'file')), - equals(path.join(dir, 'file'))); - }), completes); - }); - - test( - 'resolves a symlink that links to a path that needs more resolving', - () { - expect(withCanonicalTempDir((temp) { - var dir = path.join(temp, 'dir'); - var linkdir = path.join(temp, 'linkdir'); - var linkfile = path.join(dir, 'link'); - createDir(dir); - createSymlink(dir, linkdir); - createSymlink(path.join(linkdir, 'file'), linkfile); - expect(canonicalize(linkfile), equals(path.join(dir, 'file'))); - }), completes); - }); - - test('resolves a pair of pathologically-recursive symlinks', () { - expect(withCanonicalTempDir((temp) { - var foo = path.join(temp, 'foo'); - var subfoo = path.join(foo, 'subfoo'); - var bar = path.join(temp, 'bar'); - var subbar = path.join(bar, 'subbar'); - createSymlink(subbar, foo); - createSymlink(subfoo, bar); - expect( - canonicalize(subfoo), - equals(path.join(subfoo, 'subbar', 'subfoo'))); - }), completes); - }); - }); - - testExistencePredicate( - "entryExists", - entryExists, - forFile: true, - forFileSymlink: true, - forMultiLevelFileSymlink: true, - forDirectory: true, - forDirectorySymlink: true, - forMultiLevelDirectorySymlink: true, - forBrokenSymlink: true, - forMultiLevelBrokenSymlink: true); - - testExistencePredicate( - "linkExists", - linkExists, - forFile: false, - forFileSymlink: true, - forMultiLevelFileSymlink: true, - forDirectory: false, - forDirectorySymlink: true, - forMultiLevelDirectorySymlink: true, - forBrokenSymlink: true, - forMultiLevelBrokenSymlink: true); - - testExistencePredicate( - "fileExists", - fileExists, - forFile: true, - forFileSymlink: true, - forMultiLevelFileSymlink: true, - forDirectory: false, - forDirectorySymlink: false, - forMultiLevelDirectorySymlink: false, - forBrokenSymlink: false, - forMultiLevelBrokenSymlink: false); - - testExistencePredicate( - "dirExists", - dirExists, - forFile: false, - forFileSymlink: false, - forMultiLevelFileSymlink: false, - forDirectory: true, - forDirectorySymlink: true, - forMultiLevelDirectorySymlink: true, - forBrokenSymlink: false, - forMultiLevelBrokenSymlink: false); -} - -void testExistencePredicate(String name, bool predicate(String path), - {bool forFile, bool forFileSymlink, bool forMultiLevelFileSymlink, - bool forDirectory, bool forDirectorySymlink, bool forMultiLevelDirectorySymlink, - bool forBrokenSymlink, bool forMultiLevelBrokenSymlink}) { - group(name, () { - test('returns $forFile for a file', () { - expect(withTempDir((temp) { - var file = path.join(temp, "test.txt"); - writeTextFile(file, "contents"); - expect(predicate(file), equals(forFile)); - }), completes); - }); - - test('returns $forDirectory for a directory', () { - expect(withTempDir((temp) { - var file = path.join(temp, "dir"); - createDir(file); - expect(predicate(file), equals(forDirectory)); - }), completes); - }); - - test('returns $forDirectorySymlink for a symlink to a directory', () { - expect(withTempDir((temp) { - var targetPath = path.join(temp, "dir"); - var symlinkPath = path.join(temp, "linkdir"); - createDir(targetPath); - createSymlink(targetPath, symlinkPath); - expect(predicate(symlinkPath), equals(forDirectorySymlink)); - }), completes); - }); - - test( - 'returns $forMultiLevelDirectorySymlink for a multi-level symlink to ' - 'a directory', - () { - expect(withTempDir((temp) { - var targetPath = path.join(temp, "dir"); - var symlink1Path = path.join(temp, "link1dir"); - var symlink2Path = path.join(temp, "link2dir"); - createDir(targetPath); - createSymlink(targetPath, symlink1Path); - createSymlink(symlink1Path, symlink2Path); - expect(predicate(symlink2Path), equals(forMultiLevelDirectorySymlink)); - }), completes); - }); - - test('returns $forBrokenSymlink for a broken symlink', () { - expect(withTempDir((temp) { - var targetPath = path.join(temp, "dir"); - var symlinkPath = path.join(temp, "linkdir"); - createDir(targetPath); - createSymlink(targetPath, symlinkPath); - deleteEntry(targetPath); - expect(predicate(symlinkPath), equals(forBrokenSymlink)); - }), completes); - }); - - test( - 'returns $forMultiLevelBrokenSymlink for a multi-level broken symlink', - () { - expect(withTempDir((temp) { - var targetPath = path.join(temp, "dir"); - var symlink1Path = path.join(temp, "link1dir"); - var symlink2Path = path.join(temp, "link2dir"); - createDir(targetPath); - createSymlink(targetPath, symlink1Path); - createSymlink(symlink1Path, symlink2Path); - deleteEntry(targetPath); - expect(predicate(symlink2Path), equals(forMultiLevelBrokenSymlink)); - }), completes); - }); - - // Windows doesn't support symlinking to files. - if (Platform.operatingSystem != 'windows') { - test('returns $forFileSymlink for a symlink to a file', () { - expect(withTempDir((temp) { - var targetPath = path.join(temp, "test.txt"); - var symlinkPath = path.join(temp, "link.txt"); - writeTextFile(targetPath, "contents"); - createSymlink(targetPath, symlinkPath); - expect(predicate(symlinkPath), equals(forFileSymlink)); - }), completes); - }); - - test( - 'returns $forMultiLevelFileSymlink for a multi-level symlink to a ' 'file', - () { - expect(withTempDir((temp) { - var targetPath = path.join(temp, "test.txt"); - var symlink1Path = path.join(temp, "link1.txt"); - var symlink2Path = path.join(temp, "link2.txt"); - writeTextFile(targetPath, "contents"); - createSymlink(targetPath, symlink1Path); - createSymlink(symlink1Path, symlink2Path); - expect(predicate(symlink2Path), equals(forMultiLevelFileSymlink)); - }), completes); - }); - } - }); -} - -/// Like [withTempDir], but canonicalizes the path before passing it to [fn]. -Future withCanonicalTempDir(Future fn(String path)) => - withTempDir((temp) => fn(canonicalize(temp))); diff --git a/sdk/lib/_internal/pub_generated/test/lish/archives_and_uploads_a_package_test.dart b/sdk/lib/_internal/pub_generated/test/lish/archives_and_uploads_a_package_test.dart deleted file mode 100644 index db70c72ea31..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/archives_and_uploads_a_package_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('archives and uploads a package', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - handleUploadForm(server); - handleUpload(server); - - server.handle('GET', '/create', (request) { - return new shelf.Response.ok(JSON.encode({ - 'success': { - 'message': 'Package test_pkg 1.0.0 uploaded!' - } - })); - }); - - pub.stdout.expect(startsWith('Uploading...')); - pub.stdout.expect('Package test_pkg 1.0.0 uploaded!'); - pub.shouldExit(exit_codes.SUCCESS); - }); - - // TODO(nweiz): Once a multipart/form-data parser in Dart exists, we should - // test that "pub lish" chooses the correct files to publish. -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_doesnt_redirect_test.dart b/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_doesnt_redirect_test.dart deleted file mode 100644 index faef7ca265e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_doesnt_redirect_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration("cloud storage upload doesn't redirect", () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - handleUploadForm(server); - - server.handle('POST', '/upload', (request) { - return drainStream(request.read()).then((_) => new shelf.Response(200)); - }); - - pub.stderr.expect('Failed to upload the package.'); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_provides_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_provides_an_error_test.dart deleted file mode 100644 index a994e239fd4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/cloud_storage_upload_provides_an_error_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('cloud storage upload provides an error', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - handleUploadForm(server); - - server.handle('POST', '/upload', (request) { - return drainStream(request.read()).then((_) { - return new shelf.Response.notFound( - 'Your request sucked.', - headers: { - 'content-type': 'application/xml' - }); - }); - }); - - // TODO(nweiz): This should use the server's error message once the client - // can parse the XML. - pub.stderr.expect('Failed to upload the package.'); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_test.dart deleted file mode 100644 index 9698409f714..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('does not publish if the package is private', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["publish_to"] = "none"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - schedulePub( - args: ["lish"], - error: startsWith("A private package cannot be published."), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_with_server_arg_test.dart b/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_with_server_arg_test.dart deleted file mode 100644 index 44568c48e78..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/does_not_publish_if_private_with_server_arg_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - 'does not publish if the package is private even if a server ' - 'argument is provided', - () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["publish_to"] = "none"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - schedulePub( - args: ["lish", "--server", "http://example.com"], - error: startsWith("A private package cannot be published."), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_cannot_be_combined_with_dry_run_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_cannot_be_combined_with_dry_run_test.dart deleted file mode 100644 index 0cc6cd659cf..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/force_cannot_be_combined_with_dry_run_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('--force cannot be combined with --dry-run', () { - schedulePub(args: ['lish', '--force', '--dry-run'], error: """ - Cannot use both --force and --dry-run. - - Usage: pub publish [options] - -h, --help Print this usage information. - -n, --dry-run Validate but do not publish the package. - -f, --force Publish without confirmation if there are no errors. - --server The package server to which to upload this package. - (defaults to "https://pub.dartlang.org") - - Run "pub help" to see global options. - See http://dartlang.org/tools/pub/cmd/pub-lish.html for detailed documentation. - """, exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_private_test.dart deleted file mode 100644 index aca919bf372..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_private_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('force does not publish if the package is private', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["publish_to"] = "none"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - schedulePub( - args: ["lish", "--force"], - error: startsWith("A private package cannot be published."), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_there_are_errors_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_there_are_errors_test.dart deleted file mode 100644 index d6517169bb1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/force_does_not_publish_if_there_are_errors_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('--force does not publish if there are errors', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg.remove("homepage"); - d.dir(appPath, [d.pubspec(pkg)]).create(); - - var server = new ScheduledServer(); - var pub = startPublish(server, args: ['--force']); - - pub.shouldExit(exit_codes.SUCCESS); - pub.stderr.expect( - consumeThrough( - "Sorry, your package is missing a " "requirement and can't be published yet.")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_tests_are_no_warnings_or_errors_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_tests_are_no_warnings_or_errors_test.dart deleted file mode 100644 index 0db2516d917..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_tests_are_no_warnings_or_errors_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('--force publishes if there are no warnings or errors', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server, args: ['--force']); - - handleUploadForm(server); - handleUpload(server); - - server.handle('GET', '/create', (request) { - return new shelf.Response.ok(JSON.encode({ - 'success': { - 'message': 'Package test_pkg 1.0.0 uploaded!' - } - })); - }); - - pub.shouldExit(exit_codes.SUCCESS); - pub.stdout.expect(consumeThrough('Package test_pkg 1.0.0 uploaded!')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_there_are_warnings_test.dart b/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_there_are_warnings_test.dart deleted file mode 100644 index faf58fec47d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/force_publishes_if_there_are_warnings_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('--force publishes if there are warnings', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = "Natalie Weizenbaum"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server, args: ['--force']); - - handleUploadForm(server); - handleUpload(server); - - server.handle('GET', '/create', (request) { - return new shelf.Response.ok(JSON.encode({ - 'success': { - 'message': 'Package test_pkg 1.0.0 uploaded!' - } - })); - }); - - pub.shouldExit(exit_codes.SUCCESS); - pub.stderr.expect(consumeThrough('Suggestions:')); - pub.stderr.expect( - emitsLines( - '* Author "Natalie Weizenbaum" in pubspec.yaml should have an email ' - 'address\n' ' (e.g. "name ").')); - pub.stdout.expect(consumeThrough('Package test_pkg 1.0.0 uploaded!')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_error_test.dart deleted file mode 100644 index cfd75aa4ad3..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_error_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('package creation provides a malformed error', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - handleUploadForm(server); - handleUpload(server); - - var body = { - 'error': 'Your package was too boring.' - }; - server.handle('GET', '/create', (request) { - return new shelf.Response.notFound(JSON.encode(body)); - }); - - pub.stderr.expect('Invalid server response:'); - pub.stderr.expect(JSON.encode(body)); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_success_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_success_test.dart deleted file mode 100644 index 56963821bb2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_a_malformed_success_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('package creation provides a malformed success', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - handleUploadForm(server); - handleUpload(server); - - var body = { - 'success': 'Your package was awesome.' - }; - server.handle('GET', '/create', (request) { - return new shelf.Response.ok(JSON.encode(body)); - }); - - pub.stderr.expect('Invalid server response:'); - pub.stderr.expect(JSON.encode(body)); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_an_error_test.dart deleted file mode 100644 index fec17cd14f3..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_an_error_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('package creation provides an error', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - handleUploadForm(server); - handleUpload(server); - - server.handle('GET', '/create', (request) { - return new shelf.Response.notFound(JSON.encode({ - 'error': { - 'message': 'Your package was too boring.' - } - })); - }); - - pub.stderr.expect('Your package was too boring.'); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_invalid_json_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_invalid_json_test.dart deleted file mode 100644 index d6babb9a5f4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/package_creation_provides_invalid_json_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('package creation provides invalid JSON', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - handleUploadForm(server); - handleUpload(server); - - server.handle('GET', '/create', (request) { - return new shelf.Response.ok('{not json'); - }); - - pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json')); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_continues_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_continues_test.dart deleted file mode 100644 index 18e2f5b00fd..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_continues_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('package validation has a warning and continues', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = "Natalie Weizenbaum"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - pub.writeLine("y"); - handleUploadForm(server); - handleUpload(server); - - server.handle('GET', '/create', (request) { - return new shelf.Response.ok(JSON.encode({ - 'success': { - 'message': 'Package test_pkg 1.0.0 uploaded!' - } - })); - }); - - pub.shouldExit(exit_codes.SUCCESS); - pub.stdout.expect(consumeThrough('Package test_pkg 1.0.0 uploaded!')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_is_canceled_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_is_canceled_test.dart deleted file mode 100644 index 314c528e975..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_a_warning_and_is_canceled_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('package validation has a warning and is canceled', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = "Natalie Weizenbaum"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - var server = new ScheduledServer(); - var pub = startPublish(server); - - pub.writeLine("n"); - pub.shouldExit(exit_codes.SUCCESS); - pub.stderr.expect(consumeThrough("Package upload canceled.")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_an_error_test.dart deleted file mode 100644 index dacc67cd3c2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/package_validation_has_an_error_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('package validation has an error', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg.remove("homepage"); - d.dir(appPath, [d.pubspec(pkg)]).create(); - - var server = new ScheduledServer(); - var pub = startPublish(server); - - pub.shouldExit(exit_codes.SUCCESS); - pub.stderr.expect( - consumeThrough( - "Sorry, your package is missing a " "requirement and can't be published yet.")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/preview_errors_if_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/preview_errors_if_private_test.dart deleted file mode 100644 index 642c5c39d65..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/preview_errors_if_private_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('preview shows an error if the package is private', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["publish_to"] = "none"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - schedulePub( - args: ["lish", "--dry-run"], - error: startsWith("A private package cannot be published."), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_a_warning_test.dart b/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_a_warning_test.dart deleted file mode 100644 index 4f229afe6bf..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_a_warning_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('preview package validation has a warning', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = "Natalie Weizenbaum"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - var server = new ScheduledServer(); - var pub = startPublish(server, args: ['--dry-run']); - - pub.shouldExit(exit_codes.SUCCESS); - pub.stderr.expect(consumeThrough('Suggestions:')); - pub.stderr.expect( - emitsLines( - '* Author "Natalie Weizenbaum" in pubspec.yaml should have an email ' - 'address\n' ' (e.g. "name ").\n' '\n' 'Package has 1 warning.')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_no_warnings_test.dart b/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_no_warnings_test.dart deleted file mode 100644 index 66f092ebd4e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/preview_package_validation_has_no_warnings_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('preview package validation has no warnings', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = "Natalie Weizenbaum "; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - var server = new ScheduledServer(); - var pub = startPublish(server, args: ['--dry-run']); - - pub.shouldExit(exit_codes.SUCCESS); - pub.stderr.expect(consumeThrough('Package has 0 warnings.')); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/server_arg_does_not_override_private_test.dart b/sdk/lib/_internal/pub_generated/test/lish/server_arg_does_not_override_private_test.dart deleted file mode 100644 index 37c3f22eba1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/server_arg_does_not_override_private_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('an explicit --server argument does not override privacy', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["publish_to"] = "none"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - schedulePub( - args: ["lish", "--server", "http://arg.com"], - error: startsWith("A private package cannot be published."), - exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/server_arg_overrides_publish_to_url_test.dart b/sdk/lib/_internal/pub_generated/test/lish/server_arg_overrides_publish_to_url_test.dart deleted file mode 100644 index b509445202a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/server_arg_overrides_publish_to_url_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('an explicit --server argument overrides a "publish_to" url', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["publish_to"] = "http://pubspec.com"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - schedulePub( - args: ["lish", "--dry-run", "--server", "http://arg.com"], - output: contains("http://arg.com")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_has_a_non_string_value_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_has_a_non_string_value_test.dart deleted file mode 100644 index b24270c3d2f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_has_a_non_string_value_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('upload form fields has a non-string value', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - var body = { - 'url': 'http://example.com/upload', - 'fields': { - 'field': 12 - } - }; - handleUploadForm(server, body); - pub.stderr.expect('Invalid server response:'); - pub.stderr.expect(JSON.encode(body)); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_is_not_a_map_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_is_not_a_map_test.dart deleted file mode 100644 index ed5ad0008ee..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_fields_is_not_a_map_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('upload form fields is not a map', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - var body = { - 'url': 'http://example.com/upload', - 'fields': 12 - }; - handleUploadForm(server, body); - pub.stderr.expect('Invalid server response:'); - pub.stderr.expect(JSON.encode(body)); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_fields_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_fields_test.dart deleted file mode 100644 index 433666a94cf..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_fields_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('upload form is missing fields', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - var body = { - 'url': 'http://example.com/upload' - }; - handleUploadForm(server, body); - pub.stderr.expect('Invalid server response:'); - pub.stderr.expect(JSON.encode(body)); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_url_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_url_test.dart deleted file mode 100644 index a08b58127f6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_is_missing_url_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('upload form is missing url', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - var body = { - 'fields': { - 'field1': 'value1', - 'field2': 'value2' - } - }; - - handleUploadForm(server, body); - pub.stderr.expect('Invalid server response:'); - pub.stderr.expect(JSON.encode(body)); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_an_error_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_an_error_test.dart deleted file mode 100644 index bf65fd05968..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_an_error_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('upload form provides an error', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - server.handle('GET', '/api/packages/versions/new', (request) { - return new shelf.Response.notFound(JSON.encode({ - 'error': { - 'message': 'your request sucked' - } - })); - }); - - pub.stderr.expect('your request sucked'); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_invalid_json_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_invalid_json_test.dart deleted file mode 100644 index 70d4df06242..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_provides_invalid_json_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('upload form provides invalid JSON', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - server.handle( - 'GET', - '/api/packages/versions/new', - (request) => new shelf.Response.ok('{not json')); - - pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json')); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/upload_form_url_is_not_a_string_test.dart b/sdk/lib/_internal/pub_generated/test/lish/upload_form_url_is_not_a_string_test.dart deleted file mode 100644 index 2f32df41aa2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/upload_form_url_is_not_a_string_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(d.validPackage.create); - - integration('upload form url is not a string', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - var body = { - 'url': 12, - 'fields': { - 'field1': 'value1', - 'field2': 'value2' - } - }; - - handleUploadForm(server, body); - pub.stderr.expect('Invalid server response:'); - pub.stderr.expect(JSON.encode(body)); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/uses_publish_to_url_test.dart b/sdk/lib/_internal/pub_generated/test/lish/uses_publish_to_url_test.dart deleted file mode 100644 index 32ca1b80f7d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/uses_publish_to_url_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('preview shows an error if the package is private', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["publish_to"] = "http://example.com"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - schedulePub( - args: ["lish", "--dry-run"], - output: contains("Publishing test_pkg 1.0.0 to http://example.com")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lish/utils.dart b/sdk/lib/_internal/pub_generated/test/lish/utils.dart deleted file mode 100644 index 1342f8e92a8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lish/utils.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library lish.utils; - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/io.dart'; - -void handleUploadForm(ScheduledServer server, [Map body]) { - server.handle('GET', '/api/packages/versions/new', (request) { - return server.url.then((url) { - expect( - request.headers, - containsPair('authorization', 'Bearer access token')); - - if (body == null) { - body = { - 'url': url.resolve('/upload').toString(), - 'fields': { - 'field1': 'value1', - 'field2': 'value2' - } - }; - } - - return new shelf.Response.ok(JSON.encode(body), headers: { - 'content-type': 'application/json' - }); - }); - }); -} - -void handleUpload(ScheduledServer server) { - server.handle('POST', '/upload', (request) { - // TODO(nweiz): Once a multipart/form-data parser in Dart exists, validate - // that the request body is correctly formatted. See issue 6952. - return drainStream( - request.read()).then( - (_) => - server.url).then((url) => new shelf.Response.found(url.resolve('/create'))); - }); -} - diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/ignores_updated_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/ignores_updated_pubspec_test.dart deleted file mode 100644 index df4f670f4ca..00000000000 --- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/ignores_updated_pubspec_test.dart +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("uses what's in the lockfile regardless of the pubspec", () { - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "1.0.0")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": path.join(sandboxDir, "foo") - } - })]).create(); - - pubGet(); - - // Add a dependency on "bar" and remove "foo", but don't run "pub get". - d.dir(appPath, [d.appPubspec({ - "bar": "any" - })]).create(); - - // Note: Using canonicalize here because pub gets the path to the - // entrypoint package from the working directory, which has had symlinks - // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we - // need to accomodate that. - schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: { - "packages": { - "foo": path.join(sandboxDir, "foo", "lib"), - "myapp": canonicalize(path.join(sandboxDir, appPath, "lib")) - }, - "input_files": [ - canonicalize(path.join(sandboxDir, appPath, "pubspec.lock")), - canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/includes_dev_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/includes_dev_dependencies_test.dart deleted file mode 100644 index b12201344de..00000000000 --- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/includes_dev_dependencies_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('includes dev dependencies in the results', () { - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "1.0.0")]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dev_dependencies": { - "foo": { - "path": path.join(sandboxDir, "foo") - } - } - })]).create(); - - pubGet(); - - // Note: Using canonicalize here because pub gets the path to the - // entrypoint package from the working directory, which has had symlinks - // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we - // need to accomodate that. - schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: { - "packages": { - "foo": path.join(sandboxDir, "foo", "lib"), - "myapp": canonicalize(path.join(sandboxDir, appPath, "lib")) - }, - "input_files": [ - canonicalize(path.join(sandboxDir, appPath, "pubspec.lock")), - canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lists_dependency_directories_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/lists_dependency_directories_test.dart deleted file mode 100644 index c9725c3443c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lists_dependency_directories_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('prints the local paths to all packages in the lockfile', () { - servePackages((builder) => builder.serve("bar", "1.0.0")); - - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "1.0.0")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": path.join(sandboxDir, "foo") - }, - "bar": "any" - })]).create(); - - pubGet(); - - // Note: Using canonicalize here because pub gets the path to the - // entrypoint package from the working directory, which has had symlinks - // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we - // need to accomodate that. - schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: { - "packages": { - "foo": path.join(sandboxDir, "foo", "lib"), - "bar": port.then( - (p) => - path.join( - sandboxDir, - cachePath, - "hosted", - "localhost%58$p", - "bar-1.0.0", - "lib")), - "myapp": canonicalize(path.join(sandboxDir, appPath, "lib")) - }, - "input_files": [ - canonicalize(path.join(sandboxDir, appPath, "pubspec.lock")), - canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml"))] - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lockfile_error_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/lockfile_error_test.dart deleted file mode 100644 index d9b872a7c5f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/lockfile_error_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("reports the lockfile path when there is an error in it", () { - d.dir( - appPath, - [d.appPubspec(), d.file("pubspec.lock", "some bad yaml")]).create(); - - schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: { - "error": contains('The lockfile must be a YAML mapping.'), - "path": canonicalize(path.join(sandboxDir, appPath, "pubspec.lock")) - }, exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/missing_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/missing_pubspec_test.dart deleted file mode 100644 index 0838cd2171b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/missing_pubspec_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - // This is a regression test for #20065. - integration("reports a missing pubspec error using JSON", () { - d.dir(appPath).create(); - - schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: { - "error": 'Could not find a file named "pubspec.yaml" in "' - '${canonicalize(path.join(sandboxDir, appPath))}".', - "path": canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml")) - }, exitCode: 1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/no_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/no_lockfile_test.dart deleted file mode 100644 index 7bc95704465..00000000000 --- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/no_lockfile_test.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('with no lockfile, exits with error', () { - d.dir(appPath, [d.appPubspec()]).create(); - - schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: { - "error": 'Package "myapp" has no lockfile. Please run "pub get" first.' - }, exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/list_package_dirs/pubspec_error_test.dart b/sdk/lib/_internal/pub_generated/test/list_package_dirs/pubspec_error_test.dart deleted file mode 100644 index 5610e81a988..00000000000 --- a/sdk/lib/_internal/pub_generated/test/list_package_dirs/pubspec_error_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("reports the pubspec path when there is an error in it", () { - d.dir(appPath, [d.file("pubspec.yaml", "some bad yaml")]).create(); - - schedulePub(args: ["list-package-dirs", "--format=json"], outputJson: { - "error": contains('Error on line 1'), - "path": canonicalize(path.join(sandboxDir, appPath, "pubspec.yaml")) - }, exitCode: exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/lock_file_test.dart b/sdk/lib/_internal/pub_generated/test/lock_file_test.dart deleted file mode 100644 index de144c2a5b4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/lock_file_test.dart +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library lock_file_test; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; -import 'package:unittest/unittest.dart'; -import 'package:yaml/yaml.dart'; - -import '../lib/src/lock_file.dart'; -import '../lib/src/package.dart'; -import '../lib/src/pubspec.dart'; -import '../lib/src/source.dart'; -import '../lib/src/source_registry.dart'; -import 'test_pub.dart'; - -class MockSource extends Source { - final String name = 'mock'; - - Future doDescribe(PackageId id) => - throw new UnsupportedError("Cannot describe mock packages."); - - Future get(PackageId id, String symlink) => - throw new UnsupportedError("Cannot get a mock package."); - - Future getDirectory(PackageId id) => - throw new UnsupportedError("Cannot get the directory for mock packages."); - - dynamic parseDescription(String filePath, String description, - {bool fromLockFile: false}) { - if (!description.endsWith(' desc')) throw new FormatException(); - return description; - } - - bool descriptionsEqual(description1, description2) => - description1 == description2; - - String packageName(String description) { - // Strip off ' desc'. - return description.substring(0, description.length - 5); - } -} - -main() { - initConfig(); - - var sources = new SourceRegistry(); - var mockSource = new MockSource(); - sources.register(mockSource); - - group('LockFile', () { - group('parse()', () { - test('returns an empty lockfile if the contents are empty', () { - var lockFile = new LockFile.parse('', sources); - expect(lockFile.packages.length, equals(0)); - }); - - test('returns an empty lockfile if the contents are whitespace', () { - var lockFile = new LockFile.parse(' \t\n ', sources); - expect(lockFile.packages.length, equals(0)); - }); - - test('parses a series of package descriptions', () { - var lockFile = new LockFile.parse(''' -packages: - bar: - version: 1.2.3 - source: mock - description: bar desc - foo: - version: 2.3.4 - source: mock - description: foo desc -''', sources); - - expect(lockFile.packages.length, equals(2)); - - var bar = lockFile.packages['bar']; - expect(bar.name, equals('bar')); - expect(bar.version, equals(new Version(1, 2, 3))); - expect(bar.source, equals(mockSource.name)); - expect(bar.description, equals('bar desc')); - - var foo = lockFile.packages['foo']; - expect(foo.name, equals('foo')); - expect(foo.version, equals(new Version(2, 3, 4))); - expect(foo.source, equals(mockSource.name)); - expect(foo.description, equals('foo desc')); - }); - - test("allows an unknown source", () { - var lockFile = new LockFile.parse(''' -packages: - foo: - source: bad - version: 1.2.3 - description: foo desc -''', sources); - var foo = lockFile.packages['foo']; - expect(foo.source, equals('bad')); - }); - - test("allows an empty dependency map", () { - var lockFile = new LockFile.parse(''' -packages: -''', sources); - expect(lockFile.packages, isEmpty); - }); - - test("throws if the top level is not a map", () { - expect(() { - new LockFile.parse(''' -not a map -''', sources); - }, throwsFormatException); - }); - - test("throws if the contents of 'packages' is not a map", () { - expect(() { - new LockFile.parse(''' -packages: not a map -''', sources); - }, throwsFormatException); - }); - - test("throws if the version is missing", () { - expect(() { - new LockFile.parse(''' -packages: - foo: - source: mock - description: foo desc -''', sources); - }, throwsFormatException); - }); - - test("throws if the version is invalid", () { - expect(() { - new LockFile.parse(''' -packages: - foo: - version: vorpal - source: mock - description: foo desc -''', sources); - }, throwsFormatException); - }); - - test("throws if the source is missing", () { - expect(() { - new LockFile.parse(''' -packages: - foo: - version: 1.2.3 - description: foo desc -''', sources); - }, throwsFormatException); - }); - - test("throws if the description is missing", () { - expect(() { - new LockFile.parse(''' -packages: - foo: - version: 1.2.3 - source: mock -''', sources); - }, throwsFormatException); - }); - - test("throws if the description is invalid", () { - expect(() { - new LockFile.parse(''' -packages: - foo: - version: 1.2.3 - source: mock - description: foo desc is bad -''', sources); - }, throwsFormatException); - }); - - test("ignores extra stuff in file", () { - var lockFile = new LockFile.parse(''' -extra: - some: stuff -packages: - foo: - bonus: not used - version: 1.2.3 - source: mock - description: foo desc -''', sources); - }); - }); - - group('serialize()', () { - var lockfile; - setUp(() { - lockfile = new LockFile.empty(); - }); - - test('dumps the lockfile to YAML', () { - lockfile.packages['foo'] = - new PackageId('foo', mockSource.name, new Version.parse('1.2.3'), 'foo desc'); - lockfile.packages['bar'] = - new PackageId('bar', mockSource.name, new Version.parse('3.2.1'), 'bar desc'); - - expect(loadYaml(lockfile.serialize(null, sources)), equals({ - 'packages': { - 'foo': { - 'version': '1.2.3', - 'source': 'mock', - 'description': 'foo desc' - }, - 'bar': { - 'version': '3.2.1', - 'source': 'mock', - 'description': 'bar desc' - } - } - })); - }); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/no_package_symlinks_test.dart b/sdk/lib/_internal/pub_generated/test/no_package_symlinks_test.dart deleted file mode 100644 index 720561bff7c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/no_package_symlinks_test.dart +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - group("with --no-package-symlinks", () { - integration("installs hosted dependencies to the cache", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("bar", "1.0.0"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubCommand(command, args: ["--no-package-symlinks"]); - - d.nothing("$appPath/packages").validate(); - - d.hostedCache( - [ - d.dir( - "foo-1.0.0", - [d.dir("lib", [d.file("foo.dart", 'main() => "foo 1.0.0";')])]), - d.dir( - "bar-1.0.0", - [d.dir("lib", [d.file("bar.dart", 'main() => "bar 1.0.0";')])])]).validate(); - }); - - integration("installs git dependencies to the cache", () { - ensureGit(); - - d.git( - 'foo.git', - [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubCommand(command, args: ["--no-package-symlinks"]); - - d.nothing("$appPath/packages").validate(); - - d.dir( - cachePath, - [ - d.dir( - 'git', - [ - d.dir('cache', [d.gitPackageRepoCacheDir('foo')]), - d.gitPackageRevisionCacheDir('foo')])]).validate(); - }); - - integration("locks path dependencies", () { - d.dir("foo", [d.libDir("foo"), d.libPubspec("foo", "0.0.1")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubCommand(command, args: ["--no-package-symlinks"]); - - d.nothing("$appPath/packages").validate(); - d.matcherFile("$appPath/pubspec.lock", contains("foo")); - }); - - integration("removes package directories near entrypoints", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("packages"), - d.dir("bin/packages"), - d.dir("web/packages"), - d.dir("web/subdir/packages")]).create(); - - pubCommand(command, args: ["--no-package-symlinks"]); - - d.dir( - appPath, - [ - d.nothing("packages"), - d.nothing("bin/packages"), - d.nothing("web/packages"), - d.nothing("web/subdir/packages")]).validate(); - }); - - integration( - "doesn't remove package directories that pub wouldn't " "generate", - () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("packages"), - d.dir("bin/subdir/packages"), - d.dir("lib/packages")]).create(); - - pubCommand(command, args: ["--no-package-symlinks"]); - - d.dir( - appPath, - [ - d.nothing("packages"), - d.dir("bin/subdir/packages"), - d.dir("lib/packages")]).validate(); - }); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/utils.dart b/sdk/lib/_internal/pub_generated/test/oauth2/utils.dart deleted file mode 100644 index 8c6f8249458..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/utils.dart +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library oauth2.utils; - -import 'dart:convert'; - -import 'package:http/http.dart' as http; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/utils.dart'; - -void authorizePub(ScheduledProcess pub, ScheduledServer server, - [String accessToken = "access token"]) { - pub.stdout.expect( - 'Pub needs your authorization to upload packages on your ' 'behalf.'); - - schedule(() { - return pub.stdout.next().then((line) { - var match = - new RegExp(r'[?&]redirect_uri=([0-9a-zA-Z.%+-]+)[$&]').firstMatch(line); - expect(match, isNotNull); - - var redirectUrl = Uri.parse(Uri.decodeComponent(match.group(1))); - redirectUrl = addQueryParameters(redirectUrl, { - 'code': 'access code' - }); - return (new http.Request('GET', redirectUrl)..followRedirects = - false).send(); - }).then((response) { - expect( - response.headers['location'], - equals('http://pub.dartlang.org/authorized')); - }); - }); - - handleAccessTokenRequest(server, accessToken); -} - -void handleAccessTokenRequest(ScheduledServer server, String accessToken) { - server.handle('POST', '/token', (request) { - return request.readAsString().then((body) { - expect(body, matches(new RegExp(r'(^|&)code=access\+code(&|$)'))); - - return new shelf.Response.ok(JSON.encode({ - "access_token": accessToken, - "token_type": "bearer" - }), headers: { - 'content-type': 'application/json' - }); - }); - }); -} - diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_malformed_credentials_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_a_malformed_credentials_authenticates_again_test.dart deleted file mode 100644 index 48600b5a701..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_malformed_credentials_authenticates_again_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - 'with a malformed credentials.json, authenticates again and ' - 'saves credentials.json', - () { - d.validPackage.create(); - - var server = new ScheduledServer(); - d.dir(cachePath, [d.file('credentials.json', '{bad json')]).create(); - - var pub = startPublish(server); - confirmPublish(pub); - authorizePub(pub, server, "new access token"); - - server.handle('GET', '/api/packages/versions/new', (request) { - expect( - request.headers, - containsPair('authorization', 'Bearer new access token')); - - return new shelf.Response(200); - }); - - // After we give pub an invalid response, it should crash. We wait for it to - // do so rather than killing it so it'll write out the credentials file. - pub.shouldExit(1); - - d.credentialsFile(server, 'new access token').validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_pre_existing_credentials_does_not_authenticate_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_a_pre_existing_credentials_does_not_authenticate_test.dart deleted file mode 100644 index f1ee88a519f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_pre_existing_credentials_does_not_authenticate_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('with a pre-existing credentials.json does not authenticate', () { - d.validPackage.create(); - - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - confirmPublish(pub); - - server.handle('GET', '/api/packages/versions/new', (request) { - expect( - request.headers, - containsPair('authorization', 'Bearer access token')); - - return new shelf.Response(200); - }); - - pub.kill(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_server_rejected_refresh_token_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_a_server_rejected_refresh_token_authenticates_again_test.dart deleted file mode 100644 index f613ebc3928..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/with_a_server_rejected_refresh_token_authenticates_again_test.dart +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - // Regression test for issue 8849. - integration( - 'with a server-rejected refresh token, authenticates again and ' - 'saves credentials.json', - () { - d.validPackage.create(); - - var server = new ScheduledServer(); - d.credentialsFile( - server, - 'access token', - refreshToken: 'bad refresh token', - expiration: new DateTime.now().subtract(new Duration(hours: 1))).create(); - - var pub = startPublish(server); - - confirmPublish(pub); - - server.handle('POST', '/token', (request) { - return drainStream(request.read()).then((_) { - return new shelf.Response(400, body: JSON.encode({ - "error": "invalid_request" - }), headers: { - 'content-type': 'application/json' - }); - }); - }); - - pub.stdout.expect(startsWith('Uploading...')); - authorizePub(pub, server, 'new access token'); - - server.handle('GET', '/api/packages/versions/new', (request) { - expect( - request.headers, - containsPair('authorization', 'Bearer new access token')); - - return new shelf.Response(200); - }); - - pub.kill(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_refreshes_and_saves_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_refreshes_and_saves_test.dart deleted file mode 100644 index 82b7c4a5d09..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_refreshes_and_saves_test.dart +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - 'with an expired credentials.json, refreshes and saves the ' - 'refreshed access token to credentials.json', - () { - d.validPackage.create(); - - var server = new ScheduledServer(); - d.credentialsFile( - server, - 'access token', - refreshToken: 'refresh token', - expiration: new DateTime.now().subtract(new Duration(hours: 1))).create(); - - var pub = startPublish(server); - confirmPublish(pub); - - server.handle('POST', '/token', (request) { - return request.readAsString().then((body) { - expect( - body, - matches(new RegExp(r'(^|&)refresh_token=refresh\+token(&|$)'))); - - return new shelf.Response.ok(JSON.encode({ - "access_token": "new access token", - "token_type": "bearer" - }), headers: { - 'content-type': 'application/json' - }); - }); - }); - - server.handle('GET', '/api/packages/versions/new', (request) { - expect( - request.headers, - containsPair('authorization', 'Bearer new access token')); - - return new shelf.Response(200); - }); - - pub.shouldExit(); - - d.credentialsFile( - server, - 'new access token', - refreshToken: 'refresh token').validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_without_a_refresh_token_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_without_a_refresh_token_authenticates_again_test.dart deleted file mode 100644 index 4dabe89f5c0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/with_an_expired_credentials_without_a_refresh_token_authenticates_again_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - 'with an expired credentials.json without a refresh token, ' - 'authenticates again and saves credentials.json', - () { - d.validPackage.create(); - - var server = new ScheduledServer(); - d.credentialsFile( - server, - 'access token', - expiration: new DateTime.now().subtract(new Duration(hours: 1))).create(); - - var pub = startPublish(server); - confirmPublish(pub); - - pub.stderr.expect( - "Pub's authorization to upload packages has expired and " - "can't be automatically refreshed."); - authorizePub(pub, server, "new access token"); - - server.handle('GET', '/api/packages/versions/new', (request) { - expect( - request.headers, - containsPair('authorization', 'Bearer new access token')); - - return new shelf.Response(200); - }); - - // After we give pub an invalid response, it should crash. We wait for it to - // do so rather than killing it so it'll write out the credentials file. - pub.shouldExit(1); - - d.credentialsFile(server, 'new access token').validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_no_credentials_authenticates_and_saves_credentials_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_no_credentials_authenticates_and_saves_credentials_test.dart deleted file mode 100644 index a6a65518b32..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/with_no_credentials_authenticates_and_saves_credentials_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - 'with no credentials.json, authenticates and saves ' 'credentials.json', - () { - d.validPackage.create(); - - var server = new ScheduledServer(); - var pub = startPublish(server); - confirmPublish(pub); - authorizePub(pub, server); - - server.handle('GET', '/api/packages/versions/new', (request) { - expect( - request.headers, - containsPair('authorization', 'Bearer access token')); - - return new shelf.Response(200); - }); - - // After we give pub an invalid response, it should crash. We wait for it to - // do so rather than killing it so it'll write out the credentials file. - pub.shouldExit(1); - - d.credentialsFile(server, 'access token').validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/oauth2/with_server_rejected_credentials_authenticates_again_test.dart b/sdk/lib/_internal/pub_generated/test/oauth2/with_server_rejected_credentials_authenticates_again_test.dart deleted file mode 100644 index 75b6abbd470..00000000000 --- a/sdk/lib/_internal/pub_generated/test/oauth2/with_server_rejected_credentials_authenticates_again_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - 'with server-rejected credentials, authenticates again and saves ' - 'credentials.json', - () { - d.validPackage.create(); - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPublish(server); - - confirmPublish(pub); - - server.handle('GET', '/api/packages/versions/new', (request) { - return new shelf.Response(401, body: JSON.encode({ - 'error': { - 'message': 'your token sucks' - } - }), headers: { - 'www-authenticate': 'Bearer error="invalid_token",' - ' error_description="your token sucks"' - }); - }); - - pub.stderr.expect('OAuth2 authorization failed (your token sucks).'); - pub.stdout.expect(startsWith('Uploading...')); - pub.kill(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/package_list_files_test.dart b/sdk/lib/_internal/pub_generated/test/package_list_files_test.dart deleted file mode 100644 index 7d48927b356..00000000000 --- a/sdk/lib/_internal/pub_generated/test/package_list_files_test.dart +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library packages_list_files_test; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../lib/src/entrypoint.dart'; -import '../lib/src/io.dart'; -import '../lib/src/system_cache.dart'; -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -String root; -Entrypoint entrypoint; - -main() { - initConfig(); - - group('not in a git repo', () { - setUp(() { - d.appDir().create(); - scheduleEntrypoint(); - }); - - - integration('lists files recursively', () { - d.dir( - appPath, - [ - d.file('file1.txt', 'contents'), - d.file('file2.txt', 'contents'), - d.dir( - 'subdir', - [ - d.file('subfile1.txt', 'subcontents'), - d.file('subfile2.txt', 'subcontents')])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(), - unorderedEquals( - [ - path.join(root, 'pubspec.yaml'), - path.join(root, 'file1.txt'), - path.join(root, 'file2.txt'), - path.join(root, 'subdir', 'subfile1.txt'), - path.join(root, 'subdir', 'subfile2.txt')])); - }); - }); - - commonTests(); - }); - - group('with git', () { - setUp(() { - ensureGit(); - d.git(appPath, [d.appPubspec()]).create(); - scheduleEntrypoint(); - }); - - integration("includes files that are or aren't checked in", () { - d.dir( - appPath, - [ - d.file('file1.txt', 'contents'), - d.file('file2.txt', 'contents'), - d.dir( - 'subdir', - [ - d.file('subfile1.txt', 'subcontents'), - d.file('subfile2.txt', 'subcontents')])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(), - unorderedEquals( - [ - path.join(root, 'pubspec.yaml'), - path.join(root, 'file1.txt'), - path.join(root, 'file2.txt'), - path.join(root, 'subdir', 'subfile1.txt'), - path.join(root, 'subdir', 'subfile2.txt')])); - }); - }); - - integration("ignores files that are gitignored if desired", () { - d.dir( - appPath, - [ - d.file('.gitignore', '*.txt'), - d.file('file1.txt', 'contents'), - d.file('file2.text', 'contents'), - d.dir( - 'subdir', - [ - d.file('subfile1.txt', 'subcontents'), - d.file('subfile2.text', 'subcontents')])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(useGitIgnore: true), - unorderedEquals( - [ - path.join(root, 'pubspec.yaml'), - path.join(root, '.gitignore'), - path.join(root, 'file2.text'), - path.join(root, 'subdir', 'subfile2.text')])); - }); - - schedule(() { - expect( - entrypoint.root.listFiles(), - unorderedEquals( - [ - path.join(root, 'pubspec.yaml'), - path.join(root, 'file1.txt'), - path.join(root, 'file2.text'), - path.join(root, 'subdir', 'subfile1.txt'), - path.join(root, 'subdir', 'subfile2.text')])); - }); - }); - - commonTests(); - }); -} - -void scheduleEntrypoint() { - schedule(() { - root = path.join(sandboxDir, appPath); - entrypoint = - new Entrypoint(root, new SystemCache.withSources(rootDir: root)); - }, 'initializing entrypoint'); - - currentSchedule.onComplete.schedule(() { - entrypoint = null; - }, 'nulling entrypoint'); -} - -void commonTests() { - integration('ignores broken symlinks', () { - // Windows requires us to symlink to a directory that actually exists. - d.dir(appPath, [d.dir('target')]).create(); - scheduleSymlink(path.join(appPath, 'target'), path.join(appPath, 'link')); - schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'target'))); - - schedule(() { - expect( - entrypoint.root.listFiles(), - equals([path.join(root, 'pubspec.yaml')])); - }); - }); - - integration('ignores pubspec.lock files', () { - d.dir( - appPath, - [d.file('pubspec.lock'), d.dir('subdir', [d.file('pubspec.lock')])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(), - equals([path.join(root, 'pubspec.yaml')])); - }); - }); - - integration('ignores packages directories', () { - d.dir( - appPath, - [ - d.dir('packages', [d.file('file.txt', 'contents')]), - d.dir( - 'subdir', - [d.dir('packages', [d.file('subfile.txt', 'subcontents')]),])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(), - equals([path.join(root, 'pubspec.yaml')])); - }); - }); - - integration('allows pubspec.lock directories', () { - d.dir( - appPath, - [d.dir('pubspec.lock', [d.file('file.txt', 'contents'),])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(), - unorderedEquals( - [ - path.join(root, 'pubspec.yaml'), - path.join(root, 'pubspec.lock', 'file.txt')])); - }); - }); - - group('and "beneath"', () { - integration('only lists files beneath the given root', () { - d.dir( - appPath, - [ - d.file('file1.txt', 'contents'), - d.file('file2.txt', 'contents'), - d.dir( - 'subdir', - [ - d.file('subfile1.txt', 'subcontents'), - d.file('subfile2.txt', 'subcontents'), - d.dir( - 'subsubdir', - [ - d.file('subsubfile1.txt', 'subsubcontents'), - d.file('subsubfile2.txt', 'subsubcontents'),])])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(beneath: path.join(root, 'subdir')), - unorderedEquals( - [ - path.join(root, 'subdir', 'subfile1.txt'), - path.join(root, 'subdir', 'subfile2.txt'), - path.join(root, 'subdir', 'subsubdir', 'subsubfile1.txt'), - path.join(root, 'subdir', 'subsubdir', 'subsubfile2.txt')])); - }); - }); - - integration("doesn't care if the root is blacklisted", () { - d.dir( - appPath, - [ - d.file('file1.txt', 'contents'), - d.file('file2.txt', 'contents'), - d.dir( - 'packages', - [ - d.file('subfile1.txt', 'subcontents'), - d.file('subfile2.txt', 'subcontents'), - d.dir( - 'subsubdir', - [ - d.file('subsubfile1.txt', 'subsubcontents'), - d.file('subsubfile2.txt', 'subsubcontents')])])]).create(); - - schedule(() { - expect( - entrypoint.root.listFiles(beneath: path.join(root, 'packages')), - unorderedEquals( - [ - path.join(root, 'packages', 'subfile1.txt'), - path.join(root, 'packages', 'subfile2.txt'), - path.join(root, 'packages', 'subsubdir', 'subsubfile1.txt'), - path.join(root, 'packages', 'subsubdir', 'subsubfile2.txt')])); - }); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/preprocess_test.dart b/sdk/lib/_internal/pub_generated/test/preprocess_test.dart deleted file mode 100644 index 0cd4eadd0d0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/preprocess_test.dart +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub.test.preprocess_test; - -import 'package:pub_semver/pub_semver.dart'; -import 'package:unittest/unittest.dart'; - -import '../lib/src/preprocess.dart'; -import 'test_pub.dart'; - -main() { - initConfig(); - - test("does nothing on a file without preprocessor directives", () { - var text = ''' -some text -// normal comment -// # - //# not beginning of line -'''; - - expect(_preprocess(text), equals(text)); - }); - - test("allows bare insert directive", () { - expect(_preprocess('//> foo'), equals('foo')); - }); - - test("allows empty insert directive", () { - expect(_preprocess(''' -//> foo -//> -//> bar -'''), equals('foo\n\nbar\n')); - }); - - group("if", () { - group("with a version range", () { - test("removes sections with non-matching versions", () { - expect(_preprocess(''' -before -//# if barback <1.0.0 -inside -//# end -after -'''), equals(''' -before -after -''')); - }); - - test("doesn't insert section with non-matching versions", () { - expect(_preprocess(''' -before -//# if barback <1.0.0 -//> inside -//# end -after -'''), equals(''' -before -after -''')); - }); - - test("doesn't remove sections with matching versions", () { - expect(_preprocess(''' -before -//# if barback >1.0.0 -inside -//# end -after -'''), equals(''' -before -inside -after -''')); - }); - - test("inserts sections with matching versions", () { - expect(_preprocess(''' -before -//# if barback >1.0.0 -//> inside -//# end -after -'''), equals(''' -before -inside -after -''')); - }); - - test("allows multi-element version ranges", () { - expect(_preprocess(''' -before -//# if barback >=1.0.0 <2.0.0 -inside 1 -//# end -//# if barback >=0.9.0 <1.0.0 -inside 2 -//# end -after -'''), equals(''' -before -inside 1 -after -''')); - }); - }); - - group("with a package name", () { - test("removes sections for a nonexistent package", () { - expect(_preprocess(''' -before -//# if fblthp -inside -//# end -after -'''), equals(''' -before -after -''')); - }); - - test("doesn't insert sections for a nonexistent package", () { - expect(_preprocess(''' -before -//# if fblthp -//> inside -//# end -after -'''), equals(''' -before -after -''')); - }); - - test("doesn't remove sections with an existent package", () { - expect(_preprocess(''' -before -//# if barback -inside -//# end -after -'''), equals(''' -before -inside -after -''')); - }); - - test("inserts sections with an existent package", () { - expect(_preprocess(''' -before -//# if barback -//> inside -//# end -after -'''), equals(''' -before -inside -after -''')); - }); - }); - }); - - group("else", () { - test("removes non-matching sections", () { - expect(_preprocess(''' -before -//# if barback >1.0.0 -inside 1 -//# else -inside 2 -//# end -after -'''), equals(''' -before -inside 1 -after -''')); - }); - - test("doesn't insert non-matching sections", () { - expect(_preprocess(''' -before -//# if barback >1.0.0 -inside 1 -//# else -//> inside 2 -//# end -after -'''), equals(''' -before -inside 1 -after -''')); - }); - - test("doesn't remove matching sections", () { - expect(_preprocess(''' -before -//# if barback <1.0.0 -inside 1 -//# else -inside 2 -//# end -after -'''), equals(''' -before -inside 2 -after -''')); - }); - - test("inserts matching sections", () { - expect(_preprocess(''' -before -//# if barback <1.0.0 -inside 1 -//# else -//> inside 2 -//# end -after -'''), equals(''' -before -inside 2 -after -''')); - }); - }); - - group("errors", () { - test("disallows unknown statements", () { - expect(() => _preprocess('//# foo bar\n//# end'), throwsFormatException); - }); - - test("disallows insert directive without space", () { - expect(() => _preprocess('//>foo'), throwsFormatException); - }); - - group("if", () { - test("disallows if with no arguments", () { - expect(() => _preprocess('//# if\n//# end'), throwsFormatException); - }); - - test("disallows if with no package", () { - expect( - () => _preprocess('//# if <=1.0.0\n//# end'), - throwsFormatException); - }); - - test("disallows invalid version constraint", () { - expect( - () => _preprocess('//# if barback >=1.0\n//# end'), - throwsFormatException); - }); - - test("disallows dangling end", () { - expect(() => _preprocess('//# end'), throwsFormatException); - }); - - test("disallows if without end", () { - expect( - () => _preprocess('//# if barback >=1.0.0'), - throwsFormatException); - }); - - test("disallows nested if", () { - expect(() => _preprocess(''' -//# if barback >=1.0.0 -//# if barback >= 1.5.0 -//# end -//# end -'''), throwsFormatException); - }); - }); - - group("else", () { - test("disallows else without if", () { - expect(() => _preprocess('//# else\n//# end'), throwsFormatException); - }); - - test("disallows else without end", () { - expect( - () => _preprocess('//# if barback >=1.0.0\n//# else'), - throwsFormatException); - }); - - test("disallows else with an argument", () { - expect(() => _preprocess(''' -//# if barback >=1.0.0 -//# else barback <0.5.0 -//# end -'''), throwsFormatException); - }); - }); - }); -} - -String _preprocess(String input) => preprocess(input, { - 'barback': new Version.parse("1.2.3") -}, 'source/url'); diff --git a/sdk/lib/_internal/pub_generated/test/pub_get_and_upgrade_test.dart b/sdk/lib/_internal/pub_generated/test/pub_get_and_upgrade_test.dart deleted file mode 100644 index c4ff0e9c77c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/pub_get_and_upgrade_test.dart +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../lib/src/exit_codes.dart' as exit_codes; -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - group('requires', () { - integration('a pubspec', () { - d.dir(appPath, []).create(); - - pubCommand( - command, - error: new RegExp( - r'Could not find a file named "pubspec.yaml" ' r'in "[^\n]*"\.')); - }); - - integration('a pubspec with a "name" key', () { - d.dir(appPath, [d.pubspec({ - "dependencies": { - "foo": null - } - })]).create(); - - pubCommand( - command, - error: contains('Missing the required "name" field.'), - exitCode: exit_codes.DATA); - }); - }); - - integration('adds itself to the packages', () { - // The symlink should use the name in the pubspec, not the name of the - // directory. - d.dir(appPath, [d.pubspec({ - "name": "myapp_name" - }), d.libDir('myapp_name')]).create(); - - pubCommand(command); - - d.dir( - packagesPath, - [ - d.dir( - "myapp_name", - [d.file('myapp_name.dart', 'main() => "myapp_name";')])]).validate(); - }); - - integration( - 'does not adds itself to the packages if it has no "lib" ' 'directory', - () { - // The symlink should use the name in the pubspec, not the name of the - // directory. - d.dir(appPath, [d.pubspec({ - "name": "myapp_name" - }),]).create(); - - pubCommand(command); - - d.dir(packagesPath, [d.nothing("myapp_name")]).validate(); - }); - - integration( - 'does not add a package if it does not have a "lib" ' 'directory', - () { - // Using a path source, but this should be true of all sources. - d.dir('foo', [d.libPubspec('foo', '0.0.0-not.used')]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubCommand(command); - - d.packagesDir({ - "foo": null - }).validate(); - }); - - integration('reports a solver failure', () { - // myapp depends on foo and bar which both depend on baz with mismatched - // descriptions. - d.dir('deps', [d.dir('foo', [d.pubspec({ - "name": "foo", - "dependencies": { - "baz": { - "path": "../baz1" - } - } - })]), d.dir('bar', [d.pubspec({ - "name": "bar", - "dependencies": { - "baz": { - "path": "../baz2" - } - } - })]), - d.dir('baz1', [d.libPubspec('baz', '0.0.0')]), - d.dir('baz2', [d.libPubspec('baz', '0.0.0')])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../deps/foo" - }, - "bar": { - "path": "../deps/bar" - } - })]).create(); - - pubCommand( - command, - error: new RegExp("^Incompatible dependencies on baz:\n")); - }); - - integration('does not allow a dependency on itself', () { - d.dir(appPath, [d.appPubspec({ - "myapp": { - "path": "." - } - })]).create(); - - pubCommand( - command, - error: contains('A package may not list itself as a dependency.'), - exitCode: exit_codes.DATA); - }); - - integration('does not allow a dev dependency on itself', () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dev_dependencies": { - "myapp": { - "path": "." - } - } - })]).create(); - - pubCommand( - command, - error: contains('A package may not list itself as a dependency.'), - exitCode: exit_codes.DATA); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/pub_test.dart b/sdk/lib/_internal/pub_generated/test/pub_test.dart deleted file mode 100644 index d664fa7fb74..00000000000 --- a/sdk/lib/_internal/pub_generated/test/pub_test.dart +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../lib/src/exit_codes.dart' as exit_codes; -import 'test_pub.dart'; - -main() { - initConfig(); - - integration('running pub with no command displays usage', () { - schedulePub(args: [], output: """ - Pub is a package manager for Dart. - - Usage: pub [arguments] - - Global options: - -h, --help Print this usage information. - --version Print pub version. - --[no-]trace Print debugging information when an error occurs. - --verbosity Control output verbosity. - - [all] Show all output including internal tracing messages. - [io] Also show IO operations. - [normal] Show errors, warnings, and user messages. - [solver] Show steps during version resolution. - - -v, --verbose Shortcut for "--verbosity=all". - - Available commands: - build Apply transformers to build a package. - cache Work with the system cache. - deps Print package dependencies. - downgrade Downgrade the current package's dependencies to oldest versions. - get Get the current package's dependencies. - global Work with global packages. - help Display help information for pub. - publish Publish the current package to pub.dartlang.org. - run Run an executable from a package. - serve Run a local web development server. - upgrade Upgrade the current package's dependencies to latest versions. - uploader Manage uploaders for a package on pub.dartlang.org. - version Print pub version. - - Run "pub help " for more information about a command. - See http://dartlang.org/tools/pub for detailed documentation. - """); - }); - - integration('running pub with just --version displays version', () { - schedulePub(args: ['--version'], output: 'Pub 0.1.2+3'); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/pub_uploader_test.dart b/sdk/lib/_internal/pub_generated/test/pub_uploader_test.dart deleted file mode 100644 index 1047ede875a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/pub_uploader_test.dart +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_uploader_test; - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:shelf/shelf.dart' as shelf; - -import '../lib/src/exit_codes.dart' as exit_codes; -import '../lib/src/utils.dart'; -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -final USAGE_STRING = ''' -Manage uploaders for a package on pub.dartlang.org. - -Usage: pub uploader [options] {add/remove} --h, --help Print this usage information. - --server The package server on which the package is hosted. - (defaults to "https://pub.dartlang.org") - - --package The package whose uploaders will be modified. - (defaults to the current package) - -Run "pub help" to see global options. -See http://dartlang.org/tools/pub/cmd/pub-uploader.html for detailed documentation. -'''; - -ScheduledProcess startPubUploader(ScheduledServer server, List args) { - var tokenEndpoint = - server.url.then((url) => url.resolve('/token').toString()); - args = flatten(['uploader', '--server', tokenEndpoint, args]); - return startPub(args: args, tokenEndpoint: tokenEndpoint); -} - -main() { - initConfig(); - group('displays usage', () { - integration('when run with no arguments', () { - schedulePub( - args: ['uploader'], - output: USAGE_STRING, - exitCode: exit_codes.USAGE); - }); - - integration('when run with only a command', () { - schedulePub( - args: ['uploader', 'add'], - output: USAGE_STRING, - exitCode: exit_codes.USAGE); - }); - - integration('when run with an invalid command', () { - schedulePub( - args: ['uploader', 'foo', 'email'], - output: USAGE_STRING, - exitCode: exit_codes.USAGE); - }); - }); - - integration('adds an uploader', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPubUploader(server, ['--package', 'pkg', 'add', 'email']); - - server.handle('POST', '/api/packages/pkg/uploaders', (request) { - return request.readAsString().then((body) { - expect(body, equals('email=email')); - - return new shelf.Response.ok(JSON.encode({ - 'success': { - 'message': 'Good job!' - } - }), headers: { - 'content-type': 'application/json' - }); - }); - }); - - pub.stdout.expect('Good job!'); - pub.shouldExit(exit_codes.SUCCESS); - }); - - integration('removes an uploader', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPubUploader(server, ['--package', 'pkg', 'remove', 'email']); - - server.handle('DELETE', '/api/packages/pkg/uploaders/email', (request) { - return new shelf.Response.ok(JSON.encode({ - 'success': { - 'message': 'Good job!' - } - }), headers: { - 'content-type': 'application/json' - }); - }); - - pub.stdout.expect('Good job!'); - pub.shouldExit(exit_codes.SUCCESS); - }); - - integration('defaults to the current package', () { - d.validPackage.create(); - - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPubUploader(server, ['add', 'email']); - - server.handle('POST', '/api/packages/test_pkg/uploaders', (request) { - return new shelf.Response.ok(JSON.encode({ - 'success': { - 'message': 'Good job!' - } - }), headers: { - 'content-type': 'application/json' - }); - }); - - pub.stdout.expect('Good job!'); - pub.shouldExit(exit_codes.SUCCESS); - }); - - integration('add provides an error', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPubUploader(server, ['--package', 'pkg', 'add', 'email']); - - server.handle('POST', '/api/packages/pkg/uploaders', (request) { - return new shelf.Response(400, body: JSON.encode({ - 'error': { - 'message': 'Bad job!' - } - }), headers: { - 'content-type': 'application/json' - }); - }); - - pub.stderr.expect('Bad job!'); - pub.shouldExit(1); - }); - - integration('remove provides an error', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = - startPubUploader(server, ['--package', 'pkg', 'remove', 'e/mail']); - - server.handle('DELETE', '/api/packages/pkg/uploaders/e%2Fmail', (request) { - return new shelf.Response(400, body: JSON.encode({ - 'error': { - 'message': 'Bad job!' - } - }), headers: { - 'content-type': 'application/json' - }); - }); - - pub.stderr.expect('Bad job!'); - pub.shouldExit(1); - }); - - integration('add provides invalid JSON', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPubUploader(server, ['--package', 'pkg', 'add', 'email']); - - server.handle( - 'POST', - '/api/packages/pkg/uploaders', - (request) => new shelf.Response.ok("{not json")); - - pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json')); - pub.shouldExit(1); - }); - - integration('remove provides invalid JSON', () { - var server = new ScheduledServer(); - d.credentialsFile(server, 'access token').create(); - var pub = startPubUploader(server, ['--package', 'pkg', 'remove', 'email']); - - server.handle( - 'DELETE', - '/api/packages/pkg/uploaders/email', - (request) => new shelf.Response.ok("{not json")); - - pub.stderr.expect(emitsLines('Invalid server response:\n' '{not json')); - pub.shouldExit(1); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/pubspec_test.dart deleted file mode 100644 index 1418bf9bbfe..00000000000 --- a/sdk/lib/_internal/pub_generated/test/pubspec_test.dart +++ /dev/null @@ -1,558 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pubspec_test; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; -import 'package:unittest/unittest.dart'; - -import '../lib/src/package.dart'; -import '../lib/src/pubspec.dart'; -import '../lib/src/source.dart'; -import '../lib/src/source/path.dart'; -import '../lib/src/source_registry.dart'; -import 'test_pub.dart'; - -class MockSource extends Source { - final String name = "mock"; - - Future doDescribe(PackageId id) => - throw new UnsupportedError("Cannot describe mock packages."); - - Future get(PackageId id, String symlink) => - throw new UnsupportedError("Cannot get a mock package."); - - Future getDirectory(PackageId id) => - throw new UnsupportedError("Cannot get the directory for mock packages."); - - dynamic parseDescription(String filePath, description, {bool fromLockFile: - false}) { - if (description != 'ok') throw new FormatException('Bad'); - return description; - } - - bool descriptionsEqual(description1, description2) => - description1 == description2; - - String packageName(description) => 'foo'; -} - -main() { - initConfig(); - group('parse()', () { - var sources = new SourceRegistry(); - sources.register(new MockSource()); - sources.register(new PathSource()); - - var throwsPubspecException = - throwsA(new isInstanceOf('PubspecException')); - - expectPubspecException(String contents, fn(Pubspec pubspec), - [String expectedContains]) { - var expectation = throwsPubspecException; - if (expectedContains != null) { - expectation = throwsA( - allOf( - new isInstanceOf('PubspecException'), - predicate((error) => error.message.contains(expectedContains)))); - } - - var pubspec = new Pubspec.parse(contents, sources); - expect(() => fn(pubspec), expectation); - } - - test("doesn't eagerly throw an error for an invalid field", () { - // Shouldn't throw an error. - new Pubspec.parse('version: not a semver', sources); - }); - - test( - "eagerly throws an error if the pubspec name doesn't match the " - "expected name", - () { - expect( - () => new Pubspec.parse("name: foo", sources, expectedName: 'bar'), - throwsPubspecException); - }); - - test( - "eagerly throws an error if the pubspec doesn't have a name and an " - "expected name is passed", - () { - expect( - () => new Pubspec.parse("{}", sources, expectedName: 'bar'), - throwsPubspecException); - }); - - test("allows a version constraint for dependencies", () { - var pubspec = new Pubspec.parse(''' -dependencies: - foo: - mock: ok - version: ">=1.2.3 <3.4.5" -''', sources); - - var foo = pubspec.dependencies[0]; - expect(foo.name, equals('foo')); - expect(foo.constraint.allows(new Version(1, 2, 3)), isTrue); - expect(foo.constraint.allows(new Version(1, 2, 5)), isTrue); - expect(foo.constraint.allows(new Version(3, 4, 5)), isFalse); - }); - - test("allows an empty dependencies map", () { - var pubspec = new Pubspec.parse(''' -dependencies: -''', sources); - - expect(pubspec.dependencies, isEmpty); - }); - - test("allows a version constraint for dev dependencies", () { - var pubspec = new Pubspec.parse(''' -dev_dependencies: - foo: - mock: ok - version: ">=1.2.3 <3.4.5" -''', sources); - - var foo = pubspec.devDependencies[0]; - expect(foo.name, equals('foo')); - expect(foo.constraint.allows(new Version(1, 2, 3)), isTrue); - expect(foo.constraint.allows(new Version(1, 2, 5)), isTrue); - expect(foo.constraint.allows(new Version(3, 4, 5)), isFalse); - }); - - test("allows an empty dev dependencies map", () { - var pubspec = new Pubspec.parse(''' -dev_dependencies: -''', sources); - - expect(pubspec.devDependencies, isEmpty); - }); - - test("allows a version constraint for dependency overrides", () { - var pubspec = new Pubspec.parse(''' -dependency_overrides: - foo: - mock: ok - version: ">=1.2.3 <3.4.5" -''', sources); - - var foo = pubspec.dependencyOverrides[0]; - expect(foo.name, equals('foo')); - expect(foo.constraint.allows(new Version(1, 2, 3)), isTrue); - expect(foo.constraint.allows(new Version(1, 2, 5)), isTrue); - expect(foo.constraint.allows(new Version(3, 4, 5)), isFalse); - }); - - test("allows an empty dependency overrides map", () { - var pubspec = new Pubspec.parse(''' -dependency_overrides: -''', sources); - - expect(pubspec.dependencyOverrides, isEmpty); - }); - - test("allows an unknown source", () { - var pubspec = new Pubspec.parse(''' -dependencies: - foo: - unknown: blah -''', sources); - - var foo = pubspec.dependencies[0]; - expect(foo.name, equals('foo')); - expect(foo.source, equals('unknown')); - }); - - test("throws if a package is in dependencies and dev_dependencies", () { - expectPubspecException(''' -dependencies: - foo: - mock: ok -dev_dependencies: - foo: - mock: ok -''', (pubspec) { - // This check only triggers if both [dependencies] and [devDependencies] - // are accessed. - pubspec.dependencies; - pubspec.devDependencies; - }); - }); - - test("throws if it dependes on itself", () { - expectPubspecException(''' -name: myapp -dependencies: - myapp: - mock: ok -''', (pubspec) => pubspec.dependencies); - }); - - test("throws if it has a dev dependency on itself", () { - expectPubspecException(''' -name: myapp -dev_dependencies: - myapp: - mock: ok -''', (pubspec) => pubspec.devDependencies); - }); - - test("throws if it has an override on itself", () { - expectPubspecException(''' -name: myapp -dependency_overrides: - myapp: - mock: ok -''', (pubspec) => pubspec.dependencyOverrides); - }); - - test("throws if the description isn't valid", () { - expectPubspecException(''' -dependencies: - foo: - mock: bad -''', (pubspec) => pubspec.dependencies); - }); - - test("throws if dependency version is not a string", () { - expectPubspecException(''' -dependencies: - foo: - mock: ok - version: 1.2 -''', (pubspec) => pubspec.dependencies); - }); - - test("throws if version is not a version constraint", () { - expectPubspecException(''' -dependencies: - foo: - mock: ok - version: not constraint -''', (pubspec) => pubspec.dependencies); - }); - - test("throws if 'name' is not a string", () { - expectPubspecException( - 'name: [not, a, string]', - (pubspec) => pubspec.name); - }); - - test("throws if version is not a string", () { - expectPubspecException( - 'version: [2, 0, 0]', - (pubspec) => pubspec.version, - '"version" field must be a string'); - }); - - test("throws if version is malformed (looking like a double)", () { - expectPubspecException( - 'version: 2.1', - (pubspec) => pubspec.version, - '"version" field must have three numeric components: major, minor, ' - 'and patch. Instead of "2.1", consider "2.1.0"'); - }); - - test("throws if version is malformed (looking like an int)", () { - expectPubspecException( - 'version: 2', - (pubspec) => pubspec.version, - '"version" field must have three numeric components: major, minor, ' - 'and patch. Instead of "2", consider "2.0.0"'); - }); - - test("throws if version is not a version", () { - expectPubspecException( - 'version: not version', - (pubspec) => pubspec.version); - }); - - test("throws if transformers isn't a list", () { - expectPubspecException( - 'transformers: "not list"', - (pubspec) => pubspec.transformers, - '"transformers" field must be a list'); - }); - - test("throws if a transformer isn't a string or map", () { - expectPubspecException( - 'transformers: [12]', - (pubspec) => pubspec.transformers, - 'A transformer must be a string or map.'); - }); - - test("throws if a transformer's configuration isn't a map", () { - expectPubspecException( - 'transformers: [{pkg: 12}]', - (pubspec) => pubspec.transformers, - "A transformer's configuration must be a map."); - }); - - test( - "throws if a transformer's configuration contains an unknown " - "reserved key at the top level", - () { - expectPubspecException(''' -name: pkg -transformers: [{pkg: {\$key: "value"}}]''', - (pubspec) => pubspec.transformers, - 'Invalid transformer config: Unknown reserved field.'); - }); - - test( - "doesn't throw if a transformer's configuration contains a " - "non-top-level key beginning with a dollar sign", - () { - var pubspec = new Pubspec.parse(''' -name: pkg -transformers: -- pkg: {outer: {\$inner: value}} -''', sources); - - var pkg = pubspec.transformers[0].single; - expect(pkg.configuration["outer"]["\$inner"], equals("value")); - }); - - test("throws if the \$include value is not a string or list", () { - expectPubspecException(''' -name: pkg -transformers: -- pkg: {\$include: 123}''', - (pubspec) => pubspec.transformers, - 'Invalid transformer config: "\$include" field must be a string or ' 'list.'); - }); - - test("throws if the \$include list contains a non-string", () { - expectPubspecException(''' -name: pkg -transformers: -- pkg: {\$include: ["ok", 123, "alright", null]}''', - (pubspec) => pubspec.transformers, - 'Invalid transformer config: "\$include" field may contain only ' 'strings.'); - }); - - test("throws if the \$exclude value is not a string or list", () { - expectPubspecException(''' -name: pkg -transformers: -- pkg: {\$exclude: 123}''', - (pubspec) => pubspec.transformers, - 'Invalid transformer config: "\$exclude" field must be a string or ' 'list.'); - }); - - test("throws if the \$exclude list contains a non-string", () { - expectPubspecException(''' -name: pkg -transformers: -- pkg: {\$exclude: ["ok", 123, "alright", null]}''', - (pubspec) => pubspec.transformers, - 'Invalid transformer config: "\$exclude" field may contain only ' 'strings.'); - }); - - test("throws if a transformer is not from a dependency", () { - expectPubspecException(''' -name: pkg -transformers: [foo] -''', (pubspec) => pubspec.transformers, '"foo" is not a dependency.'); - }); - - test("allows a transformer from a normal dependency", () { - var pubspec = new Pubspec.parse(''' -name: pkg -dependencies: - foo: - mock: ok -transformers: -- foo''', sources); - - expect(pubspec.transformers[0].single.id.package, equals("foo")); - }); - - test("allows a transformer from a dev dependency", () { - var pubspec = new Pubspec.parse(''' -name: pkg -dev_dependencies: - foo: - mock: ok -transformers: -- foo''', sources); - - expect(pubspec.transformers[0].single.id.package, equals("foo")); - }); - - test("allows a transformer from a dependency override", () { - var pubspec = new Pubspec.parse(''' -name: pkg -dependency_overrides: - foo: - mock: ok -transformers: -- foo''', sources); - - expect(pubspec.transformers[0].single.id.package, equals("foo")); - }); - - test("allows comment-only files", () { - var pubspec = new Pubspec.parse(''' -# No external dependencies yet -# Including for completeness -# ...and hoping the spec expands to include details about author, version, etc -# See http://www.dartlang.org/docs/pub-package-manager/ for details -''', sources); - expect(pubspec.version, equals(Version.none)); - expect(pubspec.dependencies, isEmpty); - }); - - test("throws a useful error for unresolvable path dependencies", () { - expectPubspecException(''' -name: pkg -dependencies: - from_path: {path: non_local_path} -''', - (pubspec) => pubspec.dependencies, - '"non_local_path" is a relative path, but this isn\'t a local ' 'pubspec.'); - }); - - group("environment", () { - test("defaults to any SDK constraint if environment is omitted", () { - var pubspec = new Pubspec.parse('', sources); - expect(pubspec.environment.sdkVersion, equals(VersionConstraint.any)); - }); - - test("allows an empty environment map", () { - var pubspec = new Pubspec.parse(''' -environment: -''', sources); - expect(pubspec.environment.sdkVersion, equals(VersionConstraint.any)); - }); - - test("throws if the environment value isn't a map", () { - expectPubspecException( - 'environment: []', - (pubspec) => pubspec.environment); - }); - - test("allows a version constraint for the sdk", () { - var pubspec = new Pubspec.parse(''' -environment: - sdk: ">=1.2.3 <2.3.4" -''', sources); - expect( - pubspec.environment.sdkVersion, - equals(new VersionConstraint.parse(">=1.2.3 <2.3.4"))); - }); - - test("throws if the sdk isn't a string", () { - expectPubspecException( - 'environment: {sdk: []}', - (pubspec) => pubspec.environment); - expectPubspecException( - 'environment: {sdk: 1.0}', - (pubspec) => pubspec.environment); - }); - - test("throws if the sdk isn't a valid version constraint", () { - expectPubspecException( - 'environment: {sdk: "oopies"}', - (pubspec) => pubspec.environment); - }); - }); - - group("publishTo", () { - test("defaults to null if omitted", () { - var pubspec = new Pubspec.parse('', sources); - expect(pubspec.publishTo, isNull); - }); - - test("throws if not a string", () { - expectPubspecException( - 'publish_to: 123', - (pubspec) => pubspec.publishTo); - }); - - test("allows a URL", () { - var pubspec = new Pubspec.parse(''' -publish_to: http://example.com -''', sources); - expect(pubspec.publishTo, equals("http://example.com")); - }); - - test("allows none", () { - var pubspec = new Pubspec.parse(''' -publish_to: none -''', sources); - expect(pubspec.publishTo, equals("none")); - }); - - test("throws on other strings", () { - expectPubspecException( - 'publish_to: http://bad.url:not-port', - (pubspec) => pubspec.publishTo); - }); - }); - - group("executables", () { - test("defaults to an empty map if omitted", () { - var pubspec = new Pubspec.parse('', sources); - expect(pubspec.executables, isEmpty); - }); - - test("allows simple names for keys and most characters in values", () { - var pubspec = new Pubspec.parse(''' -executables: - abcDEF-123_: "abc DEF-123._" -''', sources); - expect(pubspec.executables['abcDEF-123_'], equals('abc DEF-123._')); - }); - - test("throws if not a map", () { - expectPubspecException( - 'executables: not map', - (pubspec) => pubspec.executables); - }); - - test("throws if key is not a string", () { - expectPubspecException( - 'executables: {123: value}', - (pubspec) => pubspec.executables); - }); - - test("throws if a key isn't a simple name", () { - expectPubspecException( - 'executables: {funny/name: ok}', - (pubspec) => pubspec.executables); - }); - - test("throws if a value is not a string", () { - expectPubspecException( - 'executables: {command: 123}', - (pubspec) => pubspec.executables); - }); - - test("throws if a value contains a path separator", () { - expectPubspecException( - 'executables: {command: funny_name/part}', - (pubspec) => pubspec.executables); - }); - - test("throws if a value contains a windows path separator", () { - expectPubspecException( - r'executables: {command: funny_name\part}', - (pubspec) => pubspec.executables); - }); - - test("uses the key if the value is null", () { - var pubspec = new Pubspec.parse(''' -executables: - command: -''', sources); - expect(pubspec.executables['command'], equals('command')); - }); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/real_version_test.dart b/sdk/lib/_internal/pub_generated/test/real_version_test.dart deleted file mode 100644 index f9a60748eb0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/real_version_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:io'; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../lib/src/exit_codes.dart' as exit_codes; -import '../lib/src/sdk.dart' as sdk; -import 'test_pub.dart'; - -main() { - initConfig(); - - // This test is a bit funny. - // - // Pub parses the "version" file that gets generated and shipped with the SDK. - // We want to make sure that the actual version file that gets created is - // also one pub can parse. If this test fails, it means the version file's - // format has changed in a way pub didn't expect. - // - // Note that this test expects to be invoked from a Dart executable that is - // in the built SDK's "bin" directory. Note also that this invokes pub from - // the built SDK directory, and not the live pub code directly in the repo. - integration('parse the real SDK "version" file', () { - // Get the path to the pub binary in the SDK. - var pubPath = path.join( - sdk.rootDirectory, - 'bin', - Platform.operatingSystem == "windows" ? "pub.bat" : "pub"); - - var pub = new ScheduledProcess.start(pubPath, ['version']); - pub.stdout.expect(startsWith("Pub")); - pub.shouldExit(exit_codes.SUCCESS); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/allows_dart_extension_test.dart b/sdk/lib/_internal/pub_generated/test/run/allows_dart_extension_test.dart deleted file mode 100644 index 90d1d8a6547..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/allows_dart_extension_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = """ -import 'dart:io'; - -main() { - stdout.writeln("stdout output"); - stderr.writeln("stderr output"); - exitCode = 123; -} -"""; - -main() { - initConfig(); - integration('allows a ".dart" extension on the argument', () { - d.dir( - appPath, - [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create(); - - var pub = pubRun(args: ["script.dart"]); - pub.stdout.expect("stdout output"); - pub.stderr.expect("stderr output"); - pub.shouldExit(123); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/app_can_read_from_stdin_test.dart b/sdk/lib/_internal/pub_generated/test/run/app_can_read_from_stdin_test.dart deleted file mode 100644 index 9eab3a7ba12..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/app_can_read_from_stdin_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = """ -import 'dart:io'; - -main() { - print("started"); - var line1 = stdin.readLineSync(); - print("between"); - var line2 = stdin.readLineSync(); - print(line1); - print(line2); -} -"""; - -main() { - initConfig(); - integration('the spawned application can read from stdin', () { - d.dir( - appPath, - [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create(); - - var pub = pubRun(args: ["script"]); - - pub.stdout.expect("started"); - pub.writeLine("first"); - pub.stdout.expect("between"); - pub.writeLine("second"); - pub.stdout.expect("first"); - pub.stdout.expect("second"); - pub.shouldExit(0); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/displays_transformer_logs_test.dart b/sdk/lib/_internal/pub_generated/test/run/displays_transformer_logs_test.dart deleted file mode 100644 index 05af3302615..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/displays_transformer_logs_test.dart +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = """ -import "package:myapp/lib.dart"; -main() { - callLib(); -} -"""; - -const LIB = """ -callLib() { - print("lib"); -} -"""; - -// Make it lazy so that "lib.dart" isn't transformed until after the process -// is started. Otherwise, since this tranformer modifies .dart files, it will -// be run while the transformers themselves are loading during pub run's -// startup. -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class LoggingTransformer extends Transformer implements LazyTransformer { - LoggingTransformer.asPlugin(); - - String get allowedExtensions => '.dart'; - - void apply(Transform transform) { - transform.logger.info('\${transform.primaryInput.id}.'); - transform.logger.warning('\${transform.primaryInput.id}.'); - } - - void declareOutputs(DeclaringTransform transform) { - // TODO(rnystrom): Remove this when #19408 is fixed. - transform.declareOutput(transform.primaryId); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration('displays transformer log messages', () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [ - d.file("lib.dart", LIB), - d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("bin", [d.file("script.dart", SCRIPT)])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = pubRun(args: ["script"]); - - // Note that the info log is only displayed here because the test - // harness runs pub in verbose mode. By default, only the warning would - // be shown. - pub.stdout.expect("[Info from Logging]:"); - pub.stdout.expect("myapp|bin/script.dart."); - - pub.stderr.expect("[Warning from Logging]:"); - pub.stderr.expect("myapp|bin/script.dart."); - - pub.stdout.expect("[Info from Logging]:"); - pub.stdout.expect("myapp|lib/lib.dart."); - - pub.stderr.expect("[Warning from Logging]:"); - pub.stderr.expect("myapp|lib/lib.dart."); - - pub.stdout.expect("lib"); - pub.shouldExit(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/does_not_run_on_transformer_error_test.dart b/sdk/lib/_internal/pub_generated/test/run/does_not_run_on_transformer_error_test.dart deleted file mode 100644 index 7d3bb786e4d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/does_not_run_on_transformer_error_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = """ -main() { - print("should not get here!"); -} -"""; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class FailingTransformer extends Transformer { - FailingTransformer.asPlugin(); - - String get allowedExtensions => '.dart'; - - void apply(Transform transform) { - // Don't run on the transformer itself. - if (transform.primaryInput.id.path.startsWith("lib")) return; - transform.logger.error('\${transform.primaryInput.id}.'); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration('does not run if a transformer has an error', () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("bin", [d.file("script.dart", SCRIPT)])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = pubRun(args: ["script"]); - - pub.stderr.expect("[Error from Failing]:"); - pub.stderr.expect("myapp|bin/script.dart."); - - // Note: no output from the script. - pub.shouldExit(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/doesnt_load_an_unnecessary_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/run/doesnt_load_an_unnecessary_transformer_test.dart deleted file mode 100644 index fefb202aaf9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/doesnt_load_an_unnecessary_transformer_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class BrokenTransformer extends Transformer { - RewriteTransformer.asPlugin() { - throw 'This transformer is broken!'; - } - - String get allowedExtensions => '.txt'; - - void apply(Transform transform) {} -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("doesn't load an unnecessary transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - r"$include": "lib/myapp.dart" - } - }] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", ""), - d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("bin", [d.file("hi.dart", "void main() => print('Hello!');")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - // This shouldn't load the transformer, since it doesn't transform - // anything that the entrypoint imports. If it did load the transformer, - // we'd know since it would throw an exception. - var pub = pubRun(args: ["hi"]); - pub.stdout.expect("Hello!"); - pub.shouldExit(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/errors_if_no_executable_is_given_test.dart b/sdk/lib/_internal/pub_generated/test/run/errors_if_no_executable_is_given_test.dart deleted file mode 100644 index 0ba4378ebbc..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/errors_if_no_executable_is_given_test.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('Errors if the executable does not exist.', () { - d.dir(appPath, [d.appPubspec()]).create(); - - schedulePub(args: ["run"], error: """ -Must specify an executable to run. - -Usage: pub run [args...] --h, --help Print this usage information. - --mode Mode to run transformers in. - (defaults to "release" for dependencies, "debug" for entrypoint) - -Run "pub help" to see global options. -""", exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/errors_if_only_transitive_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/errors_if_only_transitive_dependency_test.dart deleted file mode 100644 index 4e95e04af09..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/errors_if_only_transitive_dependency_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('Errors if the script is in a non-immediate dependency.', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("bar.dart", "main() => print('foobar');")])]).create(); - - d.dir("bar", [d.libPubspec("bar", "1.0.0", deps: { - "foo": { - "path": "../foo" - } - })]).create(); - - d.dir(appPath, [d.appPubspec({ - "bar": { - "path": "../bar" - } - })]).create(); - - pubGet(); - - var pub = pubRun(args: ["foo:script"]); - pub.stderr.expect('Package "foo" is not an immediate dependency.'); - pub.stderr.expect('Cannot run executables in transitive dependencies.'); - pub.shouldExit(exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/errors_if_path_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/errors_if_path_in_dependency_test.dart deleted file mode 100644 index 15cf766866f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/errors_if_path_in_dependency_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - 'Errors if the executable is in a subdirectory in a ' 'dependency.', - () { - d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - schedulePub(args: ["run", "foo:sub/dir"], error: """ -Cannot run an executable in a subdirectory of a dependency. - -Usage: pub run [args...] --h, --help Print this usage information. - --mode Mode to run transformers in. - (defaults to "release" for dependencies, "debug" for entrypoint) - -Run "pub help" to see global options. -""", exitCode: exit_codes.USAGE); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/ignores_explicit_dart2js_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/run/ignores_explicit_dart2js_transformer_test.dart deleted file mode 100644 index e3286e7d354..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/ignores_explicit_dart2js_transformer_test.dart +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("doesn't choke on an explicit dart2js transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [r"$dart2js"] - }), - d.dir("bin", [d.file("script.dart", "main() => print('Hello!');")])]).create(); - - var pub = pubRun(args: ["script"]); - pub.stdout.expect("Hello!"); - pub.shouldExit(0); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/includes_parent_directories_of_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/includes_parent_directories_of_entrypoint_test.dart deleted file mode 100644 index d00de270490..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/includes_parent_directories_of_entrypoint_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = r""" -import '../../a.dart'; -import '../b.dart'; -main() { - print("$a $b"); -} -"""; - -main() { - initConfig(); - integration( - 'allows assets in parent directories of the entrypoint to be' 'accessed', - () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "tool", - [ - d.file("a.dart", "var a = 'a';"), - d.dir( - "a", - [ - d.file("b.dart", "var b = 'b';"), - d.dir("b", [d.file("app.dart", SCRIPT)])])])]).create(); - - var pub = pubRun(args: [path.join("tool", "a", "b", "app")]); - pub.stdout.expect("a b"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/mode_test.dart b/sdk/lib/_internal/pub_generated/test/run/mode_test.dart deleted file mode 100644 index cff439fadd1..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/mode_test.dart +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class DartTransformer extends Transformer { - final BarbackSettings _settings; - - DartTransformer.asPlugin(this._settings); - - String get allowedExtensions => '.in'; - - void apply(Transform transform) { - transform.addOutput(new Asset.fromString( - new AssetId(transform.primaryInput.id.package, "bin/script.dart"), - "void main() => print('\${_settings.mode.name}');")); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration('runs a local script with customizable modes', () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [ - d.file("transformer.dart", TRANSFORMER), - d.file("primary.in", "")])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - // By default it should run in debug mode. - var pub = pubRun(args: ["script"]); - pub.stdout.expect("debug"); - pub.shouldExit(); - - // A custom mode should be specifiable. - pub = pubRun(args: ["--mode", "custom-mode", "script"]); - pub.stdout.expect("custom-mode"); - pub.shouldExit(); - }); - - integration('runs a dependency script with customizable modes', () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.2.3", - "transformers": ["foo/src/transformer"] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [ - d.file("transformer.dart", TRANSFORMER), - d.file("primary.in", "")])])]).create(); - - d.appDir({ - "foo": { - "path": "../foo" - } - }).create(); - - createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']); - - // By default it should run in release mode. - var pub = pubRun(args: ["foo:script"]); - pub.stdout.expect("release"); - pub.shouldExit(); - - // A custom mode should be specifiable. - pub = pubRun(args: ["--mode", "custom-mode", "foo:script"]); - pub.stdout.expect("custom-mode"); - pub.shouldExit(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/nonexistent_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/nonexistent_dependency_test.dart deleted file mode 100644 index f57ce49f9bb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/nonexistent_dependency_test.dart +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('Errors if the script is in an unknown package.', () { - d.dir(appPath, [d.appPubspec()]).create(); - - var pub = pubRun(args: ["foo:script"]); - pub.stderr.expect( - 'Could not find package "foo". Did you forget to add a ' 'dependency?'); - pub.shouldExit(exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_in_dependency_test.dart deleted file mode 100644 index eaeb26c0a35..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_in_dependency_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('Errors if the script in a dependency does not exist.', () { - d.dir("foo", [d.libPubspec("foo", "1.0.0")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet(); - - var pub = pubRun(args: ["foo:script"]); - pub.stderr.expect( - "Could not find ${p.join("bin", "script.dart")} in package foo."); - pub.shouldExit(exit_codes.NO_INPUT); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_test.dart b/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_test.dart deleted file mode 100644 index 50185724519..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/nonexistent_script_test.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as p; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('Errors if the script does not exist.', () { - d.dir(appPath, [d.appPubspec()]).create(); - - var pub = pubRun(args: ["script"]); - pub.stderr.expect("Could not find ${p.join("bin", "script.dart")}."); - pub.shouldExit(exit_codes.NO_INPUT); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/passes_along_arguments_test.dart b/sdk/lib/_internal/pub_generated/test/run/passes_along_arguments_test.dart deleted file mode 100644 index f6fe879850c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/passes_along_arguments_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = """ -main(List args) { - print(args.join(" ")); -} -"""; - -main() { - initConfig(); - integration('passes arguments to the spawned script', () { - d.dir( - appPath, - [d.appPubspec(), d.dir("bin", [d.file("args.dart", SCRIPT)])]).create(); - - // Use some args that would trip up pub's arg parser to ensure that it - // isn't trying to look at them. - var pub = pubRun(args: ["args", "--verbose", "-m", "--", "help"]); - - pub.stdout.expect("--verbose -m -- help"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_a_generated_script_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_a_generated_script_test.dart deleted file mode 100644 index 4794c3770ab..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/runs_a_generated_script_test.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class DartTransformer extends Transformer { - DartTransformer.asPlugin(); - - String get allowedExtensions => '.in'; - - void apply(Transform transform) { - transform.addOutput(new Asset.fromString( - new AssetId("myapp", "bin/script.dart"), - "void main() => print('generated');")); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration('runs a script generated from scratch by a transformer', () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [ - d.file("transformer.dart", TRANSFORMER), - d.file("primary.in", "")])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = pubRun(args: ["script"]); - - pub.stdout.expect("generated"); - pub.shouldExit(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_directory_in_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_app_in_directory_in_entrypoint_test.dart deleted file mode 100644 index 488bff6f65b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_directory_in_entrypoint_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('runs a Dart application in the entrypoint package', () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "tool", - [ - d.file("app.dart", "main() => print('tool');"), - d.dir("sub", [d.file("app.dart", "main() => print('sub');")])])]).create(); - - var pub = pubRun(args: [path.join("tool", "app")]); - pub.stdout.expect("tool"); - pub.shouldExit(); - - pub = pubRun(args: [path.join("tool", "sub", "app")]); - pub.stdout.expect("sub"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_app_in_entrypoint_test.dart deleted file mode 100644 index f4c7a6b33b3..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/runs_app_in_entrypoint_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = """ -import 'dart:io'; - -main() { - stdout.writeln("stdout output"); - stderr.writeln("stderr output"); - exitCode = 123; -} -"""; - -main() { - initConfig(); - integration('runs a Dart application in the entrypoint package', () { - d.dir( - appPath, - [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create(); - - var pub = pubRun(args: ["script"]); - pub.stdout.expect("stdout output"); - pub.stderr.expect("stderr output"); - pub.shouldExit(123); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dependency_test.dart deleted file mode 100644 index 9a02aba2087..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dependency_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('runs a named Dart application in a dependency', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("bar.dart", "main() => print('foobar');")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet(); - - var pub = pubRun(args: ["foo:bar"]); - pub.stdout.expect("foobar"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dev_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dev_dependency_test.dart deleted file mode 100644 index 8bf4c879424..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/runs_named_app_in_dev_dependency_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration('runs a named Dart application in a dev dependency', () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("bin", [d.file("bar.dart", "main() => print('foobar');")])]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dev_dependencies": { - "foo": { - "path": "../foo" - } - } - })]).create(); - - pubGet(); - - var pub = pubRun(args: ["foo:bar"]); - pub.stdout.expect("foobar"); - pub.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_the_script_in_checked_mode_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_the_script_in_checked_mode_test.dart deleted file mode 100644 index 56c3ad44a0d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/runs_the_script_in_checked_mode_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SCRIPT = """ -main() { - int a = true; -} -"""; - -main() { - initConfig(); - integration('runs the script in checked mode by default', () { - d.dir( - appPath, - [d.appPubspec(), d.dir("bin", [d.file("script.dart", SCRIPT)])]).create(); - - schedulePub( - args: ["run", "script"], - error: contains("'bool' is not a subtype of type 'int' of 'a'"), - exitCode: 255); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/run/runs_transformer_in_entrypoint_test.dart b/sdk/lib/_internal/pub_generated/test/run/runs_transformer_in_entrypoint_test.dart deleted file mode 100644 index fc154a1ddb7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/run/runs_transformer_in_entrypoint_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const SCRIPT = """ -const TOKEN = "hi"; -main() { - print(TOKEN); -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration('runs transformers in the entrypoint package', () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [d.dir("src", [d.file("transformer.dart", dartTransformer("transformed"))])]), - d.dir("bin", [d.file("hi.dart", SCRIPT)])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = pubRun(args: ["hi"]); - - pub.stdout.expect("(hi, transformed)"); - pub.shouldExit(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/404_page_test.dart b/sdk/lib/_internal/pub_generated/test/serve/404_page_test.dart deleted file mode 100644 index b8f3e9a4327..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/404_page_test.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - setUp(() { - d.dir(appPath, [d.appPubspec()]).create(); - }); - - integration("the 404 page describes the missing asset", () { - pubServe(); - - scheduleRequest("packages/foo/missing.txt").then((response) { - expect(response.statusCode, equals(404)); - - // Should mention the asset that can't be found. - expect(response.body, contains("foo")); - expect(response.body, contains("missing.txt")); - }); - - endPubServe(); - }); - - integration("the 404 page describes the error", () { - pubServe(); - - scheduleRequest("packages").then((response) { - expect(response.statusCode, equals(404)); - - // Should mention the asset that can't be found. - expect(response.body, contains('"/packages"')); - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/allows_arbitrary_modes_test.dart b/sdk/lib/_internal/pub_generated/test/serve/allows_arbitrary_modes_test.dart deleted file mode 100644 index 6e484336d67..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/allows_arbitrary_modes_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ModeTransformer extends Transformer { - final BarbackSettings settings; - ModeTransformer.asPlugin(this.settings); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return new Future.value().then((_) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, settings.mode.toString())); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows user-defined mode names", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(args: ["--mode", "depeche"]); - requestShouldSucceed("foo.out", "depeche"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/defaults_to_debug_mode_test.dart b/sdk/lib/_internal/pub_generated/test/serve/defaults_to_debug_mode_test.dart deleted file mode 100644 index 16b7de13a26..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/defaults_to_debug_mode_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ModeTransformer extends Transformer { - final BarbackSettings settings; - ModeTransformer.asPlugin(this.settings); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return new Future.value().then((_) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, settings.mode.toString())); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("defaults to debug mode", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "debug"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_crash_if_an_unused_dart_file_has_a_syntax_error_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_crash_if_an_unused_dart_file_has_a_syntax_error_test.dart deleted file mode 100644 index dc2812ddf33..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_crash_if_an_unused_dart_file_has_a_syntax_error_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("doesn't crash if an unused .dart file has a syntax error", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [ - d.file("transformer.dart", REWRITE_TRANSFORMER), - d.file("unused.dart", "(*&^#@")])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_a_dependency_is_removed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_a_dependency_is_removed_test.dart deleted file mode 100644 index 25cb7e9bdcb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_a_dependency_is_removed_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("does not get if a dependency is removed", () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - // Get "foo" into the lock file. - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - pubGet(); - - // Remove it from the pubspec. - d.dir(appPath, [d.appPubspec()]).create(); - - pubServe(shouldGetFirst: false); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_git_url_did_not_change_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_git_url_did_not_change_test.dart deleted file mode 100644 index 5bf1869b537..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_git_url_did_not_change_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("does not get first if a git dependency's url is unchanged", () { - d.git('foo.git', [d.libPubspec('foo', '1.0.0'), d.libDir("foo")]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - pubServe(shouldGetFirst: false); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_matches_override_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_matches_override_test.dart deleted file mode 100644 index 8dc2f4b1396..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_matches_override_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - // This is a regression test for https://dartbug.com/15180. - initConfig(); - integration("does not get if the locked version matches the override", () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - // Get "foo" into the lock file. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "any" - }, - "dependency_overrides": { - "foo": { - "path": "../foo", - "version": ">=0.0.1" - } - } - })]).create(); - pubGet(); - - pubServe(shouldGetFirst: false); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_version_matches_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_version_matches_test.dart deleted file mode 100644 index 67c8c648938..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_get_first_if_locked_version_matches_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - "does not get if the locked version of a dependency is allowed " - "by the pubspec's constraint", - () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - // Get "foo" into the lock file. - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo", - "version": ">=0.0.1" - }, - })]).create(); - pubGet(); - - // Change the version. - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo", - "version": "<2.0.0" - }, - })]).create(); - - pubServe(shouldGetFirst: false); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_dart_in_release_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_dart_in_release_test.dart deleted file mode 100644 index 45418cff057..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_dart_in_release_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("does not serve .dart files in release mode", () { - - d.dir( - "foo", - [d.libPubspec("foo", "0.0.1"), d.dir("lib", [d.file("foo.dart", """ - library foo; - foo() => 'foo'; - """)])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), - d.dir("lib", [d.file("lib.dart", "lib() => print('hello');"),]), - d.dir("web", [d.file("file.dart", """ - import 'package:foo/foo.dart'; - main() => print('hello'); - """), - d.dir("sub", [d.file("sub.dart", "main() => 'foo';"),])])]).create(); - - pubServe(shouldGetFirst: true, args: ["--mode", "release"]); - requestShould404("file.dart"); - requestShould404("packages/myapp/lib.dart"); - requestShould404("packages/foo/foo.dart"); - requestShould404("sub/sub.dart"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_hidden_assets_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_hidden_assets_test.dart deleted file mode 100644 index 26981c1e590..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_serve_hidden_assets_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("doesn't serve hidden assets", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file(".outer.txt", "outer contents"), - d.dir(".dir", [d.file("inner.txt", "inner contents"),])])]).create(); - - pubServe(); - requestShould404(".outer.txt"); - requestShould404(".dir/inner.txt"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/does_not_watch_compiled_js_files_test.dart b/sdk/lib/_internal/pub_generated/test/serve/does_not_watch_compiled_js_files_test.dart deleted file mode 100644 index 41b7568bf91..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/does_not_watch_compiled_js_files_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("does not watch changes to compiled JS files in the package", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create(); - - pubServe(); - waitForBuildSuccess(); - requestShouldSucceed("index.html", "body"); - - d.dir( - appPath, - [ - d.dir( - "web", - [ - d.file('file.dart', 'void main() => print("hello");'), - d.file("other.dart.js", "should be ignored"), - d.file("other.dart.js.map", "should be ignored"), - d.file("other.dart.precompiled.js", "should be ignored")])]).create(); - - waitForBuildSuccess(); - requestShouldSucceed("file.dart", 'void main() => print("hello");'); - requestShould404("other.dart.js"); - requestShould404("other.dart.js.map"); - requestShould404("other.dart.precompiled.js"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_added_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_added_test.dart deleted file mode 100644 index a7ea6a0985f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_added_test.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("gets first if a dependency is not in the lock file", () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - // Create a lock file without "foo". - d.dir(appPath, [d.appPubspec()]).create(); - pubGet(); - - // Add it to the pubspec. - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_is_not_installed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_is_not_installed_test.dart deleted file mode 100644 index ba727603f58..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_is_not_installed_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("gets first if a dependency is not installed", () { - servePackages((builder) => builder.serve("foo", "1.2.3")); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - // Run pub to get a lock file. - pubGet(); - - // Delete the system cache so it isn't installed any more. - schedule(() => deleteEntry(path.join(sandboxDir, cachePath))); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo 1.2.3";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_version_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_version_changed_test.dart deleted file mode 100644 index 8a5b294c94e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dependency_version_changed_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - "gets first if a dependency's version doesn't match the one in " - "the lock file", - () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - d.appDir({ - "foo": { - "path": "../foo", - "version": "0.0.1" - } - }).create(); - - pubGet(); - - // Change the version in the pubspec and package. - d.appDir({ - "foo": { - "path": "../foo", - "version": "0.0.2" - } - }).create(); - - d.dir("foo", [d.libPubspec("foo", "0.0.2"), d.libDir("foo")]).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dev_dependency_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dev_dependency_changed_test.dart deleted file mode 100644 index 69e8f66ac7b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_dev_dependency_changed_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:convert'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("gets first if a dev dependency has changed", () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - // Create a pubspec with "foo" and a lock file without it. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dev_dependencies": { - "foo": { - "path": "../foo" - } - } - }), d.file("pubspec.lock", JSON.encode({ - 'packages': {} - }))]).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_ref_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_ref_changed_test.dart deleted file mode 100644 index 2b43f9f8e4e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_ref_changed_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - "gets first if a git dependency's ref doesn't match the one in " - "the lock file", - () { - var repo = - d.git('foo.git', [d.libDir('foo', 'before'), d.libPubspec('foo', '1.0.0')]); - repo.create(); - var commit1 = repo.revParse('HEAD'); - - d.git( - 'foo.git', - [d.libDir('foo', 'after'), d.libPubspec('foo', '1.0.0')]).commit(); - - var commit2 = repo.revParse('HEAD'); - - // Lock it to the ref of the first commit. - d.appDir({ - "foo": { - "git": { - "url": "../foo.git", - "ref": commit1 - } - } - }).create(); - - pubGet(); - - // Change the commit in the pubspec. - d.appDir({ - "foo": { - "git": { - "url": "../foo.git", - "ref": commit2 - } - } - }).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "after";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_url_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_url_changed_test.dart deleted file mode 100644 index c41af7d2970..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_git_url_changed_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - "gets first if a git dependency's url doesn't match the one in " - "the lock file", - () { - d.git( - "foo-before.git", - [d.libPubspec("foo", "1.0.0"), d.libDir("foo", "before")]).create(); - - d.git( - "foo-after.git", - [d.libPubspec("foo", "1.0.0"), d.libDir("foo", "after")]).create(); - - d.appDir({ - "foo": { - "git": "../foo-before.git" - } - }).create(); - - pubGet(); - - // Change the path in the pubspec. - d.appDir({ - "foo": { - "git": "../foo-after.git" - } - }).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "after";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_no_lockfile_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_no_lockfile_test.dart deleted file mode 100644 index a823db78c6c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_no_lockfile_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("gets first if there is no lockfile", () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - d.appDir({ - "foo": { - "path": "../foo" - } - }).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_path_dependency_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_path_dependency_changed_test.dart deleted file mode 100644 index 156e18d3469..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_path_dependency_changed_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - "gets first if a path dependency's path doesn't match the one in " - "the lock file", - () { - d.dir( - "foo-before", - [d.libPubspec("foo", "0.0.1"), d.libDir("foo", "before")]).create(); - - d.dir( - "foo-after", - [d.libPubspec("foo", "0.0.1"), d.libDir("foo", "after")]).create(); - - d.appDir({ - "foo": { - "path": "../foo-before" - } - }).create(); - - pubGet(); - - // Change the path in the pubspec. - d.appDir({ - "foo": { - "path": "../foo-after" - } - }).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "after";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_source_changed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_source_changed_test.dart deleted file mode 100644 index f960ad6ecf6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_source_changed_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:convert'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration( - "gets first if a dependency's source doesn't match the one in " "the lock file", - () { - d.dir("foo", [d.libPubspec("foo", "0.0.1"), d.libDir("foo")]).create(); - - d.dir(appPath, [// A pubspec with a path source. - d.appPubspec({ - "foo": { - "path": "../foo" - } - }), // A lock file with the hosted source. - d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'foo': { - 'version': '0.0.0', - 'source': 'hosted', - 'description': 'foo' - } - } - }))]).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/foo.dart", 'main() => "foo";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_transitive_dependency_is_not_installed_test.dart b/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_transitive_dependency_is_not_installed_test.dart deleted file mode 100644 index 90c76ea5f0b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/gets_first_if_transitive_dependency_is_not_installed_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("gets first if a transitive dependency is not installed", () { - servePackages((builder) => builder.serve("bar", "1.2.3")); - - d.dir("foo", [d.libPubspec("foo", "1.0.0", deps: { - "bar": "any" - }), d.libDir("foo")]).create(); - - d.appDir({ - "foo": { - "path": "../foo" - } - }).create(); - - // Run pub to install everything. - pubGet(); - - // Delete the system cache so bar isn't installed any more. - schedule(() => deleteEntry(path.join(sandboxDir, cachePath))); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/bar/bar.dart", 'main() => "bar 1.2.3";'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/invalid_method_test.dart b/sdk/lib/_internal/pub_generated/test/serve/invalid_method_test.dart deleted file mode 100644 index cccad88615b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/invalid_method_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("responds with a 405 for an invalid method", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", ""),])]).create(); - - pubServe(); - - postShould405("index.html"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/invalid_urls_test.dart b/sdk/lib/_internal/pub_generated/test/serve/invalid_urls_test.dart deleted file mode 100644 index ece122e71b8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/invalid_urls_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("responds with a 404 on incomplete special URLs", () { - d.dir("foo", [d.libPubspec("foo", "0.0.1")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), - d.dir( - "lib", - [// Make a file that maps to the special "packages" directory to ensure - // it is *not* found. - d.file("packages")]), d.dir("web", [d.file("packages")])]).create(); - - pubGet(); - pubServe(); - requestShould404("packages"); - requestShould404("packages/"); - requestShould404("packages/myapp"); - requestShould404("packages/myapp/"); - requestShould404("packages/foo"); - requestShould404("packages/foo/"); - requestShould404("packages/unknown"); - requestShould404("packages/unknown/"); - endPubServe(); - }); - -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/missing_asset_test.dart b/sdk/lib/_internal/pub_generated/test/serve/missing_asset_test.dart deleted file mode 100644 index 8bb69b0f4e4..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/missing_asset_test.dart +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("responds with a 404 for missing assets", () { - d.dir(appPath, [d.appPubspec()]).create(); - - pubServe(); - requestShould404("index.html"); - requestShould404("packages/myapp/nope.dart"); - requestShould404("dir/packages/myapp/nope.dart"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/missing_dependency_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/missing_dependency_file_test.dart deleted file mode 100644 index 2fe60a4ff3a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/missing_dependency_file_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("responds with a 404 for a missing files in dependencies", () { - d.dir("foo", [d.libPubspec("foo", "0.0.1")]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubGet(); - pubServe(); - requestShould404("packages/foo/nope.dart"); - requestShould404("dir/packages/foo/nope.dart"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/missing_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/missing_file_test.dart deleted file mode 100644 index 737fb34b15f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/missing_file_test.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("responds with a 404 for missing source files", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("lib", [d.file("nope.dart", "nope")]), - d.dir("web", [d.file("index.html", ""),])]).create(); - - // Start the server with the files present so that it creates barback - // assets for them. - pubServe(); - - // Now delete them. - schedule(() { - deleteEntry(path.join(sandboxDir, appPath, "lib", "nope.dart")); - deleteEntry(path.join(sandboxDir, appPath, "web", "index.html")); - }, "delete files"); - - // Now request them. - // TODO(rnystrom): It's possible for these requests to happen quickly - // enough that the file system hasn't notified for the deletions yet. If - // that happens, we can probably just add a short delay here. - - requestShould404("index.html"); - requestShould404("packages/myapp/nope.dart"); - requestShould404("dir/packages/myapp/nope.dart"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_added_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_added_file_test.dart deleted file mode 100644 index 7a25f5a9053..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_added_file_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -// TODO(nweiz): Default to testing the native watcher and add an explicit test -// for the polling watcher when issue 14941 is fixed. - -main() { - initConfig(); - integration( - "picks up files added after serving started when using the " "native watcher", - () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create(); - - pubServe(args: ["--no-force-poll"]); - waitForBuildSuccess(); - requestShouldSucceed("index.html", "body"); - - d.dir(appPath, [d.dir("web", [d.file("other.html", "added")])]).create(); - - waitForBuildSuccess(); - requestShouldSucceed("other.html", "added"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_modified_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_modified_file_test.dart deleted file mode 100644 index 41a9eac89ea..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_modified_file_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -// TODO(nweiz): Default to testing the native watcher and add an explicit test -// for the polling watcher when issue 14941 is fixed. - -main() { - initConfig(); - integration( - "watches modifications to files when using the native watcher", - () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "before")])]).create(); - - pubServe(args: ["--no-force-poll"]); - requestShouldSucceed("index.html", "before"); - - d.dir(appPath, [d.dir("web", [d.file("index.html", "after")])]).create(); - - waitForBuildSuccess(); - requestShouldSucceed("index.html", "after"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_removed_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_removed_file_test.dart deleted file mode 100644 index 8aef49352d5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_removed_file_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -// TODO(nweiz): Default to testing the native watcher and add an explicit test -// for the polling watcher when issue 14941 is fixed. - -main() { - initConfig(); - integration( - "stop serving a file that is removed when using the native " "watcher", - () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create(); - - pubServe(args: ["--no-force-poll"]); - requestShouldSucceed("index.html", "body"); - - schedule( - () => deleteEntry(path.join(sandboxDir, appPath, "web", "index.html"))); - - waitForBuildSuccess(); - requestShould404("index.html"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/native_watch_replaced_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/native_watch_replaced_file_test.dart deleted file mode 100644 index b25721690f0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/native_watch_replaced_file_test.dart +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:async'; -import 'dart:io'; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - // This is a regression test for http://dartbug.com/21402. - initConfig(); - withBarbackVersions("any", () { - integration( - "picks up files replaced after serving started when using the " - "native watcher", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir("web", [d.file("file.txt", "before"),]), - d.file("other", "after")]).create(); - - createLockFile("myapp", pkg: ["barback"]); - - pubServe(args: ["--no-force-poll"]); - waitForBuildSuccess(); - requestShouldSucceed("file.out", "before.out"); - - schedule(() { - // Replace file.txt by renaming other on top of it. - return new File( - p.join( - sandboxDir, - appPath, - "other")).rename(p.join(sandboxDir, appPath, "web", "file.txt")); - }); - - // Read the transformed file to ensure the change is actually noticed by - // pub and not that we just get the new file contents piped through - // without pub realizing they've changed. - waitForBuildSuccess(); - requestShouldSucceed("file.out", "after.out"); - - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_lib_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_lib_test.dart deleted file mode 100644 index 2204ff640cf..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_lib_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("'packages' URLs look in the app's lib directory", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "lib", - [ - d.file("lib.dart", "foo() => 'foo';"), - d.dir("sub", [d.file("lib.dart", "bar() => 'bar';"),])])]).create(); - - pubServe(); - requestShouldSucceed("packages/myapp/lib.dart", "foo() => 'foo';"); - requestShouldSucceed("packages/myapp/sub/lib.dart", "bar() => 'bar';"); - - // "packages" can be in a subpath of the URL: - requestShouldSucceed("foo/packages/myapp/lib.dart", "foo() => 'foo';"); - requestShouldSucceed("a/b/packages/myapp/sub/lib.dart", "bar() => 'bar';"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_web_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_web_test.dart deleted file mode 100644 index e7661d439ef..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/serve_from_app_web_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("finds files in the app's web directory", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file("index.html", ""), - d.file("file.dart", "main() => print('hello');"), - d.dir( - "sub", - [ - d.file("file.html", "in subdir"), - d.file("lib.dart", "main() => 'foo';"),])])]).create(); - - pubServe(); - requestShouldSucceed("index.html", ""); - requestShouldSucceed("file.dart", "main() => print('hello');"); - requestShouldSucceed("sub/file.html", "in subdir"); - requestShouldSucceed("sub/lib.dart", "main() => 'foo';"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/serve_from_dependency_lib_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serve_from_dependency_lib_test.dart deleted file mode 100644 index 034e168468d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/serve_from_dependency_lib_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("'packages' URLs look in the dependency's lib directory", () { - d.dir( - "foo", - [ - d.libPubspec("foo", "0.0.1"), - d.dir( - "lib", - [ - d.file("lib.dart", "foo() => 'foo';"), - d.dir("sub", [d.file("lib.dart", "bar() => 'bar';"),])])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - pubServe(shouldGetFirst: true); - requestShouldSucceed("packages/foo/lib.dart", "foo() => 'foo';"); - requestShouldSucceed("packages/foo/sub/lib.dart", "bar() => 'bar';"); - - // "packages" can be in a subpath of the URL: - requestShouldSucceed("foo/packages/foo/lib.dart", "foo() => 'foo';"); - requestShouldSucceed("a/b/packages/foo/sub/lib.dart", "bar() => 'bar';"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/serves_file_with_space_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serves_file_with_space_test.dart deleted file mode 100644 index d2421cff64a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/serves_file_with_space_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("serves a filename with a space", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file("foo bar.txt", "outer contents"), - d.dir("sub dir", [d.file("inner.txt", "inner contents"),])])]).create(); - - pubServe(); - requestShouldSucceed("foo%20bar.txt", "outer contents"); - requestShouldSucceed("sub%20dir/inner.txt", "inner contents"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/serves_index_html_for_directories_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serves_index_html_for_directories_test.dart deleted file mode 100644 index c02db4855c7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/serves_index_html_for_directories_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("serves index.html for directories", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file("index.html", "super"), - d.dir("sub", [d.file("index.html", "sub")])])]).create(); - - pubServe(); - requestShouldSucceed("", "super"); - requestShouldSucceed("sub/", "sub"); - requestShouldRedirect("sub", "/sub/"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/serves_web_and_test_dirs_by_default_test.dart b/sdk/lib/_internal/pub_generated/test/serve/serves_web_and_test_dirs_by_default_test.dart deleted file mode 100644 index a15c6cbd1b2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/serves_web_and_test_dirs_by_default_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("serves web/ and test/ dirs by default", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("web", [d.file("foo", "contents")]), - d.dir("test", [d.file("bar", "contents")]), - d.dir("example", [d.file("baz", "contents")])]).create(); - - pubServe(); - requestShouldSucceed("foo", "contents", root: "web"); - requestShouldSucceed("bar", "contents", root: "test"); - requestShould404("baz", root: "web"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/supports_cross_origin_header_test.dart b/sdk/lib/_internal/pub_generated/test/serve/supports_cross_origin_header_test.dart deleted file mode 100644 index 90593936571..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/supports_cross_origin_header_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("sends responses that allow cross-origin requests", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(); - requestShouldSucceed( - "index.html", - "", - headers: containsPair("access-control-allow-origin", "*")); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_declaring_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_declaring_transformers_test.dart deleted file mode 100644 index f14da0d7c42..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_declaring_transformers_test.dart +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -const DECLARING_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class DeclaringRewriteTransformer extends Transformer - implements DeclaringTransformer { - DeclaringRewriteTransformer.asPlugin(); - - String get allowedExtensions => '.out'; - - Future apply(Transform transform) { - transform.logger.info('Rewriting \${transform.primaryInput.id}.'); - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".final"); - transform.addOutput(new Asset.fromString(id, "\$contents.final")); - }); - } - - Future declareOutputs(DeclaringTransform transform) { - transform.declareOutput(transform.primaryId.changeExtension(".final")); - return new Future.value(); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("supports a user-defined declaring transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/lazy", "myapp/src/declaring"] - }), - d.dir( - "lib", - [d.dir("src", [// Include a lazy transformer before the declaring transformer, - // because otherwise its behavior is indistinguishable from a normal - // transformer. - d.file("lazy.dart", LAZY_TRANSFORMER), - d.file("declaring.dart", DECLARING_TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - // The build should complete without either transformer logging anything. - server.stdout.expect('Build completed successfully'); - - requestShouldSucceed("foo.final", "foo.out.final"); - server.stdout.expect( - emitsLines( - '[Info from LazyRewrite]:\n' 'Rewriting myapp|web/foo.txt.\n' - '[Info from DeclaringRewrite]:\n' 'Rewriting myapp|web/foo.out.')); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_lazy_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_lazy_transformers_test.dart deleted file mode 100644 index 3c19427ea40..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/supports_user_defined_lazy_transformers_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("supports a user-defined lazy transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", LAZY_TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - // The build should complete without the transformer logging anything. - server.stdout.expect('Build completed successfully'); - - requestShouldSucceed("foo.out", "foo.out"); - server.stdout.expect( - emitsLines('[Info from LazyRewrite]:\n' 'Rewriting myapp|web/foo.txt.')); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/unknown_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/serve/unknown_dependency_test.dart deleted file mode 100644 index daa3c440ba9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/unknown_dependency_test.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("responds with a 404 unknown dependencies", () { - d.dir(appPath, [d.appPubspec()]).create(); - - pubServe(); - requestShould404("packages/foo/nope.dart"); - requestShould404("assets/foo/nope.png"); - requestShould404("dir/packages/foo/nope.dart"); - requestShould404("dir/assets/foo/nope.png"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/uses_appropriate_mime_types_test.dart b/sdk/lib/_internal/pub_generated/test/serve/uses_appropriate_mime_types_test.dart deleted file mode 100644 index bef5217e893..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/uses_appropriate_mime_types_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("uses appropriate mime types", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file("index.html", ""), - d.file("file.dart", "main() => print('hello');"), - d.file("file.js", "console.log('hello');"), - d.file("file.css", "body {color: blue}")])]).create(); - - pubServe(); - requestShouldSucceed( - "index.html", - anything, - headers: containsPair('content-type', 'text/html')); - requestShouldSucceed( - "file.dart", - anything, - headers: containsPair('content-type', 'application/dart')); - requestShouldSucceed( - "file.js", - anything, - headers: containsPair('content-type', 'application/javascript')); - requestShouldSucceed( - "file.css", - anything, - headers: containsPair('content-type', 'text/css')); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/utils.dart b/sdk/lib/_internal/pub_generated/test/serve/utils.dart deleted file mode 100644 index a0ac7cc5704..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/utils.dart +++ /dev/null @@ -1,491 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:http/http.dart' as http; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:stack_trace/stack_trace.dart'; - -import '../../lib/src/utils.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -/// The pub process running "pub serve". -ScheduledProcess _pubServer; - -/// The ephemeral port assign to the running admin server. -int _adminPort; - -/// The ephemeral ports assigned to the running servers, associated with the -/// directories they're serving. -final _ports = new Map(); - -/// A completer that completes when the server has been started and the served -/// ports are known. -Completer _portsCompleter; - -/// The web socket connection to the running pub process, or `null` if no -/// connection has been made. -WebSocket _webSocket; -Stream _webSocketBroadcastStream; - -/// The code for a transformer that renames ".txt" files to ".out" and adds a -/// ".out" suffix. -const REWRITE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, "\$contents.out")); - }); - } -} -"""; - -/// The code for a lazy version of [REWRITE_TRANSFORMER]. -const LAZY_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class LazyRewriteTransformer extends Transformer implements LazyTransformer { - LazyRewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - transform.logger.info('Rewriting \${transform.primaryInput.id}.'); - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, "\$contents.out")); - }); - } - - Future declareOutputs(DeclaringTransform transform) { - transform.declareOutput(transform.primaryId.changeExtension(".out")); - return new Future.value(); - } -} -"""; - -/// The web socket error code for a directory not being served. -const NOT_SERVED = 1; - -/// Returns the source code for a Dart library defining a Transformer that -/// rewrites Dart files. -/// -/// The transformer defines a constant named TOKEN whose value is [id]. When the -/// transformer transforms another Dart file, it will look for a "TOKEN" -/// constant definition there and modify it to include *this* transformer's -/// TOKEN value as well. -/// -/// If [import] is passed, it should be the name of a package that defines its -/// own TOKEN constant. The primary library of that package will be imported -/// here and its TOKEN value will be added to this library's. -/// -/// This transformer takes one configuration field: "addition". This is -/// concatenated to its TOKEN value before adding it to the output library. -String dartTransformer(String id, {String import}) { - if (import != null) { - id = '$id imports \${$import.TOKEN}'; - import = 'import "package:$import/$import.dart" as $import;'; - } else { - import = ''; - } - - return """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -$import - -import 'dart:io'; - -const TOKEN = "$id"; - -final _tokenRegExp = new RegExp(r'^const TOKEN = "(.*?)";\$', multiLine: true); - -class DartTransformer extends Transformer { - final BarbackSettings _settings; - - DartTransformer.asPlugin(this._settings); - - String get allowedExtensions => '.dart'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - transform.addOutput(new Asset.fromString(transform.primaryInput.id, - contents.replaceAllMapped(_tokenRegExp, (match) { - var token = TOKEN; - var addition = _settings.configuration["addition"]; - if (addition != null) token += addition; - return 'const TOKEN = "(\${match[1]}, \$token)";'; - }))); - }); - } -} -"""; -} - -/// Schedules starting the `pub serve` process. -/// -/// Unlike [pubServe], this doesn't determine the port number of the server, and -/// so may be used to test for errors in the initialization process. -/// -/// Returns the `pub serve` process. -ScheduledProcess startPubServe({Iterable args, bool createWebDir: true}) - { - var pubArgs = ["serve", "--port=0", // Use port 0 to get an ephemeral port. - "--force-poll", "--log-admin-url"]; - - if (args != null) pubArgs.addAll(args); - - // Dart2js can take a long time to compile dart code, so we increase the - // timeout to cope with that. - currentSchedule.timeout *= 1.5; - - if (createWebDir) d.dir(appPath, [d.dir("web")]).create(); - return startPub(args: pubArgs); -} - -/// Schedules starting the "pub serve" process and records its port number for -/// future requests. -/// -/// If [shouldGetFirst] is `true`, validates that pub get is run first. -/// -/// If [createWebDir] is `true`, creates a `web/` directory if one doesn't exist -/// so pub doesn't complain about having nothing to serve. -/// -/// Returns the `pub serve` process. -ScheduledProcess pubServe({bool shouldGetFirst: false, bool createWebDir: true, - Iterable args}) { - _pubServer = startPubServe(args: args, createWebDir: createWebDir); - _portsCompleter = new Completer(); - - currentSchedule.onComplete.schedule(() { - _portsCompleter = null; - _ports.clear(); - - if (_webSocket != null) { - _webSocket.close(); - _webSocket = null; - _webSocketBroadcastStream = null; - } - }); - - if (shouldGetFirst) { - _pubServer.stdout.expect( - consumeThrough( - anyOf(["Got dependencies!", matches(new RegExp(r"^Changed \d+ dependenc"))]))); - } - - _pubServer.stdout.expect(startsWith("Loading source assets...")); - _pubServer.stdout.expect(consumeWhile(matches("Loading .* transformers..."))); - - _pubServer.stdout.expect(predicate(_parseAdminPort)); - - // The server should emit one or more ports. - _pubServer.stdout.expect( - consumeWhile(predicate(_parsePort, 'emits server url'))); - schedule(() { - expect(_ports, isNot(isEmpty)); - _portsCompleter.complete(); - }); - - return _pubServer; -} - -/// The regular expression for parsing pub's output line describing the URL for -/// the server. -final _parsePortRegExp = new RegExp(r"([^ ]+) +on http://localhost:(\d+)"); - -/// Parses the port number from the "Running admin server on localhost:1234" -/// line printed by pub serve. -bool _parseAdminPort(String line) { - var match = _parsePortRegExp.firstMatch(line); - if (match == null) return false; - _adminPort = int.parse(match[2]); - return true; -} - -/// Parses the port number from the "Serving blah on localhost:1234" line -/// printed by pub serve. -bool _parsePort(String line) { - var match = _parsePortRegExp.firstMatch(line); - if (match == null) return false; - _ports[match[1]] = int.parse(match[2]); - return true; -} - -void endPubServe() { - _pubServer.kill(); -} - -/// Schedules an HTTP request to the running pub server with [urlPath] and -/// invokes [callback] with the response. -/// -/// [root] indicates which server should be accessed, and defaults to "web". -Future scheduleRequest(String urlPath, {String root}) { - return schedule(() { - return http.get(_getServerUrlSync(root, urlPath)); - }, "request $urlPath"); -} - -/// Schedules an HTTP request to the running pub server with [urlPath] and -/// verifies that it responds with a body that matches [expectation]. -/// -/// [expectation] may either be a [Matcher] or a string to match an exact body. -/// [root] indicates which server should be accessed, and defaults to "web". -/// [headers] may be either a [Matcher] or a map to match an exact headers map. -void requestShouldSucceed(String urlPath, expectation, {String root, headers}) { - scheduleRequest(urlPath, root: root).then((response) { - expect(response.statusCode, equals(200)); - if (expectation != null) expect(response.body, expectation); - if (headers != null) expect(response.headers, headers); - }); -} - -/// Schedules an HTTP request to the running pub server with [urlPath] and -/// verifies that it responds with a 404. -/// -/// [root] indicates which server should be accessed, and defaults to "web". -void requestShould404(String urlPath, {String root}) { - scheduleRequest(urlPath, root: root).then((response) { - expect(response.statusCode, equals(404)); - }); -} - -/// Schedules an HTTP request to the running pub server with [urlPath] and -/// verifies that it responds with a redirect to the given [redirectTarget]. -/// -/// [redirectTarget] may be either a [Matcher] or a string to match an exact -/// URL. [root] indicates which server should be accessed, and defaults to -/// "web". -void requestShouldRedirect(String urlPath, redirectTarget, {String root}) { - schedule(() { - var request = - new http.Request("GET", Uri.parse(_getServerUrlSync(root, urlPath))); - request.followRedirects = false; - return request.send().then((response) { - expect(response.statusCode ~/ 100, equals(3)); - expect(response.headers, containsPair('location', redirectTarget)); - }); - }, "request $urlPath"); -} - -/// Schedules an HTTP POST to the running pub server with [urlPath] and verifies -/// that it responds with a 405. -/// -/// [root] indicates which server should be accessed, and defaults to "web". -void postShould405(String urlPath, {String root}) { - schedule(() { - return http.post(_getServerUrlSync(root, urlPath)).then((response) { - expect(response.statusCode, equals(405)); - }); - }, "request $urlPath"); -} - -/// Schedules an HTTP request to the (theoretically) running pub server with -/// [urlPath] and verifies that it cannot be connected to. -/// -/// [root] indicates which server should be accessed, and defaults to "web". -void requestShouldNotConnect(String urlPath, {String root}) { - schedule(() { - return expect( - http.get(_getServerUrlSync(root, urlPath)), - throwsA(new isInstanceOf())); - }, "request $urlPath"); -} - -/// Reads lines from pub serve's stdout until it prints the build success -/// message. -/// -/// The schedule will not proceed until the output is found. If not found, it -/// will eventually time out. -void waitForBuildSuccess() => - _pubServer.stdout.expect(consumeThrough(contains("successfully"))); - -/// Schedules opening a web socket connection to the currently running pub -/// serve. -Future _ensureWebSocket() { - // Use the existing one if already connected. - if (_webSocket != null) return new Future.value(); - - // Server should already be running. - expect(_pubServer, isNotNull); - expect(_adminPort, isNotNull); - - return WebSocket.connect("ws://localhost:$_adminPort").then((socket) { - _webSocket = socket; - // TODO(rnystrom): Works around #13913. - _webSocketBroadcastStream = _webSocket.map(JSON.decode).asBroadcastStream(); - }); -} - -/// Schedules closing the web socket connection to the currently-running pub -/// serve. -void closeWebSocket() { - schedule(() { - return _ensureWebSocket().then((_) => _webSocket.close()).then((_) => _webSocket = - null); - }, "closing web socket"); -} - -/// Sends a JSON RPC 2.0 request to the running pub serve's web socket -/// connection. -/// -/// This calls a method named [method] with the given [params] (or no -/// parameters, if it's not passed). [params] may contain Futures, in which case -/// this will wait until they've completed before sending the request. -/// -/// This schedules the request, but doesn't block the schedule on the response. -/// It returns the response as a [Future]. -Future webSocketRequest(String method, [Map params]) { - var completer = new Completer(); - schedule(() { - return Future.wait( - [_ensureWebSocket(), awaitObject(params),]).then((results) { - var resolvedParams = results[1]; - chainToCompleter( - currentSchedule.wrapFuture(_jsonRpcRequest(method, resolvedParams)), - completer); - }); - }, "send $method with $params to web socket"); - return completer.future; -} - -/// Sends a JSON RPC 2.0 request to the running pub serve's web socket -/// connection, waits for a reply, then verifies the result. -/// -/// This calls a method named [method] with the given [params]. [params] may -/// contain Futures, in which case this will wait until they've completed before -/// sending the request. -/// -/// The result is validated using [result], which may be a [Matcher] or a [Map] -/// containing [Matcher]s and [Future]s. This will wait until any futures are -/// completed before sending the request. -/// -/// Returns a [Future] that completes to the call's result. -Future expectWebSocketResult(String method, Map params, result) { - return schedule(() { - return Future.wait( - [webSocketRequest(method, params), awaitObject(result)]).then((results) { - var response = results[0]; - var resolvedResult = results[1]; - expect(response["result"], resolvedResult); - return response["result"]; - }); - }, "send $method with $params to web socket and expect $result"); -} - -/// Sends a JSON RPC 2.0 request to the running pub serve's web socket -/// connection, waits for a reply, then verifies the error response. -/// -/// This calls a method named [method] with the given [params]. [params] may -/// contain Futures, in which case this will wait until they've completed before -/// sending the request. -/// -/// The error response is validated using [errorCode] and [errorMessage]. Both -/// of these must be provided. The error code is checked against [errorCode] and -/// the error message is checked against [errorMessage]. Either of these may be -/// matchers. -/// -/// If [data] is provided, it is a JSON value or matcher used to validate the -/// "data" value of the error response. -/// -/// Returns a [Future] that completes to the error's [data] field. -Future expectWebSocketError(String method, Map params, errorCode, errorMessage, - {data}) { - return schedule(() { - return webSocketRequest(method, params).then((response) { - expect(response["error"]["code"], errorCode); - expect(response["error"]["message"], errorMessage); - - if (data != null) { - expect(response["error"]["data"], data); - } - - return response["error"]["data"]; - }); - }, "send $method with $params to web socket and expect error $errorCode"); -} - -/// Validates that [root] was not bound to a port when pub serve started. -Future expectNotServed(String root) { - return schedule(() { - expect(_ports.containsKey(root), isFalse); - }); -} - -/// The next id to use for a JSON-RPC 2.0 request. -var _rpcId = 0; - -/// Sends a JSON-RPC 2.0 request calling [method] with [params]. -/// -/// Returns the response object. -Future _jsonRpcRequest(String method, [Map params]) { - var id = _rpcId++; - var message = { - "jsonrpc": "2.0", - "method": method, - "id": id - }; - if (params != null) message["params"] = params; - _webSocket.add(JSON.encode(message)); - - return _webSocketBroadcastStream.firstWhere( - (response) => response["id"] == id).then((value) { - currentSchedule.addDebugInfo( - "Web Socket request $method with params $params\n" "Result: $value"); - - expect(value["id"], equals(id)); - return value; - }); -} - -/// Returns a [Future] that completes to a URL string for the server serving -/// [path] from [root]. -/// -/// If [root] is omitted, defaults to "web". If [path] is omitted, no path is -/// included. The Future will complete once the server is up and running and -/// the bound ports are known. -Future getServerUrl([String root, String path]) => - _portsCompleter.future.then((_) => _getServerUrlSync(root, path)); - -/// Records that [root] has been bound to [port]. -/// -/// Used for testing the Web Socket API for binding new root directories to -/// ports after pub serve has been started. -registerServerPort(String root, int port) { - _ports[root] = port; -} - -/// Returns a URL string for the server serving [path] from [root]. -/// -/// If [root] is omitted, defaults to "web". If [path] is omitted, no path is -/// included. Unlike [getServerUrl], this should only be called after the ports -/// are known. -String _getServerUrlSync([String root, String path]) { - if (root == null) root = 'web'; - expect(_ports, contains(root)); - var url = "http://localhost:${_ports[root]}"; - if (path != null) url = "$url/$path"; - return url; -} - diff --git a/sdk/lib/_internal/pub_generated/test/serve/watch_added_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/watch_added_file_test.dart deleted file mode 100644 index fa2063c0492..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/watch_added_file_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("picks up files added after serving started", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create(); - - pubServe(); - waitForBuildSuccess(); - requestShouldSucceed("index.html", "body"); - - d.dir(appPath, [d.dir("web", [d.file("other.html", "added")])]).create(); - - waitForBuildSuccess(); - requestShouldSucceed("other.html", "added"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/watch_modified_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/watch_modified_file_test.dart deleted file mode 100644 index a42373726dd..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/watch_modified_file_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("watches modifications to files", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "before")])]).create(); - - pubServe(); - requestShouldSucceed("index.html", "before"); - - d.dir(appPath, [d.dir("web", [d.file("index.html", "after")])]).create(); - - waitForBuildSuccess(); - requestShouldSucceed("index.html", "after"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/watch_removed_file_test.dart b/sdk/lib/_internal/pub_generated/test/serve/watch_removed_file_test.dart deleted file mode 100644 index 222a4e31b69..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/watch_removed_file_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -main() { - initConfig(); - integration("stop serving a file that is removed", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "body")])]).create(); - - pubServe(); - requestShouldSucceed("index.html", "body"); - - schedule( - () => deleteEntry(path.join(sandboxDir, appPath, "web", "index.html"))); - - waitForBuildSuccess(); - requestShould404("index.html"); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/exit_on_close_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/exit_on_close_test.dart deleted file mode 100644 index 7e76bc43944..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/exit_on_close_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("exits when the connection closes", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "")])]).create(); - - var server = pubServe(); - - // Make sure the web socket is active. - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("web", "index.html") - }, { - "package": "myapp", - "path": "web/index.html" - }); - - expectWebSocketResult("exitOnClose", null, null); - - // Close the web socket. - closeWebSocket(); - - server.stdout.expect("Build completed successfully"); - server.stdout.expect("WebSocket connection closed, terminating."); - server.shouldExit(0); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_errors_test.dart deleted file mode 100644 index 777463601b9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_errors_test.dart +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:json_rpc_2/error_code.dart' as rpc_error_code; -import 'package:path/path.dart' as p; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - // TODO(rnystrom): Split into independent tests. - initConfig(); - integration("pathToUrls errors on bad inputs", () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), - d.file("top-level.txt", "top-level"), - d.dir("bin", [d.file("foo.txt", "foo"),]), - d.dir("lib", [d.file("myapp.dart", "myapp"),])]).create(); - - pubServe(shouldGetFirst: true); - - // Bad arguments. - expectWebSocketError("pathToUrls", { - "path": 123 - }, - rpc_error_code.INVALID_PARAMS, - 'Parameter "path" for method "pathToUrls" must be a string, but was ' '123.'); - - expectWebSocketError("pathToUrls", { - "path": "main.dart", - "line": 12.34 - }, - rpc_error_code.INVALID_PARAMS, - 'Parameter "line" for method "pathToUrls" must be an integer, but was ' - '12.34.'); - - // Unserved directories. - expectNotServed(p.join('bin', 'foo.txt')); - expectNotServed(p.join('nope', 'foo.txt')); - expectNotServed(p.join("..", "bar", "lib", "bar.txt")); - expectNotServed(p.join("..", "foo", "web", "foo.txt")); - - endPubServe(); - }); -} - -void expectNotServed(String path) { - expectWebSocketError("pathToUrls", { - "path": path - }, NOT_SERVED, 'Asset path "$path" is not currently being served.'); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_test.dart deleted file mode 100644 index 820d5522fee..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_test.dart +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; - -import '../../../lib/src/io.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - // TODO(rnystrom): Split into independent tests. - initConfig(); - integration("pathToUrls converts asset ids to matching URL paths", () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.0.0"), - d.dir("lib", [d.file("foo.dart", "foo() => null;")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), - d.dir( - "test", - [d.file("index.html", ""), d.dir("sub", [d.file("bar.html", "bar"),])]), - d.dir("lib", [d.file("app.dart", "app() => null;")]), - d.dir( - "web", - [d.file("index.html", ""), d.dir("sub", [d.file("bar.html", "bar"),])]), - d.dir("randomdir", [d.file("index.html", "")])]).create(); - - pubServe(args: ["test", "web", "randomdir"], shouldGetFirst: true); - - // Paths in web/. - expectWebSocketResult("pathToUrls", { - "path": p.join("web", "index.html") - }, { - "urls": [getServerUrl("web", "index.html")] - }); - - expectWebSocketResult("pathToUrls", { - "path": p.join("web", "sub", "bar.html") - }, { - "urls": [getServerUrl("web", "sub/bar.html")] - }); - - // Paths in test/. - expectWebSocketResult("pathToUrls", { - "path": p.join("test", "index.html") - }, { - "urls": [getServerUrl("test", "index.html")] - }); - - expectWebSocketResult("pathToUrls", { - "path": p.join("test", "sub", "bar.html") - }, { - "urls": [getServerUrl("test", "sub/bar.html")] - }); - - // A non-default directory. - expectWebSocketResult("pathToUrls", { - "path": p.join("randomdir", "index.html") - }, { - "urls": [getServerUrl("randomdir", "index.html")] - }); - - // A path in lib/. - expectWebSocketResult("pathToUrls", { - "path": p.join("lib", "app.dart") - }, { - "urls": [ - getServerUrl("test", "packages/myapp/app.dart"), - getServerUrl("web", "packages/myapp/app.dart"), - getServerUrl("randomdir", "packages/myapp/app.dart")] - }); - - // A path to this package in packages/. - expectWebSocketResult("pathToUrls", { - "path": p.join("packages", "myapp", "app.dart") - }, { - "urls": [ - getServerUrl("test", "packages/myapp/app.dart"), - getServerUrl("web", "packages/myapp/app.dart"), - getServerUrl("randomdir", "packages/myapp/app.dart")] - }); - - // A path to another package in packages/. - expectWebSocketResult("pathToUrls", { - "path": p.join("packages", "foo", "foo.dart") - }, { - "urls": [ - getServerUrl("test", "packages/foo/foo.dart"), - getServerUrl("web", "packages/foo/foo.dart"), - getServerUrl("randomdir", "packages/foo/foo.dart")] - }); - - // A relative path to another package's lib/ directory. - expectWebSocketResult("pathToUrls", { - "path": p.join("..", "foo", "lib", "foo.dart") - }, { - "urls": [ - getServerUrl("test", "packages/foo/foo.dart"), - getServerUrl("web", "packages/foo/foo.dart"), - getServerUrl("randomdir", "packages/foo/foo.dart")] - }); - - // Note: Using canonicalize here because pub gets the path to the - // entrypoint package from the working directory, which has had symlinks - // resolve. On Mac, "/tmp" is actually a symlink to "/private/tmp", so we - // need to accomodate that. - - // An absolute path to another package's lib/ directory. - expectWebSocketResult("pathToUrls", { - "path": canonicalize(p.join(sandboxDir, "foo", "lib", "foo.dart")) - }, { - "urls": [ - getServerUrl("test", "packages/foo/foo.dart"), - getServerUrl("web", "packages/foo/foo.dart"), - getServerUrl("randomdir", "packages/foo/foo.dart")] - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_with_line_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_with_line_test.dart deleted file mode 100644 index 4e2f244a703..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/path_to_urls_with_line_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("pathToUrls provides output line if given source", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("main.dart", "main"),])]).create(); - - pubServe(); - - expectWebSocketResult("pathToUrls", { - "path": p.join("web", "main.dart"), - "line": 12345 - }, { - "urls": [getServerUrl("web", "main.dart")], - "line": 12345 - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_already_served_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_already_served_test.dart deleted file mode 100644 index 6e27e86afdb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_already_served_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("returns the old URL if the directory is already served", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(); - - expectWebSocketResult("serveDirectory", { - "path": "web" - }, { - "url": getServerUrl("web") - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_request_asset_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_request_asset_test.dart deleted file mode 100644 index 19db3073f69..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_request_asset_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration( - "binds a directory to a new port and immediately requests an " - "asset URL from that server", - () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("test", [d.file("index.html", "")]), - d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(args: ["web"]); - - // Bind the new directory. - expect(webSocketRequest("serveDirectory", { - "path": "test" - }), completes); - - expectWebSocketResult("pathToUrls", { - "path": "test/index.html" - }, { - "urls": [endsWith("/index.html")] - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_serve_again_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_serve_again_test.dart deleted file mode 100644 index 0de587742e7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_serve_again_test.dart +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:async'; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration( - "binds a directory to a new port and immediately binds that " "directory again", - () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("test", [d.file("index.html", "")]), - d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(args: ["web"]); - - schedule(() { - return Future.wait([webSocketRequest("serveDirectory", { - "path": "test" - }), webSocketRequest("serveDirectory", { - "path": "test" - })]).then((results) { - expect(results[0], contains("result")); - expect(results[1], contains("result")); - expect(results[0]["result"], equals(results[1]["result"])); - }); - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_unserve_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_unserve_test.dart deleted file mode 100644 index 7266680f05c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_and_immediately_unserve_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:async'; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration( - "binds a directory to a new port and immediately unbinds that " "directory", - () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("test", [d.file("index.html", "")]), - d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(args: ["web"]); - - // We call [webSocketRequest] outside of the [schedule] call below because - // we need it to schedule the sending of the request to guarantee that the - // serve is sent before the unserve. - var serveRequest = webSocketRequest("serveDirectory", { - "path": "test" - }); - var unserveRequest = webSocketRequest("unserveDirectory", { - "path": "test" - }); - - schedule(() { - return Future.wait([serveRequest, unserveRequest]).then((results) { - expect(results[0], contains("result")); - expect(results[1], contains("result")); - // These results should be equal since "serveDirectory" returns the URL - // of the new server and "unserveDirectory" returns the URL of the - // server that was turned off. We're asserting that the same server was - // both started and stopped. - expect(results[0]["result"]["url"], matches(r"http://localhost:\d+")); - expect(results[0]["result"], equals(results[1]["result"])); - }); - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_arg_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_arg_errors_test.dart deleted file mode 100644 index 7a6374d80d2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_arg_errors_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:json_rpc_2/error_code.dart' as rpc_error_code; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "")])]).create(); - }); - - integration("responds with an error if 'path' is not a string", () { - pubServe(); - expectWebSocketError("serveDirectory", { - "path": 123 - }, - rpc_error_code.INVALID_PARAMS, - 'Parameter "path" for method "serveDirectory" must be a string, but ' - 'was 123.'); - endPubServe(); - }); - - integration("responds with an error if 'path' is absolute", () { - pubServe(); - expectWebSocketError("serveDirectory", { - "path": "/absolute.txt" - }, - rpc_error_code.INVALID_PARAMS, - '"path" must be a relative path. Got "/absolute.txt".'); - endPubServe(); - }); - - integration("responds with an error if 'path' reaches out", () { - pubServe(); - expectWebSocketError("serveDirectory", { - "path": "a/../../bad.txt" - }, - rpc_error_code.INVALID_PARAMS, - '"path" cannot reach out of its containing directory. Got ' - '"a/../../bad.txt".'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_overlapping_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_overlapping_test.dart deleted file mode 100644 index 69025310e54..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_overlapping_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("fails if the directory overlaps one already being served", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir( - "web", - [ - d.file("index.html", ""), - d.dir("sub", [d.file("index.html", ""),])])]).create(); - - pubServe(); - - var webSub = path.join("web", "sub"); - expectWebSocketError("serveDirectory", { - "path": webSub - }, - 2, - 'Path "$webSub" overlaps already served directory "web".', - data: containsPair("directories", ["web"])); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_test.dart deleted file mode 100644 index 5738eb25d9a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/serve_directory_test.dart +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("binds a directory to a new port", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("test", [d.file("index.html", "")]), - d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(args: ["web"]); - - // Bind the new directory. - expectWebSocketResult("serveDirectory", { - "path": "test" - }, { - "url": matches(r"http://localhost:\d+") - }).then((response) { - var url = Uri.parse(response["url"]); - registerServerPort("test", url.port); - }); - - // It should be served now. - requestShouldSucceed("index.html", "", root: "test"); - - // And watched. - d.dir(appPath, [d.dir("test", [d.file("index.html", "after")])]).create(); - - waitForBuildSuccess(); - requestShouldSucceed("index.html", "after", root: "test"); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_arg_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_arg_errors_test.dart deleted file mode 100644 index 25fd234e065..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_arg_errors_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:json_rpc_2/error_code.dart' as rpc_error_code; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - - setUp(() { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "")])]).create(); - }); - - integration("responds with an error if 'path' is not a string", () { - pubServe(); - expectWebSocketError("unserveDirectory", { - "path": 123 - }, - rpc_error_code.INVALID_PARAMS, - 'Parameter "path" for method "unserveDirectory" must be a string, but ' - 'was 123.'); - endPubServe(); - }); - - integration("responds with an error if 'path' is absolute", () { - pubServe(); - expectWebSocketError("unserveDirectory", { - "path": "/absolute.txt" - }, - rpc_error_code.INVALID_PARAMS, - '"path" must be a relative path. Got "/absolute.txt".'); - endPubServe(); - }); - - integration("responds with an error if 'path' reaches out", () { - pubServe(); - expectWebSocketError("unserveDirectory", { - "path": "a/../../bad.txt" - }, - rpc_error_code.INVALID_PARAMS, - '"path" cannot reach out of its containing directory. Got ' - '"a/../../bad.txt".'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_not_served_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_not_served_test.dart deleted file mode 100644 index 528f0511ecb..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_not_served_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("errors if the directory is not served", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(); - - // Unbind the directory. - expectWebSocketError("unserveDirectory", { - "path": "test" - }, NOT_SERVED, 'Directory "test" is not bound to a server.'); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_test.dart deleted file mode 100644 index c182e57f24f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/unserve_directory_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("unbinds a directory from a port", () { - d.dir( - appPath, - [ - d.appPubspec(), - d.dir("test", [d.file("index.html", "")]), - d.dir("web", [d.file("index.html", "")])]).create(); - - pubServe(); - - requestShouldSucceed("index.html", ""); - requestShouldSucceed("index.html", "", root: "test"); - - // Unbind the directory. - expectWebSocketResult("unserveDirectory", { - "path": "test" - }, { - "url": getServerUrl("test") - }); - - // "test" should not be served now. - requestShouldNotConnect("index.html", root: "test"); - - // "web" is still fine. - requestShouldSucceed("index.html", ""); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_errors_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_errors_test.dart deleted file mode 100644 index 4892bf31672..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_errors_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - setUp(() { - d.dir(appPath, [d.appPubspec()]).create(); - }); - - integration("responds with NOT_SERVED for an unknown domain", () { - pubServe(); - expectWebSocketError("urlToAssetId", { - "url": "http://example.com:80/index.html" - }, NOT_SERVED, '"example.com:80" is not being served by pub.'); - endPubServe(); - }); - - integration("responds with NOT_SERVED for an unknown port", () { - pubServe(); - expectWebSocketError("urlToAssetId", { - "url": "http://localhost:80/index.html" - }, NOT_SERVED, '"localhost:80" is not being served by pub.'); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_test.dart deleted file mode 100644 index a5727725f03..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_test.dart +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - // TODO(rnystrom): Split into independent tests. - initConfig(); - setUp(() { - d.dir( - "foo", - [ - d.libPubspec("foo", "0.0.1"), - d.dir("lib", [d.file("foo.dart", "foo")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), - d.dir("lib", [d.file("myapp.dart", "myapp"),]), - d.dir( - "test", - [d.file("index.html", ""), d.dir("sub", [d.file("bar.html", "bar"),])]), - d.dir( - "web", - [ - d.file("index.html", ""), - d.dir("sub", [d.file("bar.html", "bar"),])])]).create(); - }); - - integration("converts URLs to matching asset ids in web/", () { - pubServe(shouldGetFirst: true); - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("web", "index.html") - }, { - "package": "myapp", - "path": "web/index.html" - }); - endPubServe(); - }); - - integration( - "converts URLs to matching asset ids in subdirectories of web/", - () { - pubServe(shouldGetFirst: true); - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("web", "sub/bar.html") - }, { - "package": "myapp", - "path": "web/sub/bar.html" - }); - endPubServe(); - }); - - integration("converts URLs to matching asset ids in test/", () { - pubServe(shouldGetFirst: true); - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("test", "index.html") - }, { - "package": "myapp", - "path": "test/index.html" - }); - endPubServe(); - }); - - integration( - "converts URLs to matching asset ids in subdirectories of test/", - () { - pubServe(shouldGetFirst: true); - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("test", "sub/bar.html") - }, { - "package": "myapp", - "path": "test/sub/bar.html" - }); - endPubServe(); - }); - - integration( - "converts URLs to matching asset ids in the entrypoint's lib/", - () { - // Path in root package's lib/. - pubServe(shouldGetFirst: true); - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("web", "packages/myapp/myapp.dart") - }, { - "package": "myapp", - "path": "lib/myapp.dart" - }); - endPubServe(); - }); - - integration("converts URLs to matching asset ids in a dependency's lib/", () { - // Path in lib/. - pubServe(shouldGetFirst: true); - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("web", "packages/foo/foo.dart") - }, { - "package": "foo", - "path": "lib/foo.dart" - }); - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_with_line_test.dart b/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_with_line_test.dart deleted file mode 100644 index da13fc5a050..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve/web_socket/url_to_asset_id_with_line_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../utils.dart'; - -main() { - initConfig(); - integration("provides output line number if given source one", () { - d.dir( - appPath, - [d.appPubspec(), d.dir("web", [d.file("main.dart", "main")])]).create(); - - pubServe(); - - // Paths in web/. - expectWebSocketResult("urlToAssetId", { - "url": getServerUrl("web", "main.dart"), - "line": 12345 - }, { - "package": "myapp", - "path": "web/main.dart", - "line": 12345 - }); - - endPubServe(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/serve_packages.dart b/sdk/lib/_internal/pub_generated/test/serve_packages.dart deleted file mode 100644 index 2fad96dded9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/serve_packages.dart +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library serve_packages; - -import 'dart:async'; -import 'dart:convert'; - -import 'package:path/path.dart' as p; -import 'package:pub_semver/pub_semver.dart'; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:yaml/yaml.dart'; - -import '../lib/src/io.dart'; -import '../lib/src/utils.dart'; -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -/// The [d.DirectoryDescriptor] describing the server layout of `/api/packages` -/// on the test server. -/// -/// This contains metadata for packages that are being served via -/// [servePackages]. It's `null` if [servePackages] has not yet been called for -/// this test. -d.DirectoryDescriptor _servedApiPackageDir; - -/// The [d.DirectoryDescriptor] describing the server layout of `/packages` on -/// the test server. -/// -/// This contains the tarballs for packages that are being served via -/// [servePackages]. It's `null` if [servePackages] has not yet been called for -/// this test. -d.DirectoryDescriptor _servedPackageDir; - -/// The current [PackageServerBuilder] that a user uses to specify which package -/// to serve. -/// -/// This is preserved over multiple calls to [servePackages] within the same -/// test so that additional packages can be added. -PackageServerBuilder _builder; - -/// Creates an HTTP server that replicates the structure of pub.dartlang.org. -/// -/// Calls [callback] with a [PackageServerBuilder] that's used to specify -/// which packages to serve. -/// -/// If [replace] is false, subsequent calls to [servePackages] will add to the -/// set of packages that are being served. Previous packages will continue to be -/// served. Otherwise, the previous packages will no longer be served. -void servePackages(void callback(PackageServerBuilder builder), {bool replace: - false}) { - if (_servedPackageDir == null) { - _builder = new PackageServerBuilder(); - _servedApiPackageDir = d.dir('packages', []); - _servedPackageDir = d.dir('packages', []); - serve([d.dir('api', [_servedApiPackageDir]), _servedPackageDir]); - - currentSchedule.onComplete.schedule(() { - _builder = null; - _servedApiPackageDir = null; - _servedPackageDir = null; - }, 'cleaning up served packages'); - } - - schedule(() { - if (replace) _builder = new PackageServerBuilder(); - callback(_builder); - return _builder._await().then((resolvedPubspecs) { - _servedApiPackageDir.contents.clear(); - _servedPackageDir.contents.clear(); - _builder._packages.forEach((name, versions) { - _servedApiPackageDir.contents.addAll([d.file('$name', JSON.encode({ - 'name': name, - 'uploaders': ['nweiz@google.com'], - 'versions': versions.map( - (version) => packageVersionApiMap(version.pubspec)).toList() - })), d.dir(name, [d.dir('versions', versions.map((version) { - return d.file( - version.version.toString(), - JSON.encode(packageVersionApiMap(version.pubspec, full: true))); - }))])]); - - _servedPackageDir.contents.add( - d.dir( - name, - [ - d.dir( - 'versions', - versions.map( - (version) => d.tar('${version.version}.tar.gz', version.contents)))])); - }); - }); - }, 'initializing the package server'); -} - -/// Like [servePackages], but instead creates an empty server with no packages -/// registered. -/// -/// This will always replace a previous server. -void serveNoPackages() => servePackages((_) {}, replace: true); - -/// A builder for specifying which packages should be served by [servePackages]. -class PackageServerBuilder { - /// A map from package names to a list of concrete packages to serve. - final _packages = new Map>(); - - /// A group of futures from [serve] calls. - /// - /// This should be accessed by calling [_awair]. - var _futures = new FutureGroup(); - - /// Specifies that a package named [name] with [version] should be served. - /// - /// If [deps] is passed, it's used as the "dependencies" field of the pubspec. - /// If [pubspec] is passed, it's used as the rest of the pubspec. Either of - /// these may recursively contain Futures. - /// - /// If [contents] is passed, it's used as the contents of the package. By - /// default, a package just contains a dummy lib directory. - void serve(String name, String version, {Map deps, Map pubspec, - Iterable contents}) { - _futures.add( - Future.wait([awaitObject(deps), awaitObject(pubspec)]).then((pair) { - var resolvedDeps = pair.first; - var resolvedPubspec = pair.last; - - var pubspecFields = { - "name": name, - "version": version - }; - if (resolvedPubspec != null) pubspecFields.addAll(resolvedPubspec); - if (resolvedDeps != null) pubspecFields["dependencies"] = resolvedDeps; - - if (contents == null) contents = [d.libDir(name, "$name $version")]; - contents = - [d.file("pubspec.yaml", yaml(pubspecFields))]..addAll(contents); - - var packages = _packages.putIfAbsent(name, () => []); - packages.add(new _ServedPackage(pubspecFields, contents)); - })); - } - - /// Serves the versions of [package] and all its dependencies that are - /// currently checked into the Dart repository. - void serveRepoPackage(String package) { - _addPackage(name) { - if (_packages.containsKey(name)) return; - _packages[name] = []; - - var root = packagePath(name); - var pubspec = - new Map.from(loadYaml(readTextFile(p.join(root, 'pubspec.yaml')))); - - // Remove any SDK constraints since we don't have a valid SDK version - // while testing. - pubspec.remove('environment'); - - _packages[name].add( - new _ServedPackage( - pubspec, - [ - d.file('pubspec.yaml', yaml(pubspec)), - new d.DirectoryDescriptor.fromFilesystem('lib', p.join(root, 'lib'))])); - - if (pubspec.containsKey('dependencies')) { - pubspec['dependencies'].keys.forEach(_addPackage); - } - } - - _addPackage(package); - } - - /// Returns a Future that completes once all the [serve] calls have been fully - /// processed. - Future _await() { - if (_futures.futures.isEmpty) return new Future.value(); - return _futures.future.then((_) { - _futures = new FutureGroup(); - }); - } -} - -/// A package that's intended to be served. -class _ServedPackage { - final Map pubspec; - final List contents; - - Version get version => new Version.parse(pubspec['version']); - - _ServedPackage(this.pubspec, this.contents); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_for_immediate_and_transitive_dep_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_for_immediate_and_transitive_dep_test.dart deleted file mode 100644 index c9a50340259..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_for_immediate_and_transitive_dep_test.dart +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "creates a snapshot for an immediate dependency that's also a " - "transitive dependency", - () { - servePackages((builder) { - builder.serve( - "foo", - "1.2.3", - contents: [ - d.dir( - "bin", - [ - d.file("hello.dart", "void main() => print('hello!');"), - d.file("goodbye.dart", "void main() => print('goodbye!');"), - d.file("shell.sh", "echo shell"), - d.dir("subdir", [d.file("sub.dart", "void main() => print('sub!');")])])]); - builder.serve("bar", "1.2.3", deps: { - "foo": "1.2.3" - }); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet( - output: allOf( - [contains("Precompiled foo:hello."), contains("Precompiled foo:goodbye.")])); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [ - d.file('sdk-version', '0.1.2+3\n'), - d.dir( - 'foo', - [ - d.matcherFile('hello.dart.snapshot', contains('hello!')), - d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')), - d.nothing('shell.sh.snapshot'), - d.nothing('subdir')])]).validate(); - - var process = pubRun(args: ['foo:hello']); - process.stdout.expect("hello!"); - process.shouldExit(); - - process = pubRun(args: ['foo:goodbye']); - process.stdout.expect("goodbye!"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_test.dart deleted file mode 100644 index 553829dd7d6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/creates_a_snapshot_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "creates a snapshot for an immediate dependency's executables", - () { - servePackages((builder) { - builder.serve( - "foo", - "1.2.3", - contents: [ - d.dir( - "bin", - [ - d.file("hello.dart", "void main() => print('hello!');"), - d.file("goodbye.dart", "void main() => print('goodbye!');"), - d.file("shell.sh", "echo shell"), - d.dir("subdir", [d.file("sub.dart", "void main() => print('sub!');")])])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet( - output: allOf( - [contains("Precompiled foo:hello."), contains("Precompiled foo:goodbye.")])); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [ - d.file('sdk-version', '0.1.2+3\n'), - d.dir( - 'foo', - [ - d.matcherFile('hello.dart.snapshot', contains('hello!')), - d.matcherFile('goodbye.dart.snapshot', contains('goodbye!')), - d.nothing('shell.sh.snapshot'), - d.nothing('subdir')])]).validate(); - - var process = pubRun(args: ['foo:hello']); - process.stdout.expect("hello!"); - process.shouldExit(); - - process = pubRun(args: ['foo:goodbye']); - process.stdout.expect("goodbye!"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_load_irrelevant_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_load_irrelevant_transformers_test.dart deleted file mode 100644 index 7759718f0d3..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_load_irrelevant_transformers_test.dart +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const BROKEN_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class BrokenTransformer extends Transformer { - BrokenTransformer.asPlugin(); - - // This file intentionally has a syntax error so that any attempt to load it - // will crash. -"""; - -main() { - initConfig(); - - // Regression test for issue 20917. - integration("snapshots the transformed version of an executable", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve( - "foo", - "1.2.3", - contents: [ - d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "1.2.3", - "barback": "any" - }, - "transformers": ["myapp"] - }), - d.dir("lib", [d.file("transformer.dart", BROKEN_TRANSFORMER)])]).create(); - - pubGet(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [ - d.dir( - 'foo', - [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).validate(); - - var process = pubRun(args: ['foo:hello']); - process.stdout.expect("hello!"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_resnapshot_when_a_dependency_is_unchanged_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_resnapshot_when_a_dependency_is_unchanged_test.dart deleted file mode 100644 index b19f0600238..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_resnapshot_when_a_dependency_is_unchanged_test.dart +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't recreate a snapshot when no dependencies of a package " "have changed", - () { - servePackages((builder) { - builder.serve("foo", "1.2.3", deps: { - "bar": "any" - }, - contents: [ - d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]); - builder.serve("bar", "1.2.3"); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: contains("Precompiled foo:hello.")); - - pubUpgrade(output: isNot(contains("Precompiled foo:hello."))); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [ - d.file('sdk-version', '0.1.2+3\n'), - d.dir( - 'foo', - [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_an_entrypoint_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_an_entrypoint_dependency_test.dart deleted file mode 100644 index 60998e1f37f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_an_entrypoint_dependency_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't create a snapshot for a package that depends on the " "entrypoint", - () { - servePackages((builder) { - builder.serve("foo", "1.2.3", deps: { - 'bar': '1.2.3' - }, - contents: [ - d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]); - builder.serve("bar", "1.2.3", deps: { - 'myapp': 'any' - }); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(); - - // No local cache should be created, since all dependencies transitively - // depend on the entrypoint. - d.nothing(p.join(appPath, '.pub', 'bin')).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_path_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_path_dependency_test.dart deleted file mode 100644 index 6542ab11bf9..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_path_dependency_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("doesn't create a snapshot for a path dependency", () { - d.dir( - "foo", - [ - d.libPubspec("foo", "1.2.3"), - d.dir( - "bin", - [ - d.dir( - "bin", - [d.file("hello.dart", "void main() => print('hello!');")])])]).create(); - - d.appDir({ - "foo": { - "path": "../foo" - } - }).create(); - - pubGet(); - - d.nothing(p.join(appPath, '.pub', 'bin')).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_transitive_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_transitive_dependencies_test.dart deleted file mode 100644 index 3ea2d22e9f8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/doesnt_snapshot_transitive_dependencies_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't create a snapshot for transitive dependencies' " "executables", - () { - servePackages((builder) { - builder.serve("foo", "1.2.3", deps: { - 'bar': '1.2.3' - }); - builder.serve( - "bar", - "1.2.3", - contents: [ - d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(); - - d.nothing(p.join(appPath, '.pub', 'bin', 'bar')).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/prints_errors_for_broken_snapshots_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/prints_errors_for_broken_snapshots_test.dart deleted file mode 100644 index 60b5e1c06b0..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/prints_errors_for_broken_snapshots_test.dart +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("prints errors for broken snapshot compilation", () { - servePackages((builder) { - builder.serve( - "foo", - "1.2.3", - contents: [ - d.dir( - "bin", - [ - d.file("hello.dart", "void main() { no closing brace"), - d.file("goodbye.dart", "void main() { no closing brace"),])]); - builder.serve( - "bar", - "1.2.3", - contents: [ - d.dir( - "bin", - [ - d.file("hello.dart", "void main() { no closing brace"), - d.file("goodbye.dart", "void main() { no closing brace"),])]); - }); - - d.appDir({ - "foo": "1.2.3", - "bar": "1.2.3" - }).create(); - - // This should still have a 0 exit code, since installation succeeded even - // if precompilation didn't. - pubGet( - error: allOf( - [ - contains("Failed to precompile foo:hello"), - contains("Failed to precompile foo:goodbye"), - contains("Failed to precompile bar:hello"), - contains("Failed to precompile bar:goodbye")]), - exitCode: 0); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [ - d.file('sdk-version', '0.1.2+3\n'), - d.dir( - 'foo', - [d.nothing('hello.dart.snapshot'), d.nothing('goodbye.dart.snapshot')]), - d.dir( - 'bar', - [ - d.nothing('hello.dart.snapshot'), - d.nothing('goodbye.dart.snapshot')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/recompiles_if_the_sdk_is_out_of_date_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/recompiles_if_the_sdk_is_out_of_date_test.dart deleted file mode 100644 index f10098fc185..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/recompiles_if_the_sdk_is_out_of_date_test.dart +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration( - "creates a snapshot for an immediate dependency's executables", - () { - servePackages((builder) { - builder.serve( - "foo", - "5.6.7", - contents: [ - d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]); - }); - - d.appDir({ - "foo": "5.6.7" - }).create(); - - pubGet(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [d.dir('foo', [d.outOfDateSnapshot('hello.dart.snapshot')])]).create(); - - var process = pubRun(args: ['foo:hello']); - - // In the real world this would just print "hello!", but since we collect - // all output we see the precompilation messages as well. - process.stdout.expect("Precompiling executables..."); - process.stdout.expect(consumeThrough("hello!")); - process.shouldExit(); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [ - d.file('sdk-version', '0.1.2+3'), - d.dir( - 'foo', - [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).create(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/snapshots_transformed_code_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/snapshots_transformed_code_test.dart deleted file mode 100644 index 6defffb7e82..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/snapshots_transformed_code_test.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const REPLACE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ReplaceTransformer extends Transformer { - ReplaceTransformer.asPlugin(); - - String get allowedExtensions => '.dart'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - transform.addOutput(new Asset.fromString(transform.primaryInput.id, - contents.replaceAll("REPLACE ME", "hello!"))); - }); - } -} -"""; - -main() { - initConfig(); - integration("snapshots the transformed version of an executable", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - "barback": "any" - }, pubspec: { - 'transformers': ['foo'] - }, - contents: [ - d.dir("lib", [d.file("foo.dart", REPLACE_TRANSFORMER)]), - d.dir("bin", [d.file("hello.dart", """ -final message = 'REPLACE ME'; - -void main() => print(message); -"""),])]); - }); - - d.appDir({ - "foo": "1.2.3" - }).create(); - - pubGet(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin'), - [ - d.dir( - 'foo', - [d.matcherFile('hello.dart.snapshot', contains('hello!'))])]).validate(); - - var process = pubRun(args: ['foo:hello']); - process.stdout.expect("hello!"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/updates_snapshot_for_git_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/updates_snapshot_for_git_dependency_test.dart deleted file mode 100644 index b370c807e12..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/updates_snapshot_for_git_dependency_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades a snapshot when a git dependency is upgraded", () { - ensureGit(); - - d.git('foo.git', [d.pubspec({ - "name": "foo", - "version": "0.0.1" - }), - d.dir( - "bin", - [d.file("hello.dart", "void main() => print('Hello!');")])]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin', 'foo'), - [d.matcherFile('hello.dart.snapshot', contains('Hello!'))]).validate(); - - d.git( - 'foo.git', - [ - d.dir( - "bin", - [d.file("hello.dart", "void main() => print('Goodbye!');")])]).commit(); - - pubUpgrade(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin', 'foo'), - [d.matcherFile('hello.dart.snapshot', contains('Goodbye!'))]).validate(); - - var process = pubRun(args: ['foo:hello']); - process.stdout.expect("Goodbye!"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_for_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_for_dependency_test.dart deleted file mode 100644 index 0749c5e2565..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_for_dependency_test.dart +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades a snapshot when a dependency is upgraded", () { - servePackages((builder) { - builder.serve("foo", "1.2.3", pubspec: { - "dependencies": { - "bar": "any" - } - }, contents: [d.dir("bin", [d.file("hello.dart", """ -import 'package:bar/bar.dart'; - -void main() => print(message); -""")])]); - builder.serve( - "bar", - "1.2.3", - contents: [d.dir("lib", [d.file("bar.dart", "final message = 'hello!';")])]); - }); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin', 'foo'), - [d.matcherFile('hello.dart.snapshot', contains('hello!'))]).validate(); - - servePackages((builder) { - builder.serve( - "bar", - "1.2.4", - contents: [d.dir("lib", [d.file("bar.dart", "final message = 'hello 2!';")]),]); - }); - - pubUpgrade(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin', 'foo'), - [d.matcherFile('hello.dart.snapshot', contains('hello 2!'))]).validate(); - - var process = pubRun(args: ['foo:hello']); - process.stdout.expect("hello 2!"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_test.dart b/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_test.dart deleted file mode 100644 index bd8150f11b8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/snapshot/upgrades_snapshot_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:path/path.dart' as p; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades a snapshot when its package is upgraded", () { - servePackages((builder) { - builder.serve( - "foo", - "1.2.3", - contents: [ - d.dir("bin", [d.file("hello.dart", "void main() => print('hello!');")])]); - }); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin', 'foo'), - [d.matcherFile('hello.dart.snapshot', contains('hello!'))]).validate(); - - servePackages((builder) { - builder.serve( - "foo", - "1.2.4", - contents: [ - d.dir("bin", [d.file("hello.dart", "void main() => print('hello 2!');")])]); - }); - - pubUpgrade(output: contains("Precompiled foo:hello.")); - - d.dir( - p.join(appPath, '.pub', 'bin', 'foo'), - [d.matcherFile('hello.dart.snapshot', contains('hello 2!'))]).validate(); - - var process = pubRun(args: ['foo:hello']); - process.stdout.expect("hello 2!"); - process.shouldExit(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/test_pub.dart b/sdk/lib/_internal/pub_generated/test/test_pub.dart deleted file mode 100644 index 1fcc8d67aec..00000000000 --- a/sdk/lib/_internal/pub_generated/test/test_pub.dart +++ /dev/null @@ -1,1015 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// Test infrastructure for testing pub. -/// -/// Unlike typical unit tests, most pub tests are integration tests that stage -/// some stuff on the file system, run pub, and then validate the results. This -/// library provides an API to build tests like that. -library test_pub; - -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; -import 'dart:math'; - -import 'package:http/testing.dart'; -import 'package:path/path.dart' as p; -import 'package:pub_semver/pub_semver.dart'; -import 'package:scheduled_test/scheduled_process.dart'; -import 'package:scheduled_test/scheduled_server.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart' hide fail; -import 'package:shelf/shelf.dart' as shelf; -import 'package:shelf/shelf_io.dart' as shelf_io; -import 'package:unittest/compact_vm_config.dart'; -import 'package:yaml/yaml.dart'; - -import '../lib/src/entrypoint.dart'; -import '../lib/src/exit_codes.dart' as exit_codes; -// TODO(rnystrom): Using "gitlib" as the prefix here is ugly, but "git" collides -// with the git descriptor method. Maybe we should try to clean up the top level -// scope a bit? -import '../lib/src/git.dart' as gitlib; -import '../lib/src/http.dart'; -import '../lib/src/io.dart'; -import '../lib/src/lock_file.dart'; -import '../lib/src/log.dart' as log; -import '../lib/src/package.dart'; -import '../lib/src/pubspec.dart'; -import '../lib/src/source/hosted.dart'; -import '../lib/src/source/path.dart'; -import '../lib/src/source_registry.dart'; -import '../lib/src/system_cache.dart'; -import '../lib/src/utils.dart'; -import '../lib/src/validator.dart'; -import 'descriptor.dart' as d; -import 'serve_packages.dart'; - -export 'serve_packages.dart'; - -/// This should be called at the top of a test file to set up an appropriate -/// test configuration for the machine running the tests. -initConfig() { - useCompactVMConfiguration(); - filterStacks = true; - unittestConfiguration.timeout = null; -} - -/// The current [HttpServer] created using [serve]. -var _server; - -/// The list of paths that have been requested from the server since the last -/// call to [getRequestedPaths]. -final _requestedPaths = []; - -/// The cached value for [_portCompleter]. -Completer _portCompleterCache; - -/// A [Matcher] that matches JavaScript generated by dart2js with minification -/// enabled. -Matcher isMinifiedDart2JSOutput = - isNot(contains("// The code supports the following hooks")); - -/// A [Matcher] that matches JavaScript generated by dart2js with minification -/// disabled. -Matcher isUnminifiedDart2JSOutput = - contains("// The code supports the following hooks"); - -/// A map from package names to paths from which those packages should be loaded -/// for [createLockFile]. -/// -/// This allows older versions of dependencies than those that exist in the repo -/// to be used when testing pub. -Map _packageOverrides; - -/// A map from barback versions to the paths of directories in the repo -/// containing them. -/// -/// This includes the latest version of barback from pkg as well as all old -/// versions of barback in third_party. -final _barbackVersions = _findBarbackVersions(); - -/// Some older barback versions require older versions of barback's dependencies -/// than those that are in the repo. -/// -/// This is a map from barback version ranges to the dependencies for those -/// barback versions. Each dependency version listed here should be included in -/// third_party/pkg. -final _barbackDeps = { - new VersionConstraint.parse("<0.15.0"): { - "source_maps": "0.9.4" - } -}; - -/// Populates [_barbackVersions]. -Map _findBarbackVersions() { - var versions = {}; - var currentBarback = p.join(repoRoot, 'third_party', 'pkg', 'barback'); - versions[new Pubspec.load(currentBarback, new SourceRegistry()).version] = - currentBarback; - - for (var dir in listDir(p.join(repoRoot, 'third_party', 'pkg'))) { - var basename = p.basename(dir); - if (!basename.startsWith('barback-')) continue; - versions[new Version.parse(split1(basename, '-').last)] = dir; - } - - return versions; -} - -/// Runs the tests in [callback] against all versions of barback in the repo -/// that match [versionConstraint]. -/// -/// This is used to test that pub doesn't accidentally break older versions of -/// barback that it's committed to supporting. Only versions `0.13.0` and later -/// will be tested. -void withBarbackVersions(String versionConstraint, void callback()) { - var constraint = new VersionConstraint.parse(versionConstraint); - - var validVersions = _barbackVersions.keys.where(constraint.allows); - if (validVersions.isEmpty) { - throw new ArgumentError( - 'No available barback version matches "$versionConstraint".'); - } - - for (var version in validVersions) { - group("with barback $version", () { - setUp(() { - _packageOverrides = {}; - _packageOverrides['barback'] = _barbackVersions[version]; - _barbackDeps.forEach((constraint, deps) { - if (!constraint.allows(version)) return; - deps.forEach((packageName, version) { - _packageOverrides[packageName] = - p.join(repoRoot, 'third_party', 'pkg', '$packageName-$version'); - }); - }); - - currentSchedule.onComplete.schedule(() { - _packageOverrides = null; - }); - }); - - callback(); - }); - } -} - -/// The completer for [port]. -Completer get _portCompleter { - if (_portCompleterCache != null) return _portCompleterCache; - _portCompleterCache = new Completer(); - currentSchedule.onComplete.schedule(() { - _portCompleterCache = null; - }, 'clearing the port completer'); - return _portCompleterCache; -} - -/// A future that will complete to the port used for the current server. -Future get port => _portCompleter.future; - -/// Gets the list of paths that have been requested from the server since the -/// last time this was called (or since the server was first spun up). -Future> getRequestedPaths() { - return schedule(() { - var paths = _requestedPaths.toList(); - _requestedPaths.clear(); - return paths; - }, "get previous network requests"); -} - -/// Creates an HTTP server to serve [contents] as static files. -/// -/// This server will exist only for the duration of the pub run. Subsequent -/// calls to [serve] replace the previous server. -void serve([List contents]) { - var baseDir = d.dir("serve-dir", contents); - - _hasServer = true; - - schedule(() { - return _closeServer().then((_) { - return shelf_io.serve((request) { - currentSchedule.heartbeat(); - var path = p.posix.fromUri(request.url.path.replaceFirst("/", "")); - _requestedPaths.add(path); - - return validateStream( - baseDir.load( - path)).then((stream) => new shelf.Response.ok(stream)).catchError((error) { - return new shelf.Response.notFound('File "$path" not found.'); - }); - }, 'localhost', 0).then((server) { - _server = server; - _portCompleter.complete(_server.port); - currentSchedule.onComplete.schedule(_closeServer); - }); - }); - }, 'starting a server serving:\n${baseDir.describe()}'); -} - -/// Closes [_server]. -/// -/// Returns a [Future] that completes after the [_server] is closed. -Future _closeServer() { - if (_server == null) return new Future.value(); - var future = _server.close(); - _server = null; - _hasServer = false; - _portCompleterCache = null; - return future; -} - -/// `true` if the current test spins up an HTTP server. -bool _hasServer = false; - -/// Converts [value] into a YAML string. -String yaml(value) => JSON.encode(value); - -/// The full path to the created sandbox directory for an integration test. -String get sandboxDir => _sandboxDir; -String _sandboxDir; - -/// The path of the package cache directory used for tests, relative to the -/// sandbox directory. -final String cachePath = "cache"; - -/// The path of the mock app directory used for tests, relative to the sandbox -/// directory. -final String appPath = "myapp"; - -/// The path of the packages directory in the mock app used for tests, relative -/// to the sandbox directory. -final String packagesPath = "$appPath/packages"; - -/// Set to true when the current batch of scheduled events should be aborted. -bool _abortScheduled = false; - -/// Enum identifying a pub command that can be run with a well-defined success -/// output. -class RunCommand { - static final get = new RunCommand( - 'get', - new RegExp(r'Got dependencies!|Changed \d+ dependenc(y|ies)!')); - static final upgrade = new RunCommand( - 'upgrade', - new RegExp(r'(No dependencies changed\.|Changed \d+ dependenc(y|ies)!)$')); - static final downgrade = new RunCommand( - 'downgrade', - new RegExp(r'(No dependencies changed\.|Changed \d+ dependenc(y|ies)!)$')); - - final String name; - final RegExp success; - RunCommand(this.name, this.success); -} - -/// Runs the tests defined within [callback] using both pub get and pub upgrade. -/// -/// Many tests validate behavior that is the same between pub get and -/// upgrade have the same behavior. Instead of duplicating those tests, this -/// takes a callback that defines get/upgrade agnostic tests and runs them -/// with both commands. -void forBothPubGetAndUpgrade(void callback(RunCommand command)) { - group(RunCommand.get.name, () => callback(RunCommand.get)); - group(RunCommand.upgrade.name, () => callback(RunCommand.upgrade)); -} - -/// Schedules an invocation of pub [command] and validates that it completes -/// in an expected way. -/// -/// By default, this validates that the command completes successfully and -/// understands the normal output of a successful pub command. If [warning] is -/// given, it expects the command to complete successfully *and* print -/// [warning] to stderr. If [error] is given, it expects the command to *only* -/// print [error] to stderr. [output], [error], and [warning] may be strings, -/// [RegExp]s, or [Matcher]s. -/// -/// If [exitCode] is given, expects the command to exit with that code. -// TODO(rnystrom): Clean up other tests to call this when possible. -void pubCommand(RunCommand command, {Iterable args, output, error, - warning, int exitCode}) { - if (error != null && warning != null) { - throw new ArgumentError("Cannot pass both 'error' and 'warning'."); - } - - var allArgs = [command.name]; - if (args != null) allArgs.addAll(args); - - if (output == null) output = command.success; - - if (error != null && exitCode == null) exitCode = 1; - - // No success output on an error. - if (error != null) output = null; - if (warning != null) error = warning; - - schedulePub(args: allArgs, output: output, error: error, exitCode: exitCode); -} - -void pubGet({Iterable args, output, error, warning, int exitCode}) { - pubCommand( - RunCommand.get, - args: args, - output: output, - error: error, - warning: warning, - exitCode: exitCode); -} - -void pubUpgrade({Iterable args, output, error, warning, int exitCode}) { - pubCommand( - RunCommand.upgrade, - args: args, - output: output, - error: error, - warning: warning, - exitCode: exitCode); -} - -void pubDowngrade({Iterable args, output, error, warning, int exitCode}) - { - pubCommand( - RunCommand.downgrade, - args: args, - output: output, - error: error, - warning: warning, - exitCode: exitCode); -} - -/// Schedules starting the "pub [global] run" process and validates the -/// expected startup output. -/// -/// If [global] is `true`, this invokes "pub global run", otherwise it does -/// "pub run". -/// -/// Returns the `pub run` process. -ScheduledProcess pubRun({bool global: false, Iterable args}) { - var pubArgs = global ? ["global", "run"] : ["run"]; - pubArgs.addAll(args); - var pub = startPub(args: pubArgs); - - // Loading sources and transformers isn't normally printed, but the pub test - // infrastructure runs pub in verbose mode, which enables this. - pub.stdout.expect(consumeWhile(startsWith("Loading"))); - - return pub; -} - -/// Defines an integration test. -/// -/// The [body] should schedule a series of operations which will be run -/// asynchronously. -void integration(String description, void body()) => - _integration(description, body, test); - -/// Like [integration], but causes only this test to run. -void solo_integration(String description, void body()) => - _integration(description, body, solo_test); - -void _integration(String description, void body(), [Function testFn]) { - testFn(description, () { - // TODO(nweiz): remove this when issue 15362 is fixed. - currentSchedule.timeout *= 2; - - // The windows bots are very slow, so we increase the default timeout. - if (Platform.operatingSystem == "windows") { - currentSchedule.timeout *= 2; - } - - _sandboxDir = createSystemTempDir(); - d.defaultRoot = sandboxDir; - currentSchedule.onComplete.schedule( - () => deleteEntry(_sandboxDir), - 'deleting the sandbox directory'); - - // Schedule the test. - body(); - }); -} - -/// Get the path to the root "pub/test" directory containing the pub -/// tests. -String get testDirectory => p.absolute(p.dirname(libraryPath('test_pub'))); - -/// Schedules renaming (moving) the directory at [from] to [to], both of which -/// are assumed to be relative to [sandboxDir]. -void scheduleRename(String from, String to) { - schedule( - () => renameDir(p.join(sandboxDir, from), p.join(sandboxDir, to)), - 'renaming $from to $to'); -} - -/// Schedules creating a symlink at path [symlink] that points to [target], -/// both of which are assumed to be relative to [sandboxDir]. -void scheduleSymlink(String target, String symlink) { - schedule( - () => createSymlink(p.join(sandboxDir, target), p.join(sandboxDir, symlink)), - 'symlinking $target to $symlink'); -} - -/// Schedules a call to the Pub command-line utility. -/// -/// Runs Pub with [args] and validates that its results match [output] (or -/// [outputJson]), [error], and [exitCode]. -/// -/// [output] and [error] can be [String]s, [RegExp]s, or [Matcher]s. -/// -/// If [outputJson] is given, validates that pub outputs stringified JSON -/// matching that object, which can be a literal JSON object or any other -/// [Matcher]. -/// -/// If [environment] is given, any keys in it will override the environment -/// variables passed to the spawned process. -void schedulePub({List args, output, error, outputJson, int exitCode: - exit_codes.SUCCESS, Map environment}) { - // Cannot pass both output and outputJson. - assert(output == null || outputJson == null); - - var pub = startPub(args: args, environment: environment); - pub.shouldExit(exitCode); - - var failures = []; - var stderr; - - expect( - Future.wait( - [pub.stdoutStream().toList(), pub.stderrStream().toList()]).then((results) { - var stdout = results[0].join("\n"); - stderr = results[1].join("\n"); - - if (outputJson == null) { - _validateOutput(failures, 'stdout', output, stdout); - return null; - } - - // Allow the expected JSON to contain futures. - return awaitObject(outputJson).then((resolved) { - _validateOutputJson(failures, 'stdout', resolved, stdout); - }); - }).then((_) { - _validateOutput(failures, 'stderr', error, stderr); - - if (!failures.isEmpty) throw new TestFailure(failures.join('\n')); - }), completes); -} - -/// Like [startPub], but runs `pub lish` in particular with [server] used both -/// as the OAuth2 server (with "/token" as the token endpoint) and as the -/// package server. -/// -/// Any futures in [args] will be resolved before the process is started. -ScheduledProcess startPublish(ScheduledServer server, {List args}) { - var tokenEndpoint = - server.url.then((url) => url.resolve('/token').toString()); - if (args == null) args = []; - args = flatten(['lish', '--server', tokenEndpoint, args]); - return startPub(args: args, tokenEndpoint: tokenEndpoint); -} - -/// Handles the beginning confirmation process for uploading a packages. -/// -/// Ensures that the right output is shown and then enters "y" to confirm the -/// upload. -void confirmPublish(ScheduledProcess pub) { - // TODO(rnystrom): This is overly specific and inflexible regarding different - // test packages. Should validate this a little more loosely. - pub.stdout.expect(startsWith('Publishing test_pkg 1.0.0 to ')); - pub.stdout.expect( - emitsLines( - "|-- LICENSE\n" "|-- lib\n" "| '-- test_pkg.dart\n" "'-- pubspec.yaml\n" "\n" - "Looks great! Are you ready to upload your package (y/n)?")); - pub.writeLine("y"); -} - -/// Gets the absolute path to [relPath], which is a relative path in the test -/// sandbox. -String _pathInSandbox(String relPath) { - return p.join(p.absolute(sandboxDir), relPath); -} - -/// Gets the environment variables used to run pub in a test context. -Future getPubTestEnvironment([String tokenEndpoint]) { - final completer0 = new Completer(); - scheduleMicrotask(() { - try { - var environment = {}; - environment['_PUB_TESTING'] = 'true'; - environment['PUB_CACHE'] = _pathInSandbox(cachePath); - environment['_PUB_TEST_SDK_VERSION'] = "0.1.2+3"; - join0() { - join1() { - completer0.complete(environment); - } - if (_hasServer) { - completer0.complete(port.then(((p) { - environment['PUB_HOSTED_URL'] = "http://localhost:$p"; - return environment; - }))); - } else { - join1(); - } - } - if (tokenEndpoint != null) { - environment['_PUB_TEST_TOKEN_ENDPOINT'] = tokenEndpoint.toString(); - join0(); - } else { - join0(); - } - } catch (e, s) { - completer0.completeError(e, s); - } - }); - return completer0.future; -} - -/// Starts a Pub process and returns a [ScheduledProcess] that supports -/// interaction with that process. -/// -/// Any futures in [args] will be resolved before the process is started. -/// -/// If [environment] is given, any keys in it will override the environment -/// variables passed to the spawned process. -ScheduledProcess startPub({List args, Future tokenEndpoint, Map environment}) { - ensureDir(_pathInSandbox(appPath)); - - // Find a Dart executable we can use to spawn. Use the same one that was - // used to run this script itself. - var dartBin = Platform.executable; - - // If the executable looks like a path, get its full path. That way we - // can still find it when we spawn it with a different working directory. - if (dartBin.contains(Platform.pathSeparator)) { - dartBin = p.absolute(dartBin); - } - - // Always run pub from a snapshot. Since we require the SDK to be built, the - // snapshot should be there. Note that this *does* mean that the snapshot has - // to be manually updated when changing code before running the tests. - // Otherwise, you will test against stale data. - // - // Using the snapshot makes running the tests much faster, which is why we - // make this trade-off. - var pubPath = p.join(p.dirname(dartBin), 'snapshots/pub.dart.snapshot'); - var dartArgs = [pubPath, '--verbose']; - dartArgs.addAll(args); - - if (tokenEndpoint == null) tokenEndpoint = new Future.value(); - var environmentFuture = tokenEndpoint.then( - (tokenEndpoint) => getPubTestEnvironment(tokenEndpoint)).then((pubEnvironment) { - if (environment != null) pubEnvironment.addAll(environment); - return pubEnvironment; - }); - - return new PubProcess.start( - dartBin, - dartArgs, - environment: environmentFuture, - workingDirectory: _pathInSandbox(appPath), - description: args.isEmpty ? 'pub' : 'pub ${args.first}'); -} - -/// A subclass of [ScheduledProcess] that parses pub's verbose logging output -/// and makes [stdout] and [stderr] work as though pub weren't running in -/// verbose mode. -class PubProcess extends ScheduledProcess { - Stream> _log; - Stream _stdout; - Stream _stderr; - - PubProcess.start(executable, arguments, {workingDirectory, environment, - String description, Encoding encoding: UTF8}) - : super.start( - executable, - arguments, - workingDirectory: workingDirectory, - environment: environment, - description: description, - encoding: encoding); - - Stream> _logStream() { - if (_log == null) { - _log = mergeStreams( - _outputToLog(super.stdoutStream(), log.Level.MESSAGE), - _outputToLog(super.stderrStream(), log.Level.ERROR)); - } - - var pair = tee(_log); - _log = pair.first; - return pair.last; - } - - final _logLineRegExp = new RegExp(r"^([A-Z ]{4})[:|] (.*)$"); - final _logLevels = [ - log.Level.ERROR, - log.Level.WARNING, - log.Level.MESSAGE, - log.Level.IO, - log.Level.SOLVER, - log.Level.FINE].fold({}, (levels, level) { - levels[level.name] = level; - return levels; - }); - - Stream> _outputToLog(Stream stream, - log.Level defaultLevel) { - var lastLevel; - return stream.map((line) { - var match = _logLineRegExp.firstMatch(line); - if (match == null) return new Pair(defaultLevel, line); - - var level = _logLevels[match[1]]; - if (level == null) level = lastLevel; - lastLevel = level; - return new Pair(level, match[2]); - }); - } - - Stream stdoutStream() { - if (_stdout == null) { - _stdout = _logStream().expand((entry) { - if (entry.first != log.Level.MESSAGE) return []; - return [entry.last]; - }); - } - - var pair = tee(_stdout); - _stdout = pair.first; - return pair.last; - } - - Stream stderrStream() { - if (_stderr == null) { - _stderr = _logStream().expand((entry) { - if (entry.first != log.Level.ERROR && - entry.first != log.Level.WARNING) { - return []; - } - return [entry.last]; - }); - } - - var pair = tee(_stderr); - _stderr = pair.first; - return pair.last; - } -} - -/// The path to the `packages` directory from which pub loads its dependencies. -String get _packageRoot => p.absolute(Platform.packageRoot); - -/// Fails the current test if Git is not installed. -/// -/// We require machines running these tests to have git installed. This -/// validation gives an easier-to-understand error when that requirement isn't -/// met than just failing in the middle of a test when pub invokes git. -/// -/// This also increases the [Schedule] timeout to 30 seconds on Windows, -/// where Git runs really slowly. -void ensureGit() { - if (Platform.operatingSystem == "windows") { - currentSchedule.timeout = new Duration(seconds: 30); - } - - if (!gitlib.isInstalled) { - throw new Exception("Git must be installed to run this test."); - } -} - -/// Schedules activating a global package [package] without running -/// "pub global activate". -/// -/// This is useful because global packages must be hosted, but the test hosted -/// server doesn't serve barback. The other parameters here follow -/// [createLockFile]. -void makeGlobalPackage(String package, String version, - Iterable contents, {Iterable pkg, Map hosted}) { - // Start the server so we know what port to use in the cache directory name. - serveNoPackages(); - - // Create the package in the hosted cache. - d.hostedCache([d.dir("$package-$version", contents)]).create(); - - var lockFile = _createLockFile(pkg: pkg, hosted: hosted); - - // Add the root package to the lockfile. - var id = - new PackageId(package, "hosted", new Version.parse(version), package); - lockFile.packages[package] = id; - - // Write the lockfile to the global cache. - var sources = new SourceRegistry(); - sources.register(new HostedSource()); - sources.register(new PathSource()); - - d.dir( - cachePath, - [ - d.dir( - "global_packages", - [d.file("$package.lock", lockFile.serialize(null, sources))])]).create(); -} - -/// Creates a lock file for [package] without running `pub get`. -/// -/// [sandbox] is a list of path dependencies to be found in the sandbox -/// directory. [pkg] is a list of packages in the Dart repo's "pkg" directory; -/// each package listed here and all its dependencies will be linked to the -/// version in the Dart repo. -/// -/// [hosted] is a list of package names to version strings for dependencies on -/// hosted packages. -void createLockFile(String package, {Iterable sandbox, - Iterable pkg, Map hosted}) { - var lockFile = _createLockFile(sandbox: sandbox, pkg: pkg, hosted: hosted); - - var sources = new SourceRegistry(); - sources.register(new HostedSource()); - sources.register(new PathSource()); - - d.file( - p.join(package, 'pubspec.lock'), - lockFile.serialize(null, sources)).create(); -} - -/// Creates a lock file for [package] without running `pub get`. -/// -/// [sandbox] is a list of path dependencies to be found in the sandbox -/// directory. [pkg] is a list of packages in the Dart repo's "pkg" directory; -/// each package listed here and all its dependencies will be linked to the -/// version in the Dart repo. -/// -/// [hosted] is a list of package names to version strings for dependencies on -/// hosted packages. -LockFile _createLockFile({Iterable sandbox, Iterable pkg, - Map hosted}) { - var dependencies = {}; - - if (sandbox != null) { - for (var package in sandbox) { - dependencies[package] = '../$package'; - } - } - - if (pkg != null) { - _addPackage(String package) { - if (dependencies.containsKey(package)) return; - - var path; - if (package == 'barback' && _packageOverrides == null) { - throw new StateError( - "createLockFile() can only create a lock file " - "with a barback dependency within a withBarbackVersions() " "block."); - } - - if (_packageOverrides.containsKey(package)) { - path = _packageOverrides[package]; - } else { - path = packagePath(package); - } - - dependencies[package] = path; - var pubspec = loadYaml(readTextFile(p.join(path, 'pubspec.yaml'))); - var packageDeps = pubspec['dependencies']; - if (packageDeps == null) return; - packageDeps.keys.forEach(_addPackage); - } - - pkg.forEach(_addPackage); - } - - var lockFile = new LockFile.empty(); - dependencies.forEach((name, dependencyPath) { - var id = new PackageId(name, 'path', new Version(0, 0, 0), { - 'path': dependencyPath, - 'relative': p.isRelative(dependencyPath) - }); - lockFile.packages[name] = id; - }); - - if (hosted != null) { - hosted.forEach((name, version) { - var id = new PackageId(name, 'hosted', new Version.parse(version), name); - lockFile.packages[name] = id; - }); - } - - return lockFile; -} - -/// Returns the path to [package] within the repo. -String packagePath(String package) => - dirExists(p.join(repoRoot, 'pkg', package)) ? - p.join(repoRoot, 'pkg', package) : - p.join(repoRoot, 'third_party', 'pkg', package); - -/// Uses [client] as the mock HTTP client for this test. -/// -/// Note that this will only affect HTTP requests made via http.dart in the -/// parent process. -void useMockClient(MockClient client) { - var oldInnerClient = innerHttpClient; - innerHttpClient = client; - currentSchedule.onComplete.schedule(() { - innerHttpClient = oldInnerClient; - }, 'de-activating the mock client'); -} - -/// Describes a map representing a library package with the given [name], -/// [version], and [dependencies]. -Map packageMap(String name, String version, [Map dependencies]) { - var package = { - "name": name, - "version": version, - "author": "Natalie Weizenbaum ", - "homepage": "http://pub.dartlang.org", - "description": "A package, I guess." - }; - - if (dependencies != null) package["dependencies"] = dependencies; - - return package; -} - -/// Resolves [target] relative to the path to pub's `test/asset` directory. -String testAssetPath(String target) { - var libPath = libraryPath('test_pub'); - - // We are running from the generated directory, but non-dart assets are only - // in the canonical directory. - // TODO(rnystrom): Remove this when #104 is fixed. - libPath = libPath.replaceAll('pub_generated', 'pub'); - - return p.join(p.dirname(libPath), 'asset', target); -} - -/// Returns a Map in the format used by the pub.dartlang.org API to represent a -/// package version. -/// -/// [pubspec] is the parsed pubspec of the package version. If [full] is true, -/// this returns the complete map, including metadata that's only included when -/// requesting the package version directly. -Map packageVersionApiMap(Map pubspec, {bool full: false}) { - var name = pubspec['name']; - var version = pubspec['version']; - var map = { - 'pubspec': pubspec, - 'version': version, - 'url': '/api/packages/$name/versions/$version', - 'archive_url': '/packages/$name/versions/$version.tar.gz', - 'new_dartdoc_url': '/api/packages/$name/versions/$version' '/new_dartdoc', - 'package_url': '/api/packages/$name' - }; - - if (full) { - map.addAll({ - 'downloads': 0, - 'created': '2012-09-25T18:38:28.685260', - 'libraries': ['$name.dart'], - 'uploader': ['nweiz@google.com'] - }); - } - - return map; -} - -/// Returns the name of the shell script for a binstub named [name]. -/// -/// Adds a ".bat" extension on Windows. -String binStubName(String name) => Platform.isWindows ? '$name.bat' : name; - -/// Compares the [actual] output from running pub with [expected]. -/// -/// If [expected] is a [String], ignores leading and trailing whitespace -/// differences and tries to report the offending difference in a nice way. -/// -/// If it's a [RegExp] or [Matcher], just reports whether the output matches. -void _validateOutput(List failures, String pipe, expected, - String actual) { - if (expected == null) return; - - if (expected is String) { - _validateOutputString(failures, pipe, expected, actual); - } else { - if (expected is RegExp) expected = matches(expected); - expect(actual, expected); - } -} - -void _validateOutputString(List failures, String pipe, String expected, - String actual) { - var actualLines = actual.split("\n"); - var expectedLines = expected.split("\n"); - - // Strip off the last line. This lets us have expected multiline strings - // where the closing ''' is on its own line. It also fixes '' expected output - // to expect zero lines of output, not a single empty line. - if (expectedLines.last.trim() == '') { - expectedLines.removeLast(); - } - - var results = []; - var failed = false; - - // Compare them line by line to see which ones match. - var length = max(expectedLines.length, actualLines.length); - for (var i = 0; i < length; i++) { - if (i >= actualLines.length) { - // Missing output. - failed = true; - results.add('? ${expectedLines[i]}'); - } else if (i >= expectedLines.length) { - // Unexpected extra output. - failed = true; - results.add('X ${actualLines[i]}'); - } else { - var expectedLine = expectedLines[i].trim(); - var actualLine = actualLines[i].trim(); - - if (expectedLine != actualLine) { - // Mismatched lines. - failed = true; - results.add('X ${actualLines[i]}'); - } else { - // Output is OK, but include it in case other lines are wrong. - results.add('| ${actualLines[i]}'); - } - } - } - - // If any lines mismatched, show the expected and actual. - if (failed) { - failures.add('Expected $pipe:'); - failures.addAll(expectedLines.map((line) => '| $line')); - failures.add('Got:'); - failures.addAll(results); - } -} - -/// Validates that [actualText] is a string of JSON that matches [expected], -/// which may be a literal JSON object, or any other [Matcher]. -void _validateOutputJson(List failures, String pipe, expected, - String actualText) { - var actual; - try { - actual = JSON.decode(actualText); - } on FormatException catch (error) { - failures.add('Expected $pipe JSON:'); - failures.add(expected); - failures.add('Got invalid JSON:'); - failures.add(actualText); - } - - // Match against the expectation. - expect(actual, expected); -} - -/// A function that creates a [Validator] subclass. -typedef Validator ValidatorCreator(Entrypoint entrypoint); - -/// Schedules a single [Validator] to run on the [appPath]. -/// -/// Returns a scheduled Future that contains the errors and warnings produced -/// by that validator. -Future, List>> - schedulePackageValidation(ValidatorCreator fn) { - return schedule(() { - var cache = - new SystemCache.withSources(rootDir: p.join(sandboxDir, cachePath)); - - return new Future.sync(() { - var validator = fn(new Entrypoint(p.join(sandboxDir, appPath), cache)); - return validator.validate().then((_) { - return new Pair(validator.errors, validator.warnings); - }); - }); - }, "validating package"); -} - -/// A matcher that matches a Pair. -Matcher pairOf(Matcher firstMatcher, Matcher lastMatcher) => - new _PairMatcher(firstMatcher, lastMatcher); - -class _PairMatcher extends Matcher { - final Matcher _firstMatcher; - final Matcher _lastMatcher; - - _PairMatcher(this._firstMatcher, this._lastMatcher); - - bool matches(item, Map matchState) { - if (item is! Pair) return false; - return _firstMatcher.matches(item.first, matchState) && - _lastMatcher.matches(item.last, matchState); - } - - Description describe(Description description) { - return description.addAll("(", ", ", ")", [_firstMatcher, _lastMatcher]); - } -} - -/// A [StreamMatcher] that matches multiple lines of output. -StreamMatcher emitsLines(String output) => inOrder(output.split("\n")); diff --git a/sdk/lib/_internal/pub_generated/test/transcript_test.dart b/sdk/lib/_internal/pub_generated/test/transcript_test.dart deleted file mode 100644 index 34ea1303a00..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transcript_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library version_test; - -import 'package:unittest/unittest.dart'; -import 'test_pub.dart'; -import '../lib/src/transcript.dart'; - -main() { - initConfig(); - - test("discards from the middle once it reaches the maximum", () { - var transcript = new Transcript(4); - forEachToString() { - var result = ""; - transcript.forEach((entry) => result += entry, (n) => result += "[$n]"); - return result; - } - - expect(forEachToString(), equals("")); - transcript.add("a"); - expect(forEachToString(), equals("a")); - transcript.add("b"); - expect(forEachToString(), equals("ab")); - transcript.add("c"); - expect(forEachToString(), equals("abc")); - transcript.add("d"); - expect(forEachToString(), equals("abcd")); - transcript.add("e"); - expect(forEachToString(), equals("ab[1]de")); - transcript.add("f"); - expect(forEachToString(), equals("ab[2]ef")); - }); - - test("does not discard if it doesn't reach the maximum", () { - var transcript = new Transcript(40); - forEachToString() { - var result = ""; - transcript.forEach((entry) => result += entry, (n) => result += "[$n]"); - return result; - } - - expect(forEachToString(), equals("")); - transcript.add("a"); - expect(forEachToString(), equals("a")); - transcript.add("b"); - expect(forEachToString(), equals("ab")); - transcript.add("c"); - expect(forEachToString(), equals("abc")); - transcript.add("d"); - expect(forEachToString(), equals("abcd")); - transcript.add("e"); - expect(forEachToString(), equals("abcde")); - transcript.add("f"); - expect(forEachToString(), equals("abcdef")); - }); - -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/a_transformer_rejects_its_config_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/a_transformer_rejects_its_config_test.dart deleted file mode 100644 index 0ee0f1f5016..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/a_transformer_rejects_its_config_test.dart +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const REJECT_CONFIG_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RejectConfigTransformer extends Transformer { - RejectConfigTransformer.asPlugin(BarbackSettings settings) { - throw "I hate these settings!"; - } - - Future isPrimary(_) => new Future.value(true); - Future apply(Transform transform) {} -} -"""; - -main() { - initConfig(); - - withBarbackVersions("any", () { - integration("a transformer can reject is configuration", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - 'foo': 'bar' - } - }] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [d.file("transformer.dart", REJECT_CONFIG_TRANSFORMER)])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = startPubServe(); - pub.stderr.expect( - endsWith('Error loading transformer: I hate these ' 'settings!')); - pub.shouldExit(1); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/asset_not_found_exceptions_are_detectable_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/asset_not_found_exceptions_are_detectable_test.dart deleted file mode 100644 index 12e3816287f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/asset_not_found_exceptions_are_detectable_test.dart +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:convert'; - -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -final transformer = """ -import 'dart:async'; -import 'dart:convert'; - -import 'package:barback/barback.dart'; - -class GetInputTransformer extends Transformer { - GetInputTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.readInputAsString(new AssetId('myapp', 'nonexistent')) - .catchError((error) { - if (error is! AssetNotFoundException) throw error; - transform.addOutput(new Asset.fromString(transform.primaryInput.id, - JSON.encode({ - 'package': error.id.package, - 'path': error.id.path - }))); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("AssetNotFoundExceptions are detectable", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - requestShouldSucceed("foo.txt", JSON.encode({ - "package": "myapp", - "path": "nonexistent" - })); - endPubServe(); - - // Since the AssetNotFoundException was caught and handled, the server - // shouldn't print any error information for it. - server.stderr.expect(isDone); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/cache_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/cache_test.dart deleted file mode 100644 index fada25db129..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/cache_test.dart +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const REPLACE_FROM_LIBRARY_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:bar/bar.dart'; - -class ReplaceTransformer extends Transformer { - ReplaceTransformer.asPlugin(); - - String get allowedExtensions => '.dart'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - transform.addOutput(new Asset.fromString( - transform.primaryInput.id, - contents.replaceAll("Hello", replacement))); - }); - } -} -"""; - -// TODO(nweiz): Currently scheduled_test.setUp doesn't play well with test_pub, -// since it only assigns the sandbox directory once the main test body has -// run. Fix this and move this to a real setUp call. -void setUp() { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any' - }, - contents: [ - d.dir( - "lib", - [d.file("transformer.dart", replaceTransformer("Hello", "Goodbye"))])]); - - builder.serve("bar", "1.2.3", deps: { - 'barback': 'any' - }, - contents: [ - d.dir( - "lib", - [d.file("transformer.dart", replaceTransformer("Goodbye", "See ya"))])]); - - builder.serve("baz", "1.2.3"); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "1.2.3", - "bar": "1.2.3" - }, - "transformers": ["foo"] - }), - d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create(); - - pubGet(); -} - -main() { - initConfig(); - - integration("caches a transformer snapshot", () { - setUp(); - - var process = pubRun(args: ['myapp']); - process.stdout.expect("Goodbye!"); - process.shouldExit(); - - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [ - d.file("manifest.txt", "0.1.2+3\nfoo"), - d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate(); - - // Run the executable again to make sure loading the transformer from the - // cache works. - process = pubRun(args: ['myapp']); - process.stdout.expect("Goodbye!"); - process.shouldExit(); - }); - - integration("recaches if the SDK version is out-of-date", () { - setUp(); - - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [// The version 0.0.1 is different than the test version 0.1.2+3. - d.file("manifest.txt", "0.0.1\nfoo"), - d.file("transformers.snapshot", "junk")])]).create(); - - var process = pubRun(args: ['myapp']); - process.stdout.expect("Goodbye!"); - process.shouldExit(); - - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [ - d.file("manifest.txt", "0.1.2+3\nfoo"), - d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate(); - }); - - integration("recaches if the transformers change", () { - setUp(); - - var process = pubRun(args: ['myapp']); - process.stdout.expect("Goodbye!"); - process.shouldExit(); - - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [ - d.file("manifest.txt", "0.1.2+3\nfoo"), - d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "1.2.3", - "bar": "1.2.3" - }, - "transformers": ["foo", "bar"] - }), - d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create(); - - process = pubRun(args: ['myapp']); - process.stdout.expect("See ya!"); - process.shouldExit(); - - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [ - d.file("manifest.txt", "0.1.2+3\nbar,foo"), - d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate(); - }); - - integration("recaches if the transformer version changes", () { - setUp(); - - var process = pubRun(args: ['myapp']); - process.stdout.expect("Goodbye!"); - process.shouldExit(); - - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [ - d.file("manifest.txt", "0.1.2+3\nfoo"), - d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate(); - - servePackages((builder) { - builder.serve("foo", "2.0.0", deps: { - 'barback': 'any' - }, - contents: [ - d.dir( - "lib", - [d.file("transformer.dart", replaceTransformer("Hello", "New"))])]); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "any" - }, - "transformers": ["foo"] - })]).create(); - - pubUpgrade(); - - process = pubRun(args: ['myapp']); - process.stdout.expect("New!"); - process.shouldExit(); - - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [ - d.file("manifest.txt", "0.1.2+3\nfoo"), - d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate(); - }); - - integration("recaches if a transitive dependency version changes", () { - servePackages((builder) { - builder.serveRepoPackage('barback'); - - builder.serve("foo", "1.2.3", deps: { - 'barback': 'any', - 'bar': 'any' - }, - contents: [ - d.dir("lib", [d.file("transformer.dart", REPLACE_FROM_LIBRARY_TRANSFORMER)])]); - - builder.serve( - "bar", - "1.2.3", - contents: [ - d.dir("lib", [d.file("bar.dart", "final replacement = 'Goodbye';")])]); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "1.2.3" - }, - "transformers": ["foo"] - }), - d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create(); - - pubGet(); - - var process = pubRun(args: ['myapp']); - process.stdout.expect("Goodbye!"); - process.shouldExit(); - - servePackages((builder) { - builder.serve( - "bar", - "2.0.0", - contents: [ - d.dir("lib", [d.file("bar.dart", "final replacement = 'See ya';")])]); - }); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "any" - }, - "transformers": ["foo"] - })]).create(); - - pubUpgrade(); - - process = pubRun(args: ['myapp']); - process.stdout.expect("See ya!"); - process.shouldExit(); - }); - - // Issue 21298. - integration("doesn't recache when a transformer is removed", () { - setUp(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "1.2.3", - "bar": "1.2.3" - }, - "transformers": ["foo", "bar"] - }), - d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create(); - - var process = pubRun(args: ['myapp']); - process.stdout.expect("See ya!"); - process.shouldExit(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": "1.2.3", - // Add a new dependency to trigger another "pub get". This works - // around issue 20498. - "baz": "1.2.3" - }, - "transformers": ["foo"] - }), - d.dir("bin", [d.file("myapp.dart", "main() => print('Hello!');")])]).create(); - - process = pubRun(args: ['myapp']); - process.stdout.expect( - "Your pubspec has changed, so we need to update your lockfile:"); - process.stdout.expect(consumeThrough("Goodbye!")); - process.shouldExit(); - - // "bar" should still be in the manifest, since there's no reason to - // recompile the cache. - d.dir( - appPath, - [ - d.dir( - ".pub/transformers", - [ - d.file("manifest.txt", "0.1.2+3\nbar,foo"), - d.matcherFile("transformers.snapshot", isNot(isEmpty))])]).validate(); - }); -} - -String replaceTransformer(String input, String output) { - return """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class ReplaceTransformer extends Transformer { - ReplaceTransformer.asPlugin(); - - String get allowedExtensions => '.dart'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - transform.addOutput(new Asset.fromString( - transform.primaryInput.id, - contents.replaceAll("$input", "$output"))); - }); - } -} -"""; -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_log_messages_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_log_messages_test.dart deleted file mode 100644 index ca37e51e423..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/can_log_messages_test.dart +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; -import 'package:scheduled_test/scheduled_stream.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -const SOURCE_MAPS_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:source_maps/source_maps.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - transform.logger.info('info!'); - transform.logger.warning('Warning!', - asset: transform.primaryInput.id.changeExtension('.foo')); - var sourceFile = new SourceFile.text( - 'http://fake.com/not_real.dart', - 'not a real\\ndart file'); - transform.logger.error('ERROR!', span: new FileSpan(sourceFile, 11)); - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, "\$contents.out")); - }); - } -} -"""; - -const SOURCE_SPAN_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:source_span/source_span.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - transform.logger.info('info!'); - transform.logger.warning('Warning!', - asset: transform.primaryInput.id.changeExtension('.foo')); - var sourceFile = new SourceFile('not a real\\ndart file', - url: 'http://fake.com/not_real.dart'); - transform.logger.error('ERROR!', span: sourceFile.span(11, 12)); - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, "\$contents.out")); - }); - } -} -"""; - -main() { - initConfig(); - // This intentionally tests barback 0.14.2 with both transformers, since it - // supports both types of span. - withBarbackVersions("<0.15.0", () => runTest(SOURCE_MAPS_TRANSFORMER)); - withBarbackVersions(">=0.14.2", () => runTest(SOURCE_SPAN_TRANSFORMER)); -} - -void runTest(String transformerText) { - integration("can log messages", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformerText)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = startPub(args: ["build"]); - pub.stdout.expect(startsWith("Loading source assets...")); - pub.stdout.expect(consumeWhile(matches("Loading .* transformers..."))); - pub.stdout.expect(startsWith("Building myapp...")); - - pub.stdout.expect(emitsLines(""" -[Rewrite on myapp|web/foo.txt]: -info!""")); - - pub.stderr.expect(emitsLines(""" -[Rewrite on myapp|web/foo.txt with input myapp|web/foo.foo]: -Warning! -[Rewrite on myapp|web/foo.txt]:""")); - - // The details of the analyzer's error message change pretty frequently, - // so instead of validating the entire line, just look for a couple of - // salient bits of information. - pub.stderr.expect(allOf([contains("2"), // The line number. - contains("1"), // The column number. - contains("http://fake.com/not_real.dart"), // The library. - contains("ERROR"), // That it's an error. - ])); - - // In barback >=0.15.0, the span will point to the location where the error - // occurred. - pub.stderr.expect(allow(inOrder(["d", "^"]))); - - pub.stderr.expect("Build failed."); - - pub.shouldExit(exit_codes.DATA); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_consume_primary_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_consume_primary_test.dart deleted file mode 100644 index 0bb8314e696..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_consume_primary_test.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - transform.consumePrimary(); - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - var asset = new Asset.fromString(id, "\$contents.out"); - transform.addOutput(asset); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("a transform can use consumePrimary", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - requestShould404("foo.txt"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_has_input_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_has_input_test.dart deleted file mode 100644 index 93f4a6e8dac..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_has_input_test.dart +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return Future.wait([ - transform.hasInput(transform.primaryInput.id), - transform.hasInput(new AssetId('hooble', 'whatsit')) - ]).then((results) { - var id = transform.primaryInput.id.changeExtension(".out"); - var asset = new Asset.fromString(id, - "primary: \${results[0]}, secondary: \${results[1]}"); - transform.addOutput(asset); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("a transform can use hasInput", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "primary: true, secondary: false"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_as_string_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_as_string_test.dart deleted file mode 100644 index 0e542018902..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_as_string_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.readInputAsString(transform.primaryInput.id) - .then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, "\$contents.out")); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("a transform can use readInputAsString", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_test.dart deleted file mode 100644 index e54fb6cc0e5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/can_use_read_input_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.readInput(transform.primaryInput.id).toList() - .then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - var asset = new Asset.fromString(id, "\$contents.out"); - transform.addOutput(asset); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("a transform can use readInputAsString", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "[[102, 111, 111]].out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/configuration/configuration_defaults_to_empty_map_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/configuration/configuration_defaults_to_empty_map_test.dart deleted file mode 100644 index 514676ede72..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/configuration/configuration_defaults_to_empty_map_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:convert'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -final transformer = """ -import 'dart:async'; -import 'dart:convert'; - -import 'package:barback/barback.dart'; - -class ConfigTransformer extends Transformer { - final BarbackSettings settings; - - ConfigTransformer.asPlugin(this.settings); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".json"); - transform.addOutput( - new Asset.fromString(id, JSON.encode(settings.configuration))); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("configuration defaults to an empty map", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - requestShouldSucceed("foo.json", JSON.encode({})); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/configuration/passes_configuration_to_a_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/configuration/passes_configuration_to_a_transformer_test.dart deleted file mode 100644 index 94da357e763..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/configuration/passes_configuration_to_a_transformer_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:convert'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -final transformer = """ -import 'dart:async'; -import 'dart:convert'; - -import 'package:barback/barback.dart'; - -class ConfigTransformer extends Transformer { - final BarbackSettings settings; - - ConfigTransformer.asPlugin(this.settings); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".json"); - transform.addOutput( - new Asset.fromString(id, JSON.encode(settings.configuration))); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("passes configuration to a transformer", () { - var configuration = { - "param": ["list", "of", "values"] - }; - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": configuration - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - requestShouldSucceed("foo.json", JSON.encode(configuration)); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/configuration/with_configuration_only_instantiates_configurable_transformers_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/configuration/with_configuration_only_instantiates_configurable_transformers_test.dart deleted file mode 100644 index db40874dd9e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/configuration/with_configuration_only_instantiates_configurable_transformers_test.dart +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'dart:convert'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -final transformer = """ -import 'dart:async'; -import 'dart:convert'; - -import 'package:barback/barback.dart'; - -class ConfigTransformer extends Transformer { - final BarbackSettings settings; - - ConfigTransformer.asPlugin(this.settings); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".json"); - transform.addOutput( - new Asset.fromString(id, JSON.encode(settings.configuration))); - }); - } -} - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".out"); - transform.addOutput(new Asset.fromString(id, "\$contents.out")); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration( - "with configuration, only instantiates configurable " "transformers", - () { - var configuration = { - "param": ["list", "of", "values"] - }; - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": configuration - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - requestShouldSucceed("foo.json", JSON.encode(configuration)); - requestShould404("foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/dart2js_transformer_before_another_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/dart2js_transformer_before_another_transformer_test.dart deleted file mode 100644 index 5be8957e929..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/dart2js_transformer_before_another_transformer_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -// Regression test for issue 21726. -main() { - initConfig(); - withBarbackVersions("any", () { - integration("runs a dart2js transformer before a local transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [r"$dart2js", "myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/does_not_run_a_transform_on_an_input_in_another_package_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/does_not_run_a_transform_on_an_input_in_another_package_test.dart deleted file mode 100644 index c1d9c7c8619..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/does_not_run_a_transform_on_an_input_in_another_package_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("does not run a transform on an input in another package", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "0.0.1", - "transformers": ["foo/transformer"] - }), - d.dir( - "lib", - [ - d.file("transformer.dart", REWRITE_TRANSFORMER), - d.file("foo.txt", "foo")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }), d.dir("lib", [d.file("bar.txt", "bar")])]).create(); - - createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']); - - pubServe(); - requestShould404("packages/myapp/bar.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_glob_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_glob_test.dart deleted file mode 100644 index 9bf91008911..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_glob_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows a glob to exclude", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$exclude": "**/foo.txt" - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShould404("foo.out"); - requestShouldSucceed("bar.out", "bar.out"); - requestShould404("sub/foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_list_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_list_test.dart deleted file mode 100644 index 0c2295a963a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_list_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("excludes a list of assets", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$exclude": ["web/foo.txt", "web/sub/foo.txt"] - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShould404("foo.out"); - requestShould404("sub/foo.out"); - requestShouldSucceed("bar.out", "bar.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_prefix_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_prefix_test.dart deleted file mode 100644 index 12bbfd2c308..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_prefix_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows a directory prefix to exclude", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$exclude": "web/sub" - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),]), - d.dir("subbub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - requestShouldSucceed("bar.out", "bar.out"); - requestShouldSucceed("subbub/foo.out", "foo.out"); - requestShould404("sub/foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_string_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_string_test.dart deleted file mode 100644 index a7d92c098ab..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/exclude_asset_string_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows a single string as the asset to exclude", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$exclude": "web/foo.txt" - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShould404("foo.out"); - requestShouldSucceed("sub/foo.out", "foo.out"); - requestShouldSucceed("bar.out", "bar.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_glob_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_glob_test.dart deleted file mode 100644 index 07a4702ac58..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_glob_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows a glob to include", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$include": "**/foo.txt" - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - requestShould404("bar.out"); - requestShouldSucceed("sub/foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_list_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_list_test.dart deleted file mode 100644 index eb2d29ca95d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_list_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("includes assets", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$include": ["web/foo.txt", "web/sub/foo.txt"] - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - requestShouldSucceed("sub/foo.out", "foo.out"); - requestShould404("bar.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_prefix_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_prefix_test.dart deleted file mode 100644 index 22f2c7e3d1e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_prefix_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows a directory prefix to include", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$include": "web/sub" - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),]), - d.dir("subbub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShould404("foo.out"); - requestShould404("bar.out"); - requestShouldSucceed("sub/foo.out", "foo.out"); - requestShould404("subbub/foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_string_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_string_test.dart deleted file mode 100644 index 761c017955f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/include_asset_string_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("allows a single string as the asset to include", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$include": "web/foo.txt" - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("foo.txt", "foo"), - d.file("bar.txt", "bar"), - d.dir("sub", [d.file("foo.txt", "foo"),])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - requestShould404("sub/foo.out"); - requestShould404("bar.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/includes_before_excludes_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/includes_before_excludes_test.dart deleted file mode 100644 index 6df3ca0d307..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/includes_before_excludes_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("applies includes before excludes if both are present", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - "\$include": ["web/a.txt", "web/b.txt"], - "\$exclude": "web/a.txt" - } - }] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir( - "web", - [ - d.file("a.txt", "a.txt"), - d.file("b.txt", "b.txt"), - d.file("c.txt", "c.txt")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShould404("a.out"); - requestShouldSucceed("b.out", "b.txt.out"); - requestShould404("c.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_aggregate_transformer_test.dart deleted file mode 100644 index 436aa6e8715..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_aggregate_transformer_test.dart +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -const AGGREGATE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; - -class ManyToOneTransformer extends AggregateTransformer { - ManyToOneTransformer.asPlugin(); - - String classifyPrimary(AssetId id) { - if (id.extension != '.txt') return null; - return p.url.dirname(id.path); - } - - Future apply(AggregateTransform transform) { - return transform.primaryInputs.toList().then((assets) { - assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path)); - return Future.wait(assets.map((asset) => asset.readAsString())); - }).then((contents) { - var id = new AssetId(transform.package, - p.url.join(transform.key, 'out.txt')); - transform.addOutput(new Asset.fromString(id, contents.join('\\n'))); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions(">=0.14.1", () { - integration("works on an aggregate transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp": { - "\$include": ["web/a.txt", "web/b.txt", "web/c.txt"], - "\$exclude": "web/a.txt" - } - }] - }), - d.dir("lib", [d.file("transformer.dart", AGGREGATE_TRANSFORMER),]), - d.dir( - "web", - [ - d.file("a.txt", "a"), - d.file("b.txt", "b"), - d.file("c.txt", "c"), - d.file("d.txt", "d")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("out.txt", "b\nc"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_dart2js_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_dart2js_test.dart deleted file mode 100644 index 31c7e2e30de..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_dart2js_test.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("works on the dart2js transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "\$dart2js": { - "\$include": ["web/a.dart", "web/b.dart"], - "\$exclude": "web/a.dart" - } - }] - }), - d.dir( - "web", - [ - d.file("a.dart", "void main() => print('hello');"), - d.file("b.dart", "void main() => print('hello');"), - d.file("c.dart", "void main() => print('hello');")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - // Dart2js should remain lazy. - server.stdout.expect("Build completed successfully"); - - requestShould404("a.dart.js"); - requestShouldSucceed("b.dart.js", isNot(isEmpty)); - server.stdout.expect( - consumeThrough( - emitsLines("[Info from Dart2JS]:\n" "Compiling myapp|web/b.dart..."))); - server.stdout.expect(consumeThrough("Build completed successfully")); - - requestShould404("c.dart.js"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_lazy_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_lazy_transformer_test.dart deleted file mode 100644 index 5fcdeea9add..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_lazy_transformer_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("works on a lazy transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp": { - "\$include": ["web/a.txt", "web/b.txt"], - "\$exclude": "web/a.txt" - } - }] - }), - d.dir("lib", [d.file("transformer.dart", LAZY_TRANSFORMER)]), - d.dir( - "web", - [d.file("a.txt", "a"), d.file("b.txt", "b"), d.file("c.txt", "c")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - // The transformer should remain lazy. - server.stdout.expect("Build completed successfully"); - - requestShould404("a.out"); - requestShouldSucceed("b.out", isNot(isEmpty)); - server.stdout.expect( - consumeThrough( - emitsLines("[Info from LazyRewrite]:\n" "Rewriting myapp|web/b.txt."))); - server.stdout.expect(consumeThrough("Build completed successfully")); - - requestShould404("c.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_transformer_group_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_transformer_group_test.dart deleted file mode 100644 index f4d6acbc571..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/exclusion/works_on_transformer_group_test.dart +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; -import '../../serve/utils.dart'; - -const GROUP = """ -import 'package:barback/barback.dart'; - -import 'transformer.dart'; - -class RewriteGroup implements TransformerGroup { - RewriteGroup.asPlugin(); - - Iterable get phases => [[new RewriteTransformer.asPlugin()]]; -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("works on a transformer group", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/group": { - "\$include": ["web/a.txt", "web/b.txt"], - "\$exclude": "web/a.txt" - } - }] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [ - d.file("transformer.dart", REWRITE_TRANSFORMER), - d.file("group.dart", GROUP)])]), - d.dir( - "web", - [ - d.file("a.txt", "a.txt"), - d.file("b.txt", "b.txt"), - d.file("c.txt", "c.txt")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShould404("a.out"); - requestShouldSucceed("b.out", "b.txt.out"); - requestShould404("c.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_file_that_defines_no_transforms_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_file_that_defines_no_transforms_test.dart deleted file mode 100644 index f4cddcb4e51..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_file_that_defines_no_transforms_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - - withBarbackVersions("any", () { - integration("fails to load a file that defines no transforms", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/transformer"] - }), - d.dir("lib", [d.file("transformer.dart", "library does_nothing;")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = startPubServe(); - pub.stderr.expect(startsWith('No transformers were defined in ')); - pub.stderr.expect(startsWith('required by myapp.')); - pub.shouldExit(1); - pub.stderr.expect(never(contains('This is an unexpected error'))); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_non_existent_transform_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_non_existent_transform_test.dart deleted file mode 100644 index 9388b094db8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_non_existent_transform_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("fails to load a non-existent transform", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/transform"] - })]).create(); - - var pub = startPubServe(); - pub.stderr.expect( - 'Transformer library "package:myapp/transform.dart" not found.'); - pub.shouldExit(1); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_pubspec_with_reserved_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_pubspec_with_reserved_transformer_test.dart deleted file mode 100644 index a9eebf3bdd2..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_pubspec_with_reserved_transformer_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - - withBarbackVersions("any", () { - integration("fails to load a pubspec with reserved transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["\$nonexistent"] - }), - d.dir( - "lib", - [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = startPubServe(); - pub.stderr.expect( - contains( - 'Invalid transformer config: Unsupported ' - 'built-in transformer \$nonexistent.')); - pub.shouldExit(exit_codes.DATA); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_from_a_non_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_from_a_non_dependency_test.dart deleted file mode 100644 index ba4ea1a1a8f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_from_a_non_dependency_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/exit_codes.dart' as exit_codes; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("fails to load a transform from a non-dependency", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["foo"] - })]).create(); - - var pub = startPubServe(); - pub.stderr.expect(contains('"foo" is not a dependency.')); - pub.shouldExit(exit_codes.DATA); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_a_syntax_error_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_a_syntax_error_test.dart deleted file mode 100644 index 4e5052c6473..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_a_syntax_error_test.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - - // A syntax error will cause the analyzer to fail to parse the transformer - // when attempting to rewrite its imports. - withBarbackVersions("any", () { - integration("fails to load a transform with a syntax error", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [d.dir("src", [d.file("transformer.dart", "syntax error")])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = startPubServe(); - pub.stderr.expect(contains("unexpected token 'syntax'")); - pub.shouldExit(1); - pub.stderr.expect(never(contains('This is an unexpected error'))); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_an_import_error_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_an_import_error_test.dart deleted file mode 100644 index 3f68f63bb3f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_a_transform_with_an_import_error_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - - // An import error will cause the isolate API to fail synchronously while - // loading the transformer. - withBarbackVersions("any", () { - integration("fails to load a transform with an import error", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [d.file("transformer.dart", "import 'does/not/exist.dart';")])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - var pub = startPubServe(); - pub.stderr.expect("Unhandled exception:"); - pub.stderr.expect( - startsWith("Uncaught Error: Load Error: Failure getting ")); - pub.shouldExit(1); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_an_unconfigurable_transformer_when_config_is_passed_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_an_unconfigurable_transformer_when_config_is_passed_test.dart deleted file mode 100644 index 7c20db7fd9b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/fails_to_load_an_unconfigurable_transformer_when_config_is_passed_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - - withBarbackVersions("any", () { - integration( - "fails to load an unconfigurable transformer when config is " "passed", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "myapp/src/transformer": { - 'foo': 'bar' - } - }] - }), - d.dir( - "lib", - [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var pub = startPubServe(); - pub.stderr.expect( - startsWith('No transformers that accept configuration ' 'were defined in ')); - pub.shouldExit(1); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_declaring_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_declaring_aggregate_transformer_test.dart deleted file mode 100644 index 07bc966a1b8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_declaring_aggregate_transformer_test.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const AGGREGATE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; - -class ManyToOneTransformer extends AggregateTransformer - implements DeclaringAggregateTransformer { - ManyToOneTransformer.asPlugin(); - - String classifyPrimary(AssetId id) { - if (id.extension != '.out') return null; - return p.url.dirname(id.path); - } - - Future apply(AggregateTransform transform) { - return transform.primaryInputs.toList().then((assets) { - assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path)); - return Future.wait(assets.map((asset) => asset.readAsString())); - }).then((contents) { - var id = new AssetId(transform.package, - p.url.join(transform.key, 'out.final')); - transform.addOutput(new Asset.fromString(id, contents.join('\\n'))); - }); - } - - void declareOutputs(DeclaringAggregateTransform transform) { - transform.declareOutput(new AssetId(transform.package, - p.url.join(transform.key, 'out.final'))); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions(">=0.14.1", () { - integration("loads a declaring aggregate transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/lazy", "myapp/aggregate"] - }), - d.dir( - "lib", - [ - d.file("lazy.dart", LAZY_TRANSFORMER), - d.file("aggregate.dart", AGGREGATE_TRANSFORMER),]), - d.dir("web", [d.file("foo.txt", "foo"), d.file("bar.txt", "bar")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - // The transformer should preserve laziness. - server.stdout.expect("Build completed successfully"); - - requestShouldSucceed("out.final", "bar.out\nfoo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_diamond_transformer_dependency_graph_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_diamond_transformer_dependency_graph_test.dart deleted file mode 100644 index 2a970fefc30..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_diamond_transformer_dependency_graph_test.dart +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("loads a diamond transformer dependency graph", () { - d.dir("top", [d.pubspec({ - "name": "top", - "version": "1.0.0" - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer('top')),])]).create(); - - d.dir("left", [d.pubspec({ - "name": "left", - "version": "1.0.0", - "transformers": ["top/transformer"], - "dependencies": { - "top": { - "path": "../top" - } - } - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer('left')),])]).create(); - - d.dir("right", [d.pubspec({ - "name": "right", - "version": "1.0.0", - "transformers": ["top/transformer"], - "dependencies": { - "top": { - "path": "../top" - } - } - }), - d.dir( - "lib", - [d.file("transformer.dart", dartTransformer('right')),])]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [ - "left/transformer", - "right/transformer", - "myapp/transformer"], - "dependencies": { - 'left': { - 'path': '../left' - }, - 'right': { - 'path': '../right' - }, - } - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer('myapp'))]), - d.dir("web", [d.file("main.dart", 'const TOKEN = "main.dart";')])]).create(); - - createLockFile( - 'myapp', - sandbox: ['top', 'left', 'right'], - pkg: ['barback']); - - pubServe(); - requestShouldSucceed( - "main.dart", - 'const TOKEN = "(((main.dart, (left, top)), (right, top)), ((myapp, ' - '(left, top)), (right, top)))";'); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_lazy_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_lazy_aggregate_transformer_test.dart deleted file mode 100644 index d377c443857..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_lazy_aggregate_transformer_test.dart +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const AGGREGATE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; - -class ManyToOneTransformer extends AggregateTransformer - implements LazyAggregateTransformer { - ManyToOneTransformer.asPlugin(); - - String classifyPrimary(AssetId id) { - if (id.extension != '.txt') return null; - return p.url.dirname(id.path); - } - - Future apply(AggregateTransform transform) { - return transform.primaryInputs.toList().then((assets) { - assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path)); - return Future.wait(assets.map((asset) => asset.readAsString())); - }).then((contents) { - var id = new AssetId(transform.package, - p.url.join(transform.key, 'out.txt')); - transform.addOutput(new Asset.fromString(id, contents.join('\\n'))); - }); - } - - void declareOutputs(DeclaringAggregateTransform transform) { - transform.declareOutput(new AssetId(transform.package, - p.url.join(transform.key, 'out.txt'))); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions(">=0.14.1", () { - integration("loads a lazy aggregate transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), - d.dir("lib", [d.file("transformer.dart", AGGREGATE_TRANSFORMER),]), - d.dir("web", [d.file("foo.txt", "foo"), d.file("bar.txt", "bar")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - // The transformer should preserve laziness. - server.stdout.expect("Build completed successfully"); - - requestShouldSucceed("out.txt", "bar\nfoo"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_transformer_defined_in_an_exported_library_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_a_transformer_defined_in_an_exported_library_test.dart deleted file mode 100644 index a4435926074..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/loads_a_transformer_defined_in_an_exported_library_test.dart +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("loads a transformer defined in an exported library", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file("myapp.dart", "export 'src/transformer.dart';"), - d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_an_aggregate_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_an_aggregate_transformer_test.dart deleted file mode 100644 index 6872b8d4368..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/loads_an_aggregate_transformer_test.dart +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const AGGREGATE_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; -import 'package:path/path.dart' as p; - -class ManyToOneTransformer extends AggregateTransformer { - ManyToOneTransformer.asPlugin(); - - String classifyPrimary(AssetId id) { - if (id.extension != '.txt') return null; - return p.url.dirname(id.path); - } - - Future apply(AggregateTransform transform) { - return transform.primaryInputs.toList().then((assets) { - assets.sort((asset1, asset2) => asset1.id.path.compareTo(asset2.id.path)); - return Future.wait(assets.map((asset) => asset.readAsString())); - }).then((contents) { - var id = new AssetId(transform.package, - p.url.join(transform.key, 'out.txt')); - transform.addOutput(new Asset.fromString(id, contents.join('\\n'))); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions(">=0.14.1", () { - integration("loads an aggregate transformer", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), - d.dir("lib", [d.file("transformer.dart", AGGREGATE_TRANSFORMER),]), - d.dir("web", [d.file("foo.txt", "foo"), d.file("bar.txt", "bar")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("out.txt", "bar\nfoo"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/loads_different_configurations_from_the_same_isolate_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/loads_different_configurations_from_the_same_isolate_test.dart deleted file mode 100644 index fc285095723..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/loads_different_configurations_from_the_same_isolate_test.dart +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("loads different configurations from the same isolate", () { - // If different configurations are loaded from different isolates, a - // transformer can end up being loaded twice. It's even possible for the - // second load to use code that's transformed by the first, which is - // really bad. This tests sets up such a scenario. - // - // The foo package has two self-transformers: foo/first and foo/second, - // loaded in that order. This means that *no instances of foo/first* - // should ever have their code transformed by foo/second. - // - // The myapp package also has a reference to foo/first. This reference has - // a different configuration than foo's, which means that if it's loaded - // in a separate isolate, it will be loaded after all of foo's - // transformers have run. This means that foo/first.dart will have been - // transformed by foo/first and foo/second, causing it to have different - // code than the previous instance. This tests asserts that that doesn't - // happen. - - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0", - "transformers": [{ - "foo/first": { - "addition": " in foo" - } - }, "foo/second"] - }), - d.dir( - "lib", - [ - d.file("first.dart", dartTransformer('foo/first')), - d.file("second.dart", dartTransformer('foo/second'))])]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [{ - "foo/first": { - "addition": " in myapp", - "\$include": "web/first.dart" - } - }, { - "foo/second": { - "\$include": "web/second.dart" - } - }], - "dependencies": { - 'foo': { - 'path': '../foo' - } - } - }), - d.dir("web", [// This is transformed by foo/first. It's used to see which - // transformers ran on foo/first. - d.file("first.dart", 'const TOKEN = "myapp/first";'), - // This is transformed by foo/second. It's used to see which - // transformers ran on foo/second. - d.file("second.dart", 'const TOKEN = "myapp/second";')])]).create(); - - createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']); - - pubServe(); - - // The version of foo/first used on myapp should have myapp's - // configuration and shouldn't be transformed by foo/second. - requestShouldSucceed( - "first.dart", - 'const TOKEN = "(myapp/first, foo/first in myapp)";'); - - // foo/second should be transformed by only foo/first. - requestShouldSucceed( - "second.dart", - 'const TOKEN = "(myapp/second, (foo/second, foo/first in foo))";'); - - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/multiple_transformers_reject_their_config_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/multiple_transformers_reject_their_config_test.dart deleted file mode 100644 index 6a87bcbe06d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/multiple_transformers_reject_their_config_test.dart +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_stream.dart'; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const REJECT_CONFIG_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RejectConfigTransformer extends Transformer { - RejectConfigTransformer.asPlugin(BarbackSettings settings) { - throw "I hate these settings!"; - } - - Future isPrimary(_) => new Future.value(true); - Future apply(Transform transform) {} -} -"""; - -main() { - initConfig(); - - withBarbackVersions("any", () { - integration( - "multiple transformers in the same phase reject their " "configurations", - () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": [[{ - "myapp/src/transformer": { - 'foo': 'bar' - } - }, { - "myapp/src/transformer": { - 'baz': 'bang' - } - }, { - "myapp/src/transformer": { - 'qux': 'fblthp' - } - }]] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [d.file("transformer.dart", REJECT_CONFIG_TRANSFORMER)])])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - // We should see three instances of the error message, once for each - // use of the transformer. - var pub = startPubServe(); - for (var i = 0; i < 3; i++) { - pub.stderr.expect( - consumeThrough( - endsWith('Error loading transformer: ' 'I hate these settings!'))); - } - pub.shouldExit(1); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/prefers_transformer_to_library_name_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/prefers_transformer_to_library_name_test.dart deleted file mode 100644 index 53b8132dba7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/prefers_transformer_to_library_name_test.dart +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const WRONG_TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) { - return transform.primaryInput.readAsString().then((contents) { - var id = transform.primaryInput.id.changeExtension(".wrong"); - transform.addOutput(new Asset.fromString(id, "\$contents.wrong")); - }); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("prefers transformer.dart to .dart", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp"] - }), - d.dir( - "lib", - [ - d.file("transformer.dart", REWRITE_TRANSFORMER), - d.file("myapp.dart", WRONG_TRANSFORMER)]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - requestShould404("foo.wrong"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_error_in_apply_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_error_in_apply_test.dart deleted file mode 100644 index af118726a75..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_error_in_apply_test.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -final transformer = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; - - Future apply(Transform transform) => throw new Exception('oh no!'); -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("prints a transform error in apply", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - server.stderr.expect( - emitsLines( - 'Build error:\n' 'Transform Rewrite on myapp|web/foo.txt threw error: oh no!')); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_interface_error_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_interface_error_test.dart deleted file mode 100644 index 4a661f6f51f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/prints_a_transform_interface_error_test.dart +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -final transformer = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer { - RewriteTransformer.asPlugin(); - - String get allowedExtensions => '.txt'; -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("prints a transform interface error", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", transformer)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - var server = pubServe(); - server.stderr.expect( - emitsLines( - "Build error:\n" "Transform Rewrite on myapp|web/foo.txt threw error: Class " - "'RewriteTransformer' has no instance method 'apply'.")); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_local_transform_on_the_application_package_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_local_transform_on_the_application_package_test.dart deleted file mode 100644 index 714d8fba04f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_local_transform_on_the_application_package_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("runs a local transform on the application package", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", REWRITE_TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transform_on_the_application_package_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transform_on_the_application_package_test.dart deleted file mode 100644 index 2dcc5eb6418..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transform_on_the_application_package_test.dart +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("runs a third-party transform on the application package", () { - d.dir( - "foo", - [ - d.libPubspec("foo", '1.0.0'), - d.dir("lib", [d.file("foo.dart", REWRITE_TRANSFORMER)])]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "foo": { - "path": "../foo" - } - }, - "transformers": ["foo"] - }), d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transformer_on_a_local_transformer_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transformer_on_a_local_transformer_test.dart deleted file mode 100644 index 0227502e7ef..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_third_party_transformer_on_a_local_transformer_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("runs a third-party transformer on a local transformer", () { - d.dir( - "foo", - [ - d.libPubspec("foo", '1.0.0'), - d.dir("lib", [d.file("transformer.dart", dartTransformer('foo'))])]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["foo/transformer", "myapp/transformer"], - "dependencies": { - "foo": { - "path": "../foo" - } - } - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer('myapp'))]), - d.dir("web", [d.file("main.dart", 'const TOKEN = "main.dart";')])]).create(); - - createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']); - - pubServe(); - requestShouldSucceed( - "main.dart", - 'const TOKEN = "((main.dart, foo), (myapp, foo))";'); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_group_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_group_test.dart deleted file mode 100644 index bdf881426fd..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_group_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const GROUP = """ -import 'package:barback/barback.dart'; - -import 'transformer.dart'; - -class RewriteGroup implements TransformerGroup { - RewriteGroup.asPlugin(); - - Iterable get phases => [[new RewriteTransformer.asPlugin()]]; -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("runs a transformer group", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/group"] - }), - d.dir( - "lib", - [ - d.dir( - "src", - [ - d.file("transformer.dart", REWRITE_TRANSFORMER), - d.file("group.dart", GROUP)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_on_a_dependency_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_on_a_dependency_test.dart deleted file mode 100644 index c19f18091ff..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/runs_a_transformer_on_a_dependency_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("runs a local transformer on a dependency", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "0.0.1", - "transformers": ["foo/transformer"] - }), - d.dir( - "lib", - [ - d.file("transformer.dart", REWRITE_TRANSFORMER), - d.file("foo.txt", "foo")])]).create(); - - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - }),]).create(); - - createLockFile('myapp', sandbox: ['foo'], pkg: ['barback']); - - pubServe(); - requestShouldSucceed("packages/foo/foo.out", "foo.out"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/runs_one_third_party_transformer_on_another_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/runs_one_third_party_transformer_on_another_test.dart deleted file mode 100644 index 3bc572279fc..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/runs_one_third_party_transformer_on_another_test.dart +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("runs one third-party transformer on another", () { - d.dir("foo", [d.pubspec({ - "name": "foo", - "version": "1.0.0" - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer('foo')),])]).create(); - - d.dir("bar", [d.pubspec({ - "name": "bar", - "version": "1.0.0", - "transformers": ["foo/transformer"], - "dependencies": { - "foo": { - "path": "../foo" - } - } - }), - d.dir("lib", [d.file("transformer.dart", dartTransformer('bar')),])]).create(); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["bar/transformer"], - "dependencies": { - 'bar': { - 'path': '../bar' - } - } - }), - d.dir("web", [d.file("main.dart", 'const TOKEN = "main.dart";')])]).create(); - - createLockFile('myapp', sandbox: ['foo', 'bar'], pkg: ['barback']); - - pubServe(); - requestShouldSucceed( - "main.dart", - 'const TOKEN = "(main.dart, (bar, foo))";'); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/transformer/supports_a_transformer_that_doesnt_return_futures_test.dart b/sdk/lib/_internal/pub_generated/test/transformer/supports_a_transformer_that_doesnt_return_futures_test.dart deleted file mode 100644 index 4c14c5b8c48..00000000000 --- a/sdk/lib/_internal/pub_generated/test/transformer/supports_a_transformer_that_doesnt_return_futures_test.dart +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import '../serve/utils.dart'; - -const TRANSFORMER = """ -import 'dart:async'; - -import 'package:barback/barback.dart'; - -class RewriteTransformer extends Transformer implements DeclaringTransformer { - RewriteTransformer.asPlugin(); - - bool isPrimary(AssetId id) => id.extension == '.txt'; - - void apply(Transform transform) { - transform.addOutput(new Asset.fromString( - transform.primaryInput.id, "new contents")); - } - - void declareOutputs(DeclaringTransform transform) { - transform.declareOutput(transform.primaryId); - } -} -"""; - -main() { - initConfig(); - withBarbackVersions("any", () { - integration("supports a transformer that doesn't return futures", () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "transformers": ["myapp/src/transformer"] - }), - d.dir("lib", [d.dir("src", [d.file("transformer.dart", TRANSFORMER)])]), - d.dir("web", [d.file("foo.txt", "foo")])]).create(); - - createLockFile('myapp', pkg: ['barback']); - - pubServe(); - requestShouldSucceed("foo.txt", "new contents"); - endPubServe(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/unknown_source_test.dart b/sdk/lib/_internal/pub_generated/test/unknown_source_test.dart deleted file mode 100644 index e760a66a497..00000000000 --- a/sdk/lib/_internal/pub_generated/test/unknown_source_test.dart +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS d.file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE d.file. - -library pub_tests; - -import 'dart:convert'; - -import 'descriptor.dart' as d; -import 'test_pub.dart'; - -main() { - initConfig(); - - forBothPubGetAndUpgrade((command) { - integration('fails gracefully on a dependency from an unknown source', () { - d.appDir({ - "foo": { - "bad": "foo" - } - }).create(); - - pubCommand( - command, - error: 'Package myapp depends on foo from unknown source "bad".'); - }); - - integration( - 'fails gracefully on transitive dependency from an unknown ' 'source', - () { - d.dir( - 'foo', - [d.libDir('foo', 'foo 0.0.1'), d.libPubspec('foo', '0.0.1', deps: { - "bar": { - "bad": "bar" - } - })]).create(); - - d.appDir({ - "foo": { - "path": "../foo" - } - }).create(); - - pubCommand( - command, - error: 'Package foo depends on bar from unknown source "bad".'); - }); - - integration('ignores unknown source in lockfile', () { - d.dir('foo', [d.libDir('foo'), d.libPubspec('foo', '0.0.1')]).create(); - - // Depend on "foo" from a valid source. - d.dir(appPath, [d.appPubspec({ - "foo": { - "path": "../foo" - } - })]).create(); - - // But lock it to a bad one. - d.dir(appPath, [d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'foo': { - 'version': '0.0.0', - 'source': 'bad', - 'description': { - 'name': 'foo' - } - } - } - }))]).create(); - - pubCommand(command); - - // Should upgrade to the new one. - d.dir( - packagesPath, - [d.dir("foo", [d.file("foo.dart", 'main() => "foo";')])]).validate(); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/dry_run_does_not_apply_changes_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/dry_run_does_not_apply_changes_test.dart deleted file mode 100644 index fe9ce8b7a14..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/dry_run_does_not_apply_changes_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/io.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; - -main() { - initConfig(); - integration("--dry-run shows report but does not apply changes", () { - servePackages((builder) { - builder.serve("foo", "1.0.0"); - builder.serve("foo", "2.0.0"); - }); - - // Create the first lockfile. - d.appDir({ - "foo": "1.0.0" - }).create(); - - pubGet(); - - // Change the pubspec. - d.appDir({ - "foo": "any" - }).create(); - - // Also delete the "packages" directory. - schedule(() { - deleteEntry(path.join(sandboxDir, appPath, "packages")); - }); - - // Do the dry run. - pubUpgrade( - args: ["--dry-run"], - output: allOf( - [contains("> foo 2.0.0 (was 1.0.0)"), contains("Would change 1 dependency.")])); - - d.dir(appPath, [// The lockfile should be unmodified. - d.matcherFile("pubspec.lock", contains("1.0.0")), - // The "packages" directory should not have been regenerated. - d.nothing("packages")]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/do_not_upgrade_if_unneeded_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/do_not_upgrade_if_unneeded_test.dart deleted file mode 100644 index 458717fb453..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/git/do_not_upgrade_if_unneeded_test.dart +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "doesn't upgrade one locked Git package's dependencies if it's " - "not necessary", - () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec("foo", "1.0.0", deps: { - "foo-dep": { - "git": "../foo-dep.git" - } - })]).create(); - - d.git( - 'foo-dep.git', - [d.libDir('foo-dep'), d.libPubspec('foo-dep', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]), - d.dir('foo-dep', [d.file('foo-dep.dart', 'main() => "foo-dep";')])]).validate(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec("foo", "1.0.0", deps: { - "foo-dep": { - "git": "../foo-dep.git" - } - })]).create(); - - d.git( - 'foo-dep.git', - [d.libDir('foo-dep', 'foo-dep 2'), d.libPubspec('foo-dep', '1.0.0')]).commit(); - - pubUpgrade(args: ['foo']); - - d.dir( - packagesPath, - [ - d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')]), - d.dir( - 'foo-dep', - [d.file('foo-dep.dart', 'main() => "foo-dep";')]),]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_locked_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_locked_test.dart deleted file mode 100644 index e047cfbbca5..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_locked_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades locked Git packages", () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.git('bar.git', [d.libDir('bar'), d.libPubspec('bar', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - }, - "bar": { - "git": "../bar.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]), - d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - d.git( - 'bar.git', - [d.libDir('bar', 'bar 2'), d.libPubspec('bar', '1.0.0')]).commit(); - - pubUpgrade(); - - d.dir( - packagesPath, - [ - d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')]), - d.dir('bar', [d.file('bar.dart', 'main() => "bar 2";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_one_locked_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_one_locked_test.dart deleted file mode 100644 index a9e78efcd43..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_one_locked_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades one locked Git package but no others", () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.git('bar.git', [d.libDir('bar'), d.libPubspec('bar', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - }, - "bar": { - "git": "../bar.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [ - d.dir('foo', [d.file('foo.dart', 'main() => "foo";')]), - d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate(); - - d.git( - 'foo.git', - [d.libDir('foo', 'foo 2'), d.libPubspec('foo', '1.0.0')]).commit(); - - d.git( - 'bar.git', - [d.libDir('bar', 'bar 2'), d.libPubspec('bar', '1.0.0')]).commit(); - - pubUpgrade(args: ['foo']); - - d.dir( - packagesPath, - [ - d.dir('foo', [d.file('foo.dart', 'main() => "foo 2";')]), - d.dir('bar', [d.file('bar.dart', 'main() => "bar";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_incompatible_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_incompatible_pubspec_test.dart deleted file mode 100644 index 0d48281896a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_incompatible_pubspec_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../../lib/src/exit_codes.dart' as exit_codes; -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades Git packages to an incompatible pubspec", () { - ensureGit(); - - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]).create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - d.git('foo.git', [d.libDir('zoo'), d.libPubspec('zoo', '1.0.0')]).commit(); - - pubUpgrade( - error: contains('"name" field doesn\'t match expected name ' '"foo".'), - exitCode: exit_codes.DATA); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_nonexistent_pubspec_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_nonexistent_pubspec_test.dart deleted file mode 100644 index 0a747570aee..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/git/upgrade_to_nonexistent_pubspec_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades Git packages to a nonexistent pubspec", () { - ensureGit(); - - var repo = - d.git('foo.git', [d.libDir('foo'), d.libPubspec('foo', '1.0.0')]); - repo.create(); - - d.appDir({ - "foo": { - "git": "../foo.git" - } - }).create(); - - pubGet(); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - - repo.runGit(['rm', 'pubspec.yaml']); - repo.runGit(['commit', '-m', 'delete']); - - pubUpgrade( - error: new RegExp( - r'Could not find a file named "pubspec.yaml" ' r'in "[^\n]*"\.')); - - d.dir( - packagesPath, - [d.dir('foo', [d.file('foo.dart', 'main() => "foo";')])]).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_dependers_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_dependers_test.dart deleted file mode 100644 index 2d97532f87a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_dependers_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "upgrades a locked package's dependers in order to get it to max " "version", - () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "bar": "<2.0.0" - }); - builder.serve("bar", "1.0.0"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0" - }).validate(); - - servePackages((builder) { - builder.serve("foo", "2.0.0", deps: { - "bar": "<3.0.0" - }); - builder.serve("bar", "2.0.0"); - }); - - pubUpgrade(args: ['bar']); - - d.packagesDir({ - "foo": "2.0.0", - "bar": "2.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_if_necessary_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_if_necessary_test.dart deleted file mode 100644 index fb684696b8f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/unlock_if_necessary_test.dart +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "upgrades one locked pub server package's dependencies if it's " "necessary", - () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "foo_dep": "any" - }); - builder.serve("foo_dep", "1.0.0"); - }); - - d.appDir({ - "foo": "any" - }).create(); - - pubGet(); - - d.packagesDir({ - "foo": "1.0.0", - "foo_dep": "1.0.0" - }).validate(); - - servePackages((builder) { - builder.serve("foo", "2.0.0", deps: { - "foo_dep": ">1.0.0" - }); - builder.serve("foo_dep", "2.0.0"); - }); - - pubUpgrade(args: ['foo']); - - d.packagesDir({ - "foo": "2.0.0", - "foo_dep": "2.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/upgrade_removed_constraints_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/hosted/upgrade_removed_constraints_test.dart deleted file mode 100644 index b5194dd5296..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/hosted/upgrade_removed_constraints_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("upgrades dependencies whose constraints have been removed", () { - servePackages((builder) { - builder.serve("foo", "1.0.0", deps: { - "shared-dep": "any" - }); - builder.serve("bar", "1.0.0", deps: { - "shared-dep": "<2.0.0" - }); - builder.serve("shared-dep", "1.0.0"); - builder.serve("shared-dep", "2.0.0"); - }); - - d.appDir({ - "foo": "any", - "bar": "any" - }).create(); - - pubUpgrade(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": "1.0.0", - "shared-dep": "1.0.0" - }).validate(); - - d.appDir({ - "foo": "any" - }).create(); - - pubUpgrade(); - - d.packagesDir({ - "foo": "1.0.0", - "bar": null, - "shared-dep": "2.0.0" - }).validate(); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/describes_change_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/describes_change_test.dart deleted file mode 100644 index 45eace94e58..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/report/describes_change_test.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("shows how package changed from previous lockfile", () { - servePackages((builder) { - builder.serve("unchanged", "1.0.0"); - builder.serve("version_changed", "1.0.0"); - builder.serve("version_changed", "2.0.0"); - builder.serve("source_changed", "1.0.0"); - }); - - d.dir( - "source_changed", - [d.libDir("source_changed"), d.libPubspec("source_changed", "2.0.0")]).create(); - - d.dir( - "description_changed_1", - [ - d.libDir("description_changed"), - d.libPubspec("description_changed", "1.0.0")]).create(); - - d.dir( - "description_changed_2", - [ - d.libDir("description_changed"), - d.libPubspec("description_changed", "1.0.0")]).create(); - - // Create the first lockfile. - d.appDir({ - "unchanged": "any", - "version_changed": "1.0.0", - "source_changed": "any", - "description_changed": { - "path": "../description_changed_1" - } - }).create(); - - pubGet(); - - // Change the pubspec. - d.appDir({ - "unchanged": "any", - "version_changed": "any", - "source_changed": { - "path": "../source_changed" - }, - "description_changed": { - "path": "../description_changed_2" - } - }).create(); - - // Upgrade everything. - pubUpgrade(output: new RegExp(r""" -Resolving dependencies\.\.\..* -. description_changed 1\.0\.0 from path \.\.[/\\]description_changed_2 \(was 1\.0\.0 from path \.\.[/\\]description_changed_1\) -. source_changed 2\.0\.0 from path \.\.[/\\]source_changed \(was 1\.0\.0\) -. unchanged 1\.0\.0 -. version_changed 2\.0\.0 \(was 1\.0\.0\) -""", multiLine: true)); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/does_not_show_newer_versions_for_locked_packages_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/does_not_show_newer_versions_for_locked_packages_test.dart deleted file mode 100644 index 034f902e6e6..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/report/does_not_show_newer_versions_for_locked_packages_test.dart +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "does not show how many newer versions are available for " - "packages that are locked and not being upgraded", - () { - servePackages((builder) { - builder.serve("not_upgraded", "1.0.0"); - builder.serve("not_upgraded", "2.0.0"); - builder.serve("not_upgraded", "3.0.0-dev"); - builder.serve("upgraded", "1.0.0"); - builder.serve("upgraded", "2.0.0"); - builder.serve("upgraded", "3.0.0-dev"); - }); - - // Constraint everything to the first version. - d.appDir({ - "not_upgraded": "1.0.0", - "upgraded": "1.0.0" - }).create(); - - pubGet(); - - // Loosen the constraints. - d.appDir({ - "not_upgraded": "any", - "upgraded": "any" - }).create(); - - // Only upgrade "upgraded". - pubUpgrade(args: ["upgraded"], output: new RegExp(r""" -Resolving dependencies\.\.\..* - not_upgraded 1\.0\.0 -. upgraded 2\.0\.0 \(was 1\.0\.0\) \(3\.0\.0-dev available\) -""", multiLine: true)); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/highlights_overrides_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/highlights_overrides_test.dart deleted file mode 100644 index 4b567f4bec7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/report/highlights_overrides_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("highlights overridden packages", () { - servePackages((builder) => builder.serve("overridden", "1.0.0")); - - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependency_overrides": { - "overridden": "any" - } - })]).create(); - - // Upgrade everything. - pubUpgrade(output: new RegExp(r""" -Resolving dependencies\.\.\..* -! overridden 1\.0\.0 \(overridden\) -""", multiLine: true)); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/leading_character_shows_change_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/leading_character_shows_change_test.dart deleted file mode 100644 index bb567c2eaaa..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/report/leading_character_shows_change_test.dart +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("the character before each package describes the change", () { - servePackages((builder) { - builder.serve("added", "1.0.0"); - builder.serve("downgraded", "1.0.0"); - builder.serve("downgraded", "2.0.0"); - builder.serve("overridden", "1.0.0"); - builder.serve("removed", "1.0.0"); - builder.serve("source_changed", "1.0.0"); - builder.serve("upgraded", "1.0.0"); - builder.serve("upgraded", "2.0.0"); - builder.serve("unchanged", "1.0.0"); - }); - - d.dir( - "description_changed_1", - [ - d.libDir("description_changed"), - d.libPubspec("description_changed", "1.0.0")]).create(); - - d.dir( - "description_changed_2", - [ - d.libDir("description_changed"), - d.libPubspec("description_changed", "1.0.0")]).create(); - - d.dir( - "source_changed", - [d.libDir("source_changed"), d.libPubspec("source_changed", "1.0.0")]).create(); - - // Create the first lockfile. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "description_changed": { - "path": "../description_changed_1" - }, - "downgraded": "2.0.0", - "removed": "any", - "source_changed": "any", - "unchanged": "any", - "upgraded": "1.0.0" - }, - "dependency_overrides": { - "overridden": "any" - } - })]).create(); - - pubGet(); - - // Change the pubspec. - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependencies": { - "added": "any", - "description_changed": { - "path": "../description_changed_2" - }, - "downgraded": "1.0.0", - "source_changed": { - "path": "../source_changed" - }, - "unchanged": "any", - "upgraded": "2.0.0" - }, - "dependency_overrides": { - "overridden": "any" - } - })]).create(); - - // Upgrade everything. - pubUpgrade(output: new RegExp(r""" -Resolving dependencies\.\.\..* -\+ added .* -\* description_changed .* -< downgraded .* -! overridden .* -\* source_changed .* - unchanged .* -> upgraded .* -These packages are no longer being depended on: -- removed .* -""", multiLine: true)); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_newer_available_versions_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_newer_available_versions_test.dart deleted file mode 100644 index 99364476537..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_newer_available_versions_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration("shows how many newer versions are available", () { - servePackages((builder) { - builder.serve("multiple_newer", "1.0.0"); - builder.serve("multiple_newer", "1.0.1-unstable.1"); - builder.serve("multiple_newer", "1.0.1"); - builder.serve("multiple_newer", "1.0.2-unstable.1"); - builder.serve("multiple_newer_stable", "1.0.0"); - builder.serve("multiple_newer_stable", "1.0.1"); - builder.serve("multiple_newer_stable", "1.0.2"); - builder.serve("multiple_newer_unstable", "1.0.0"); - builder.serve("multiple_newer_unstable", "1.0.1-unstable.1"); - builder.serve("multiple_newer_unstable", "1.0.1-unstable.2"); - builder.serve("no_newer", "1.0.0"); - builder.serve("one_newer_unstable", "1.0.0"); - builder.serve("one_newer_unstable", "1.0.1-unstable.1"); - builder.serve("one_newer_stable", "1.0.0"); - builder.serve("one_newer_stable", "1.0.1"); - }); - - // Constraint everything to the first version. - d.appDir({ - "multiple_newer": "1.0.0", - "multiple_newer_stable": "1.0.0", - "multiple_newer_unstable": "1.0.0", - "no_newer": "1.0.0", - "one_newer_unstable": "1.0.0", - "one_newer_stable": "1.0.0" - }).create(); - - // Upgrade everything. - pubUpgrade(output: new RegExp(r""" -Resolving dependencies\.\.\..* -. multiple_newer 1\.0\.0 \(1\.0\.1 available\) -. multiple_newer_stable 1\.0\.0 \(1\.0\.2\ available\) -. multiple_newer_unstable 1\.0\.0 \(1\.0\.1-unstable\.2 available\) -. no_newer 1\.0\.0 -. one_newer_stable 1\.0\.0 \(1\.0\.1 available\) -. one_newer_unstable 1\.0\.0 \(1\.0\.1-unstable\.1 available\) -""", multiLine: true)); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_number_of_changed_dependencies_test.dart b/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_number_of_changed_dependencies_test.dart deleted file mode 100644 index 2d0b6d7d167..00000000000 --- a/sdk/lib/_internal/pub_generated/test/upgrade/report/shows_number_of_changed_dependencies_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_tests; - -import '../../descriptor.dart' as d; -import '../../test_pub.dart'; - -main() { - initConfig(); - integration( - "does not show how many newer versions are available for " - "packages that are locked and not being upgraded", - () { - servePackages((builder) { - builder.serve("a", "1.0.0"); - builder.serve("b", "1.0.0"); - builder.serve("c", "2.0.0"); - }); - - d.appDir({ - "a": "any" - }).create(); - - // One dependency changed. - pubUpgrade(output: new RegExp(r"Changed 1 dependency!$")); - - // Remove one and add two. - d.appDir({ - "b": "any", - "c": "any" - }).create(); - - pubUpgrade(output: new RegExp(r"Changed 3 dependencies!$")); - - // Don't change anything. - pubUpgrade(output: new RegExp(r"No dependencies changed.$")); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/utils_test.dart b/sdk/lib/_internal/pub_generated/test/utils_test.dart deleted file mode 100644 index 178b7f75388..00000000000 --- a/sdk/lib/_internal/pub_generated/test/utils_test.dart +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library utils_test; - -import 'package:unittest/unittest.dart'; -import 'test_pub.dart'; -import '../lib/src/utils.dart'; - -main() { - initConfig(); - - group('yamlToString()', () { - test('null', () { - expect(yamlToString(null), equals('null')); - }); - - test('numbers', () { - expect(yamlToString(123), equals('123')); - expect(yamlToString(12.34), equals('12.34')); - }); - - test('does not quote strings that do not need it', () { - expect(yamlToString('a'), equals('a')); - expect(yamlToString('some-string'), equals('some-string')); - expect(yamlToString('hey123CAPS'), equals('hey123CAPS')); - expect(yamlToString("_under_score"), equals('_under_score')); - }); - - test('quotes other strings', () { - expect(yamlToString(''), equals('""')); - expect(yamlToString('123'), equals('"123"')); - expect(yamlToString('white space'), equals('"white space"')); - expect(yamlToString('"quote"'), equals(r'"\"quote\""')); - expect(yamlToString("apostrophe'"), equals('"apostrophe\'"')); - expect(yamlToString("new\nline"), equals(r'"new\nline"')); - expect(yamlToString("?unctu@t!on"), equals(r'"?unctu@t!on"')); - }); - - test('lists use JSON style', () { - expect(yamlToString([1, 2, 3]), equals('[1,2,3]')); - }); - - test('uses indentation for maps', () { - expect(yamlToString({ - 'a': { - 'b': 1, - 'c': 2 - }, - 'd': 3 - }), equals(""" -a: - b: 1 - c: 2 -d: 3""")); - }); - - test('sorts map keys', () { - expect(yamlToString({ - 'a': 1, - 'c': 2, - 'b': 3, - 'd': 4 - }), equals(""" -a: 1 -b: 3 -c: 2 -d: 4""")); - }); - - test('quotes map keys as needed', () { - expect(yamlToString({ - 'no': 1, - 'yes!': 2, - '123': 3 - }), equals(""" -"123": 3 -no: 1 -"yes!": 2""")); - }); - - test('handles non-string map keys', () { - var map = new Map(); - map[null] = "null"; - map[123] = "num"; - map[true] = "bool"; - - expect(yamlToString(map), equals(""" -123: num -null: null -true: bool""")); - }); - - test('handles empty maps', () { - expect(yamlToString({}), equals("{}")); - expect(yamlToString({ - 'a': {}, - 'b': {} - }), equals(""" -a: {} -b: {}""")); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/compiled_dartdoc_test.dart b/sdk/lib/_internal/pub_generated/test/validator/compiled_dartdoc_test.dart deleted file mode 100644 index cd0599dca3d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/compiled_dartdoc_test.dart +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/compiled_dartdoc.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator compiledDartdoc(Entrypoint entrypoint) => - new CompiledDartdocValidator(entrypoint); - -main() { - initConfig(); - - group('should consider a package valid if it', () { - setUp(d.validPackage.create); - - integration('looks normal', () => expectNoValidationError(compiledDartdoc)); - - integration('has most but not all files from compiling dartdoc', () { - d.dir( - appPath, - [ - d.dir( - "doc-out", - [ - d.file("nav.json", ""), - d.file("index.html", ""), - d.file("styles.css", ""), - d.file("dart-logo-small.png", "")])]).create(); - expectNoValidationError(compiledDartdoc); - }); - - integration('contains compiled dartdoc in a hidden directory', () { - ensureGit(); - - d.dir( - appPath, - [ - d.dir( - ".doc-out", - [ - d.file('nav.json', ''), - d.file('index.html', ''), - d.file('styles.css', ''), - d.file('dart-logo-small.png', ''), - d.file('client-live-nav.js', '')])]).create(); - expectNoValidationError(compiledDartdoc); - }); - - integration('contains compiled dartdoc in a gitignored directory', () { - ensureGit(); - - d.git( - appPath, - [ - d.dir( - "doc-out", - [ - d.file('nav.json', ''), - d.file('index.html', ''), - d.file('styles.css', ''), - d.file('dart-logo-small.png', ''), - d.file('client-live-nav.js', '')]), - d.file(".gitignore", "/doc-out")]).create(); - expectNoValidationError(compiledDartdoc); - }); - }); - - group("should consider a package invalid if it", () { - integration('contains compiled dartdoc', () { - d.validPackage.create(); - - d.dir( - appPath, - [ - d.dir( - 'doc-out', - [ - d.file('nav.json', ''), - d.file('index.html', ''), - d.file('styles.css', ''), - d.file('dart-logo-small.png', ''), - d.file('client-live-nav.js', '')])]).create(); - - expectValidationWarning(compiledDartdoc); - }); - - integration( - 'contains compiled dartdoc in a non-gitignored hidden ' 'directory', - () { - ensureGit(); - - d.validPackage.create(); - - d.git( - appPath, - [ - d.dir( - '.doc-out', - [ - d.file('nav.json', ''), - d.file('index.html', ''), - d.file('styles.css', ''), - d.file('dart-logo-small.png', ''), - d.file('client-live-nav.js', '')])]).create(); - - expectValidationWarning(compiledDartdoc); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/dependency_override_test.dart b/sdk/lib/_internal/pub_generated/test/validator/dependency_override_test.dart deleted file mode 100644 index 75a64f7be81..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/dependency_override_test.dart +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/dependency_override.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator dependencyOverride(Entrypoint entrypoint) => - new DependencyOverrideValidator(entrypoint); - -main() { - initConfig(); - - integration('invalidates a package if it has dependency overrides', () { - d.dir(appPath, [d.pubspec({ - "name": "myapp", - "dependency_overrides": { - "foo": "<3.0.0" - } - })]).create(); - - expectValidationError(dependencyOverride); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/dependency_test.dart b/sdk/lib/_internal/pub_generated/test/validator/dependency_test.dart deleted file mode 100644 index 689fc66130c..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/dependency_test.dart +++ /dev/null @@ -1,411 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:convert'; - -import 'package:http/http.dart' as http; -import 'package:http/testing.dart'; -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/dependency.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator dependency(Entrypoint entrypoint) => - new DependencyValidator(entrypoint); - -expectDependencyValidationError(String error) { - expect( - schedulePackageValidation(dependency), - completion(pairOf(anyElement(contains(error)), isEmpty))); -} - -expectDependencyValidationWarning(String warning) { - expect( - schedulePackageValidation(dependency), - completion(pairOf(isEmpty, anyElement(contains(warning))))); -} - -/// Sets up a test package with dependency [dep] and mocks a server with -/// [hostedVersions] of the package available. -setUpDependency(Map dep, {List hostedVersions}) { - useMockClient(new MockClient((request) { - expect(request.method, equals("GET")); - expect(request.url.path, equals("/api/packages/foo")); - - if (hostedVersions == null) { - return new Future.value(new http.Response("not found", 404)); - } else { - return new Future.value(new http.Response(JSON.encode({ - "name": "foo", - "uploaders": ["nweiz@google.com"], - "versions": hostedVersions.map( - (version) => packageVersionApiMap(packageMap('foo', version))).toList() - }), 200)); - } - })); - - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": dep - })]).create(); -} - -main() { - initConfig(); - - group('should consider a package valid if it', () { - integration('looks normal', () { - d.validPackage.create(); - expectNoValidationError(dependency); - }); - - integration('has a ^ constraint with an appropriate SDK constraint', () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "^1.2.3" - }, sdk: ">=1.8.0 <2.0.0")]).create(); - expectNoValidationError(dependency); - }); - }); - - group('should consider a package invalid if it', () { - setUp(d.validPackage.create); - - group('has a git dependency', () { - group('where a hosted version exists', () { - integration("and should suggest the hosted primary version", () { - setUpDependency({ - 'git': 'git://github.com/dart-lang/foo' - }, hostedVersions: ["3.0.0-pre", "2.0.0", "1.0.0"]); - expectDependencyValidationWarning(' foo: ">=2.0.0 <3.0.0"'); - }); - - integration( - "and should suggest the hosted prerelease version if " - "it's the only version available", - () { - setUpDependency({ - 'git': 'git://github.com/dart-lang/foo' - }, hostedVersions: ["3.0.0-pre", "2.0.0-pre"]); - expectDependencyValidationWarning(' foo: ">=3.0.0-pre <4.0.0"'); - }); - - integration( - "and should suggest a tighter constraint if primary is " "pre-1.0.0", - () { - setUpDependency({ - 'git': 'git://github.com/dart-lang/foo' - }, hostedVersions: ["0.0.1", "0.0.2"]); - expectDependencyValidationWarning(' foo: ">=0.0.2 <0.1.0"'); - }); - }); - - group('where no hosted version exists', () { - integration("and should use the other source's version", () { - setUpDependency({ - 'git': 'git://github.com/dart-lang/foo', - 'version': '>=1.0.0 <2.0.0' - }); - expectDependencyValidationWarning(' foo: ">=1.0.0 <2.0.0"'); - }); - - integration( - "and should use the other source's unquoted version if " "concrete", - () { - setUpDependency({ - 'git': 'git://github.com/dart-lang/foo', - 'version': '0.2.3' - }); - expectDependencyValidationWarning(' foo: 0.2.3'); - }); - }); - }); - - group('has a path dependency', () { - group('where a hosted version exists', () { - integration("and should suggest the hosted primary version", () { - setUpDependency({ - 'path': path.join(sandboxDir, 'foo') - }, hostedVersions: ["3.0.0-pre", "2.0.0", "1.0.0"]); - expectDependencyValidationError(' foo: ">=2.0.0 <3.0.0"'); - }); - - integration( - "and should suggest the hosted prerelease version if " - "it's the only version available", - () { - setUpDependency({ - 'path': path.join(sandboxDir, 'foo') - }, hostedVersions: ["3.0.0-pre", "2.0.0-pre"]); - expectDependencyValidationError(' foo: ">=3.0.0-pre <4.0.0"'); - }); - - integration( - "and should suggest a tighter constraint if primary is " "pre-1.0.0", - () { - setUpDependency({ - 'path': path.join(sandboxDir, 'foo') - }, hostedVersions: ["0.0.1", "0.0.2"]); - expectDependencyValidationError(' foo: ">=0.0.2 <0.1.0"'); - }); - }); - - group('where no hosted version exists', () { - integration("and should use the other source's version", () { - setUpDependency({ - 'path': path.join(sandboxDir, 'foo'), - 'version': '>=1.0.0 <2.0.0' - }); - expectDependencyValidationError(' foo: ">=1.0.0 <2.0.0"'); - }); - - integration( - "and should use the other source's unquoted version if " "concrete", - () { - setUpDependency({ - 'path': path.join(sandboxDir, 'foo'), - 'version': '0.2.3' - }); - expectDependencyValidationError(' foo: 0.2.3'); - }); - }); - }); - - group('has an unconstrained dependency', () { - group('and it should not suggest a version', () { - integration("if there's no lockfile", () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "any" - })]).create(); - - expect( - schedulePackageValidation(dependency), - completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:")))))); - }); - - integration( - "if the lockfile doesn't have an entry for the " "dependency", - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "any" - }), d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'bar': { - 'version': '1.2.3', - 'source': 'hosted', - 'description': { - 'name': 'bar', - 'url': 'http://pub.dartlang.org' - } - } - } - }))]).create(); - - expect( - schedulePackageValidation(dependency), - completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:")))))); - }); - }); - - group('with a lockfile', () { - integration( - 'and it should suggest a constraint based on the locked ' 'version', - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "any" - }), d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'foo': { - 'version': '1.2.3', - 'source': 'hosted', - 'description': { - 'name': 'foo', - 'url': 'http://pub.dartlang.org' - } - } - } - }))]).create(); - - expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"'); - }); - - integration( - 'and it should suggest a concrete constraint if the locked ' - 'version is pre-1.0.0', - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "any" - }), d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'foo': { - 'version': '0.1.2', - 'source': 'hosted', - 'description': { - 'name': 'foo', - 'url': 'http://pub.dartlang.org' - } - } - } - }))]).create(); - - expectDependencyValidationWarning(' foo: ">=0.1.2 <0.2.0"'); - }); - }); - }); - - integration( - 'with a single-version dependency and it should suggest a ' - 'constraint based on the version', - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "1.2.3" - })]).create(); - - expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"'); - }); - - group('has a dependency without a lower bound', () { - group('and it should not suggest a version', () { - integration("if there's no lockfile", () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "<3.0.0" - })]).create(); - - expect( - schedulePackageValidation(dependency), - completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:")))))); - }); - - integration( - "if the lockfile doesn't have an entry for the " "dependency", - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "<3.0.0" - }), d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'bar': { - 'version': '1.2.3', - 'source': 'hosted', - 'description': { - 'name': 'bar', - 'url': 'http://pub.dartlang.org' - } - } - } - }))]).create(); - - expect( - schedulePackageValidation(dependency), - completion(pairOf(isEmpty, everyElement(isNot(contains("\n foo:")))))); - }); - }); - - group('with a lockfile', () { - integration( - 'and it should suggest a constraint based on the locked ' 'version', - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "<3.0.0" - }), d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'foo': { - 'version': '1.2.3', - 'source': 'hosted', - 'description': { - 'name': 'foo', - 'url': 'http://pub.dartlang.org' - } - } - } - }))]).create(); - - expectDependencyValidationWarning(' foo: ">=1.2.3 <3.0.0"'); - }); - - integration('and it should preserve the upper-bound operator', () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "<=3.0.0" - }), d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'foo': { - 'version': '1.2.3', - 'source': 'hosted', - 'description': { - 'name': 'foo', - 'url': 'http://pub.dartlang.org' - } - } - } - }))]).create(); - - expectDependencyValidationWarning(' foo: ">=1.2.3 <=3.0.0"'); - }); - - integration( - 'and it should expand the suggested constraint if the ' - 'locked version matches the upper bound', - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "<=1.2.3" - }), d.file("pubspec.lock", JSON.encode({ - 'packages': { - 'foo': { - 'version': '1.2.3', - 'source': 'hosted', - 'description': { - 'name': 'foo', - 'url': 'http://pub.dartlang.org' - } - } - } - }))]).create(); - - expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"'); - }); - }); - }); - - group('with a dependency without an upper bound', () { - integration( - 'and it should suggest a constraint based on the lower bound', - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": ">=1.2.3" - })]).create(); - - expectDependencyValidationWarning(' foo: ">=1.2.3 <2.0.0"'); - }); - - integration('and it should preserve the lower-bound operator', () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": ">1.2.3" - })]).create(); - - expectDependencyValidationWarning(' foo: ">1.2.3 <2.0.0"'); - }); - }); - - group('has a ^ dependency', () { - integration("without an SDK constraint", () { - d.dir(appPath, [d.libPubspec("integration_pkg", "1.0.0", deps: { - "foo": "^1.2.3" - })]).create(); - - expectDependencyValidationError(' foo: ">=1.2.3 <2.0.0"'); - }); - - integration("with a too-broad SDK constraint", () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", deps: { - "foo": "^1.2.3" - }, sdk: ">=1.5.0 <2.0.0")]).create(); - - expectDependencyValidationError(' foo: ">=1.2.3 <2.0.0"'); - }); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/directory_test.dart b/sdk/lib/_internal/pub_generated/test/validator/directory_test.dart deleted file mode 100644 index fcfdb11cb3e..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/directory_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/directory.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator directory(Entrypoint entrypoint) => - new DirectoryValidator(entrypoint); - -main() { - initConfig(); - - group('should consider a package valid if it', () { - setUp(d.validPackage.create); - - integration('looks normal', () => expectNoValidationError(directory)); - - integration('has a nested directory named "tools"', () { - d.dir(appPath, [d.dir("foo", [d.dir("tools")])]).create(); - expectNoValidationError(directory); - }); - }); - - group( - 'should consider a package invalid if it has a top-level directory ' 'named', - () { - setUp(d.validPackage.create); - - var names = [ - "benchmarks", - "docs", - "examples", - "sample", - "samples", - "tests", - "tools"]; - - for (var name in names) { - integration('"$name"', () { - d.dir(appPath, [d.dir(name)]).create(); - expectValidationWarning(directory); - }); - } - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/executable_test.dart b/sdk/lib/_internal/pub_generated/test/validator/executable_test.dart deleted file mode 100644 index 995fef90907..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/executable_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/executable.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator executable(Entrypoint entrypoint) => - new ExecutableValidator(entrypoint); - -main() { - initConfig(); - - setUp(d.validPackage.create); - - group('should consider a package valid if it', () { - integration('has executables that are present', () { - d.dir(appPath, [d.pubspec({ - "name": "test_pkg", - "version": "1.0.0", - "executables": { - "one": "one_script", - "two": null - } - }), - d.dir( - "bin", - [ - d.file("one_script.dart", "main() => print('ok');"), - d.file("two.dart", "main() => print('ok');")])]).create(); - expectNoValidationError(executable); - }); - }); - - group("should consider a package invalid if it", () { - integration('is missing one or more listed executables', () { - d.dir(appPath, [d.pubspec({ - "name": "test_pkg", - "version": "1.0.0", - "executables": { - "nope": "not_there", - "nada": null - } - })]).create(); - expectValidationWarning(executable); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/license_test.dart b/sdk/lib/_internal/pub_generated/test/validator/license_test.dart deleted file mode 100644 index 7cd2039481a..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/license_test.dart +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/io.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/license.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator license(Entrypoint entrypoint) => new LicenseValidator(entrypoint); - -main() { - initConfig(); - - group('should consider a package valid if it', () { - setUp(d.validPackage.create); - - integration('looks normal', () => expectNoValidationError(license)); - - integration('has a COPYING file', () { - schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE'))); - d.file(path.join(appPath, 'COPYING'), '').create(); - expectNoValidationError(license); - }); - - integration('has a prefixed LICENSE file', () { - schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE'))); - d.file(path.join(appPath, 'MIT_LICENSE'), '').create(); - expectNoValidationError(license); - }); - - integration('has a suffixed LICENSE file', () { - schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE'))); - d.file(path.join(appPath, 'LICENSE.md'), '').create(); - expectNoValidationError(license); - }); - }); - - integration( - 'should consider a package invalid if it has no LICENSE file', - () { - d.validPackage.create(); - schedule(() => deleteEntry(path.join(sandboxDir, appPath, 'LICENSE'))); - expectValidationError(license); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/name_test.dart b/sdk/lib/_internal/pub_generated/test/validator/name_test.dart deleted file mode 100644 index 6e91bf42814..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/name_test.dart +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/io.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/name.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator name(Entrypoint entrypoint) => new NameValidator(entrypoint); - -main() { - initConfig(); - - group('should consider a package valid if it', () { - setUp(d.validPackage.create); - - integration('looks normal', () => expectNoValidationError(name)); - - integration('has a badly-named library in lib/src', () { - d.dir( - appPath, - [ - d.libPubspec("test_pkg", "1.0.0"), - d.dir( - "lib", - [ - d.file("test_pkg.dart", "int i = 1;"), - d.dir("src", [d.file("8ball.dart", "int j = 2;")])])]).create(); - expectNoValidationError(name); - }); - - integration('has a name that starts with an underscore', () { - d.dir( - appPath, - [ - d.libPubspec("_test_pkg", "1.0.0"), - d.dir("lib", [d.file("_test_pkg.dart", "int i = 1;")])]).create(); - expectNoValidationError(name); - }); - }); - - group('should consider a package invalid if it', () { - setUp(d.validPackage.create); - - integration('has an empty package name', () { - d.dir(appPath, [d.libPubspec("", "1.0.0")]).create(); - expectValidationError(name); - }); - - integration('has a package name with an invalid character', () { - d.dir(appPath, [d.libPubspec("test-pkg", "1.0.0")]).create(); - expectValidationError(name); - }); - - integration('has a package name that begins with a number', () { - d.dir(appPath, [d.libPubspec("8ball", "1.0.0")]).create(); - expectValidationError(name); - }); - - integration('has a package name that contains upper-case letters', () { - d.dir(appPath, [d.libPubspec("TestPkg", "1.0.0")]).create(); - expectValidationWarning(name); - }); - - integration('has a package name that is a Dart reserved word', () { - d.dir(appPath, [d.libPubspec("final", "1.0.0")]).create(); - expectValidationError(name); - }); - - integration('has a library name with an invalid character', () { - d.dir( - appPath, - [ - d.libPubspec("test_pkg", "1.0.0"), - d.dir("lib", [d.file("test-pkg.dart", "int i = 0;")])]).create(); - expectValidationWarning(name); - }); - - integration('has a library name that begins with a number', () { - d.dir( - appPath, - [ - d.libPubspec("test_pkg", "1.0.0"), - d.dir("lib", [d.file("8ball.dart", "int i = 0;")])]).create(); - expectValidationWarning(name); - }); - - integration('has a library name that contains upper-case letters', () { - d.dir( - appPath, - [ - d.libPubspec("test_pkg", "1.0.0"), - d.dir("lib", [d.file("TestPkg.dart", "int i = 0;")])]).create(); - expectValidationWarning(name); - }); - - integration('has a library name that is a Dart reserved word', () { - d.dir( - appPath, - [ - d.libPubspec("test_pkg", "1.0.0"), - d.dir("lib", [d.file("for.dart", "int i = 0;")])]).create(); - expectValidationWarning(name); - }); - - integration('has a single library named differently than the package', () { - schedule( - () => deleteEntry(path.join(sandboxDir, appPath, "lib", "test_pkg.dart"))); - d.dir( - appPath, - [d.dir("lib", [d.file("best_pkg.dart", "int i = 0;")])]).create(); - expectValidationWarning(name); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/pubspec_field_test.dart b/sdk/lib/_internal/pub_generated/test/validator/pubspec_field_test.dart deleted file mode 100644 index 0d0c8b91c1f..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/pubspec_field_test.dart +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/pubspec_field.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator pubspecField(Entrypoint entrypoint) => - new PubspecFieldValidator(entrypoint); - -main() { - initConfig(); - - group('should consider a package valid if it', () { - setUp(d.validPackage.create); - - integration('looks normal', () => expectNoValidationError(pubspecField)); - - integration('has "authors" instead of "author"', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["authors"] = [pkg.remove("author")]; - d.dir(appPath, [d.pubspec(pkg)]).create(); - expectNoValidationError(pubspecField); - }); - - integration('has an HTTPS homepage URL', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["homepage"] = "https://pub.dartlang.org"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectNoValidationError(pubspecField); - }); - - integration('has an HTTPS documentation URL', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["documentation"] = "https://pub.dartlang.org"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectNoValidationError(pubspecField); - }); - }); - - group('should consider a package invalid if it', () { - setUp(d.validPackage.create); - - integration('is missing the "homepage" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg.remove("homepage"); - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('is missing the "description" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg.remove("description"); - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('is missing the "author" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg.remove("author"); - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('has a non-string "homepage" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["homepage"] = 12; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('has a non-string "description" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["description"] = 12; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('has a non-string "author" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = 12; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('has a non-list "authors" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["authors"] = 12; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('has a non-string member of the "authors" field', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["authors"] = [12]; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('has a single author without an email', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = "Natalie Weizenbaum"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationWarning(pubspecField); - }); - - integration('has one of several authors without an email', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg.remove("author"); - pkg["authors"] = [ - "Bob Nystrom ", - "Natalie Weizenbaum", - "John Messerly "]; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationWarning(pubspecField); - }); - - integration('has a single author without a name', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["author"] = ""; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationWarning(pubspecField); - }); - - integration('has one of several authors without a name', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg.remove("author"); - pkg["authors"] = [ - "Bob Nystrom ", - "", - "John Messerly "]; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationWarning(pubspecField); - }); - - integration('has a non-HTTP homepage URL', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["homepage"] = "file:///foo/bar"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - - integration('has a non-HTTP documentation URL', () { - var pkg = packageMap("test_pkg", "1.0.0"); - pkg["documentation"] = "file:///foo/bar"; - d.dir(appPath, [d.pubspec(pkg)]).create(); - - expectValidationError(pubspecField); - }); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/sdk_constraint_test.dart b/sdk/lib/_internal/pub_generated/test/validator/sdk_constraint_test.dart deleted file mode 100644 index 27c568a4f76..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/sdk_constraint_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:convert'; - -import 'package:http/http.dart' as http; -import 'package:http/testing.dart'; -import 'package:path/path.dart' as path; -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/sdk_constraint.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator sdkConstraint(Entrypoint entrypoint) => - new SdkConstraintValidator(entrypoint); - -main() { - initConfig(); - - group('should consider a package valid if it', () { - integration('has no SDK constraint', () { - d.validPackage.create(); - expectNoValidationError(sdkConstraint); - }); - - integration('has an SDK constraint without ^', () { - d.dir( - appPath, - [d.libPubspec("test_pkg", "1.0.0", sdk: ">=1.8.0 <2.0.0")]).create(); - expectNoValidationError(sdkConstraint); - }); - }); - - test( - "should consider a package invalid if it has an SDK constraint with " "^", - () { - d.dir(appPath, [d.libPubspec("test_pkg", "1.0.0", sdk: "^1.8.0")]).create(); - expect( - schedulePackageValidation(sdkConstraint), - completion(pairOf(anyElement(contains('">=1.8.0 <2.0.0"')), isEmpty))); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/size_test.dart b/sdk/lib/_internal/pub_generated/test/validator/size_test.dart deleted file mode 100644 index 15a4b06561b..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/size_test.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:math' as math; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/validator/size.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Function size(int size) { - return (entrypoint) => new SizeValidator(entrypoint, new Future.value(size)); -} - -main() { - initConfig(); - - setUp(d.validPackage.create); - - integration('should consider a package valid if it is <= 10 MB', () { - expectNoValidationError(size(100)); - expectNoValidationError(size(10 * math.pow(2, 20))); - }); - - integration('should consider a package invalid if it is more than 10 MB', () { - expectValidationError(size(10 * math.pow(2, 20) + 1)); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/utf8_readme_test.dart b/sdk/lib/_internal/pub_generated/test/validator/utf8_readme_test.dart deleted file mode 100644 index a2e3cf19cd7..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/utf8_readme_test.dart +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../../lib/src/entrypoint.dart'; -import '../../lib/src/validator.dart'; -import '../../lib/src/validator/utf8_readme.dart'; -import '../descriptor.dart' as d; -import '../test_pub.dart'; -import 'utils.dart'; - -Validator utf8Readme(Entrypoint entrypoint) => - new Utf8ReadmeValidator(entrypoint); - -main() { - initConfig(); - - group('should consider a package valid if it', () { - setUp(d.validPackage.create); - - integration('looks normal', () => expectNoValidationError(utf8Readme)); - - integration('has a non-primary readme with invalid utf-8', () { - d.dir( - appPath, - [ - d.file("README", "Valid utf-8"), - d.binaryFile("README.invalid", [192])]).create(); - expectNoValidationError(utf8Readme); - }); - }); - - integration( - 'should consider a package invalid if it has a README with ' 'invalid utf-8', - () { - d.validPackage.create(); - - d.dir(appPath, [d.binaryFile("README", [192])]).create(); - expectValidationWarning(utf8Readme); - }); -} diff --git a/sdk/lib/_internal/pub_generated/test/validator/utils.dart b/sdk/lib/_internal/pub_generated/test/validator/utils.dart deleted file mode 100644 index def5bb9878d..00000000000 --- a/sdk/lib/_internal/pub_generated/test/validator/utils.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library validator.utils; - -import 'package:scheduled_test/scheduled_test.dart'; - -import '../test_pub.dart'; - -void expectNoValidationError(ValidatorCreator fn) { - expect(schedulePackageValidation(fn), completion(pairOf(isEmpty, isEmpty))); -} - -void expectValidationError(ValidatorCreator fn) { - expect( - schedulePackageValidation(fn), - completion(pairOf(isNot(isEmpty), anything))); -} - -void expectValidationWarning(ValidatorCreator fn) { - expect( - schedulePackageValidation(fn), - completion(pairOf(isEmpty, isNot(isEmpty)))); -} diff --git a/sdk/lib/_internal/pub_generated/test/version_solver_test.dart b/sdk/lib/_internal/pub_generated/test/version_solver_test.dart deleted file mode 100644 index f013a8821c8..00000000000 --- a/sdk/lib/_internal/pub_generated/test/version_solver_test.dart +++ /dev/null @@ -1,1720 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -library pub_upgrade_test; - -import 'dart:async'; - -import 'package:pub_semver/pub_semver.dart'; -import 'package:unittest/unittest.dart'; - -import '../lib/src/lock_file.dart'; -import '../lib/src/log.dart' as log; -import '../lib/src/package.dart'; -import '../lib/src/pubspec.dart'; -import '../lib/src/sdk.dart' as sdk; -import '../lib/src/source/cached.dart'; -import '../lib/src/system_cache.dart'; -import '../lib/src/utils.dart'; -import '../lib/src/solver/version_solver.dart'; -import 'test_pub.dart'; - -MockSource source1; -MockSource source2; - -main() { - initConfig(); - - // Uncomment this to debug failing tests. - // log.verbosity = log.Verbosity.SOLVER; - - // Since this test isn't run from the SDK, it can't find the "version" file - // to load. Instead, just manually inject a version. - sdk.version = new Version(1, 2, 3); - - group('basic graph', basicGraph); - group('with lockfile', withLockFile); - group('root dependency', rootDependency); - group('dev dependency', devDependency); - group('unsolvable', unsolvable); - group('bad source', badSource); - group('backtracking', backtracking); - group('SDK constraint', sdkConstraint); - group('pre-release', prerelease); - group('override', override); - group('downgrade', downgrade); -} - -void basicGraph() { - testResolve('no dependencies', { - 'myapp 0.0.0': {} - }, result: { - 'myapp from root': '0.0.0' - }); - - testResolve('simple dependency tree', { - 'myapp 0.0.0': { - 'a': '1.0.0', - 'b': '1.0.0' - }, - 'a 1.0.0': { - 'aa': '1.0.0', - 'ab': '1.0.0' - }, - 'aa 1.0.0': {}, - 'ab 1.0.0': {}, - 'b 1.0.0': { - 'ba': '1.0.0', - 'bb': '1.0.0' - }, - 'ba 1.0.0': {}, - 'bb 1.0.0': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0', - 'aa': '1.0.0', - 'ab': '1.0.0', - 'b': '1.0.0', - 'ba': '1.0.0', - 'bb': '1.0.0' - }); - - testResolve('shared dependency with overlapping constraints', { - 'myapp 0.0.0': { - 'a': '1.0.0', - 'b': '1.0.0' - }, - 'a 1.0.0': { - 'shared': '>=2.0.0 <4.0.0' - }, - 'b 1.0.0': { - 'shared': '>=3.0.0 <5.0.0' - }, - 'shared 2.0.0': {}, - 'shared 3.0.0': {}, - 'shared 3.6.9': {}, - 'shared 4.0.0': {}, - 'shared 5.0.0': {}, - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0', - 'b': '1.0.0', - 'shared': '3.6.9' - }); - - testResolve( - 'shared dependency where dependent version in turn affects ' - 'other dependencies', - { - 'myapp 0.0.0': { - 'foo': '<=1.0.2', - 'bar': '1.0.0' - }, - 'foo 1.0.0': {}, - 'foo 1.0.1': { - 'bang': '1.0.0' - }, - 'foo 1.0.2': { - 'whoop': '1.0.0' - }, - 'foo 1.0.3': { - 'zoop': '1.0.0' - }, - 'bar 1.0.0': { - 'foo': '<=1.0.1' - }, - 'bang 1.0.0': {}, - 'whoop 1.0.0': {}, - 'zoop 1.0.0': {} - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.1', - 'bar': '1.0.0', - 'bang': '1.0.0' - }, maxTries: 2); - - testResolve('circular dependency', { - 'myapp 1.0.0': { - 'foo': '1.0.0' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'bar 1.0.0': { - 'foo': '1.0.0' - } - }, result: { - 'myapp from root': '1.0.0', - 'foo': '1.0.0', - 'bar': '1.0.0' - }); -} - -withLockFile() { - testResolve('with compatible locked dependency', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'foo 1.0.1': { - 'bar': '1.0.1' - }, - 'foo 1.0.2': { - 'bar': '1.0.2' - }, - 'bar 1.0.0': {}, - 'bar 1.0.1': {}, - 'bar 1.0.2': {} - }, lockfile: { - 'foo': '1.0.1' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.1', - 'bar': '1.0.1' - }); - - testResolve('with incompatible locked dependency', { - 'myapp 0.0.0': { - 'foo': '>1.0.1' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'foo 1.0.1': { - 'bar': '1.0.1' - }, - 'foo 1.0.2': { - 'bar': '1.0.2' - }, - 'bar 1.0.0': {}, - 'bar 1.0.1': {}, - 'bar 1.0.2': {} - }, lockfile: { - 'foo': '1.0.1' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.2', - 'bar': '1.0.2' - }); - - testResolve('with unrelated locked dependency', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'foo 1.0.1': { - 'bar': '1.0.1' - }, - 'foo 1.0.2': { - 'bar': '1.0.2' - }, - 'bar 1.0.0': {}, - 'bar 1.0.1': {}, - 'bar 1.0.2': {}, - 'baz 1.0.0': {} - }, lockfile: { - 'baz': '1.0.0' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.2', - 'bar': '1.0.2' - }); - - testResolve( - 'unlocks dependencies if necessary to ensure that a new ' - 'dependency is satisfied', - { - 'myapp 0.0.0': { - 'foo': 'any', - 'newdep': 'any' - }, - 'foo 1.0.0': { - 'bar': '<2.0.0' - }, - 'bar 1.0.0': { - 'baz': '<2.0.0' - }, - 'baz 1.0.0': { - 'qux': '<2.0.0' - }, - 'qux 1.0.0': {}, - 'foo 2.0.0': { - 'bar': '<3.0.0' - }, - 'bar 2.0.0': { - 'baz': '<3.0.0' - }, - 'baz 2.0.0': { - 'qux': '<3.0.0' - }, - 'qux 2.0.0': {}, - 'newdep 2.0.0': { - 'baz': '>=1.5.0' - } - }, lockfile: { - 'foo': '1.0.0', - 'bar': '1.0.0', - 'baz': '1.0.0', - 'qux': '1.0.0' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '2.0.0', - 'bar': '2.0.0', - 'baz': '2.0.0', - 'qux': '1.0.0', - 'newdep': '2.0.0' - }, maxTries: 3); -} - -rootDependency() { - testResolve('with root source', { - 'myapp 1.0.0': { - 'foo': '1.0.0' - }, - 'foo 1.0.0': { - 'myapp from root': '>=1.0.0' - } - }, result: { - 'myapp from root': '1.0.0', - 'foo': '1.0.0' - }); - - testResolve('with different source', { - 'myapp 1.0.0': { - 'foo': '1.0.0' - }, - 'foo 1.0.0': { - 'myapp': '>=1.0.0' - } - }, result: { - 'myapp from root': '1.0.0', - 'foo': '1.0.0' - }); - - testResolve('with mismatched sources', { - 'myapp 1.0.0': { - 'foo': '1.0.0', - 'bar': '1.0.0' - }, - 'foo 1.0.0': { - 'myapp': '>=1.0.0' - }, - 'bar 1.0.0': { - 'myapp from mock2': '>=1.0.0' - } - }, error: sourceMismatch('myapp', 'foo', 'bar')); - - testResolve('with wrong version', { - 'myapp 1.0.0': { - 'foo': '1.0.0' - }, - 'foo 1.0.0': { - 'myapp': '<1.0.0' - } - }, error: couldNotSolve); -} - -devDependency() { - testResolve("includes root package's dev dependencies", { - 'myapp 1.0.0': { - '(dev) foo': '1.0.0', - '(dev) bar': '1.0.0' - }, - 'foo 1.0.0': {}, - 'bar 1.0.0': {} - }, result: { - 'myapp from root': '1.0.0', - 'foo': '1.0.0', - 'bar': '1.0.0' - }); - - testResolve("includes dev dependency's transitive dependencies", { - 'myapp 1.0.0': { - '(dev) foo': '1.0.0' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'bar 1.0.0': {} - }, result: { - 'myapp from root': '1.0.0', - 'foo': '1.0.0', - 'bar': '1.0.0' - }); - - testResolve("ignores transitive dependency's dev dependencies", { - 'myapp 1.0.0': { - 'foo': '1.0.0' - }, - 'foo 1.0.0': { - '(dev) bar': '1.0.0' - }, - 'bar 1.0.0': {} - }, result: { - 'myapp from root': '1.0.0', - 'foo': '1.0.0' - }); -} - -unsolvable() { - testResolve('no version that matches requirement', { - 'myapp 0.0.0': { - 'foo': '>=1.0.0 <2.0.0' - }, - 'foo 2.0.0': {}, - 'foo 2.1.3': {} - }, error: noVersion(['myapp', 'foo'])); - - testResolve('no version that matches combined constraint', { - 'myapp 0.0.0': { - 'foo': '1.0.0', - 'bar': '1.0.0' - }, - 'foo 1.0.0': { - 'shared': '>=2.0.0 <3.0.0' - }, - 'bar 1.0.0': { - 'shared': '>=2.9.0 <4.0.0' - }, - 'shared 2.5.0': {}, - 'shared 3.5.0': {} - }, error: noVersion(['shared', 'foo', 'bar'])); - - testResolve('disjoint constraints', { - 'myapp 0.0.0': { - 'foo': '1.0.0', - 'bar': '1.0.0' - }, - 'foo 1.0.0': { - 'shared': '<=2.0.0' - }, - 'bar 1.0.0': { - 'shared': '>3.0.0' - }, - 'shared 2.0.0': {}, - 'shared 4.0.0': {} - }, error: disjointConstraint(['shared', 'foo', 'bar'])); - - testResolve('mismatched descriptions', { - 'myapp 0.0.0': { - 'foo': '1.0.0', - 'bar': '1.0.0' - }, - 'foo 1.0.0': { - 'shared-x': '1.0.0' - }, - 'bar 1.0.0': { - 'shared-y': '1.0.0' - }, - 'shared-x 1.0.0': {}, - 'shared-y 1.0.0': {} - }, error: descriptionMismatch('shared', 'foo', 'bar')); - - testResolve('mismatched sources', { - 'myapp 0.0.0': { - 'foo': '1.0.0', - 'bar': '1.0.0' - }, - 'foo 1.0.0': { - 'shared': '1.0.0' - }, - 'bar 1.0.0': { - 'shared from mock2': '1.0.0' - }, - 'shared 1.0.0': {}, - 'shared 1.0.0 from mock2': {} - }, error: sourceMismatch('shared', 'foo', 'bar')); - - testResolve('no valid solution', { - 'myapp 0.0.0': { - 'a': 'any', - 'b': 'any' - }, - 'a 1.0.0': { - 'b': '1.0.0' - }, - 'a 2.0.0': { - 'b': '2.0.0' - }, - 'b 1.0.0': { - 'a': '2.0.0' - }, - 'b 2.0.0': { - 'a': '1.0.0' - } - }, error: couldNotSolve, maxTries: 4); - - // This is a regression test for #15550. - testResolve('no version that matches while backtracking', { - 'myapp 0.0.0': { - 'a': 'any', - 'b': '>1.0.0' - }, - 'a 1.0.0': {}, - 'b 1.0.0': {} - }, error: noVersion(['myapp', 'b']), maxTries: 1); - - - // This is a regression test for #18300. - testResolve('...', { - "myapp 0.0.0": { - "angular": "any", - "collection": "any" - }, - "analyzer 0.12.2": {}, - "angular 0.10.0": { - "di": ">=0.0.32 <0.1.0", - "collection": ">=0.9.1 <1.0.0" - }, - "angular 0.9.11": { - "di": ">=0.0.32 <0.1.0", - "collection": ">=0.9.1 <1.0.0" - }, - "angular 0.9.10": { - "di": ">=0.0.32 <0.1.0", - "collection": ">=0.9.1 <1.0.0" - }, - "collection 0.9.0": {}, - "collection 0.9.1": {}, - "di 0.0.37": { - "analyzer": ">=0.13.0 <0.14.0" - }, - "di 0.0.36": { - "analyzer": ">=0.13.0 <0.14.0" - } - }, error: noVersion(['myapp', 'angular', 'collection']), maxTries: 9); -} - -badSource() { - testResolve('fail if the root package has a bad source in dep', { - 'myapp 0.0.0': { - 'foo from bad': 'any' - }, - }, error: unknownSource('myapp', 'foo', 'bad')); - - testResolve('fail if the root package has a bad source in dev dep', { - 'myapp 0.0.0': { - '(dev) foo from bad': 'any' - }, - }, error: unknownSource('myapp', 'foo', 'bad')); - - testResolve('fail if all versions have bad source in dep', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar from bad': 'any' - }, - 'foo 1.0.1': { - 'baz from bad': 'any' - }, - 'foo 1.0.3': { - 'bang from bad': 'any' - }, - }, error: unknownSource('foo', 'bar', 'bad'), maxTries: 3); - - testResolve('ignore versions with bad source in dep', { - 'myapp 1.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': 'any' - }, - 'foo 1.0.1': { - 'bar from bad': 'any' - }, - 'foo 1.0.3': { - 'bar from bad': 'any' - }, - 'bar 1.0.0': {} - }, result: { - 'myapp from root': '1.0.0', - 'foo': '1.0.0', - 'bar': '1.0.0' - }, maxTries: 3); -} - -backtracking() { - testResolve('circular dependency on older version', { - 'myapp 0.0.0': { - 'a': '>=1.0.0' - }, - 'a 1.0.0': {}, - 'a 2.0.0': { - 'b': '1.0.0' - }, - 'b 1.0.0': { - 'a': '1.0.0' - } - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0' - }, maxTries: 2); - - // The latest versions of a and b disagree on c. An older version of either - // will resolve the problem. This test validates that b, which is farther - // in the dependency graph from myapp is downgraded first. - testResolve('rolls back leaf versions first', { - 'myapp 0.0.0': { - 'a': 'any' - }, - 'a 1.0.0': { - 'b': 'any' - }, - 'a 2.0.0': { - 'b': 'any', - 'c': '2.0.0' - }, - 'b 1.0.0': {}, - 'b 2.0.0': { - 'c': '1.0.0' - }, - 'c 1.0.0': {}, - 'c 2.0.0': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '2.0.0', - 'b': '1.0.0', - 'c': '2.0.0' - }, maxTries: 2); - - // Only one version of baz, so foo and bar will have to downgrade until they - // reach it. - testResolve('simple transitive', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'foo 2.0.0': { - 'bar': '2.0.0' - }, - 'foo 3.0.0': { - 'bar': '3.0.0' - }, - 'bar 1.0.0': { - 'baz': 'any' - }, - 'bar 2.0.0': { - 'baz': '2.0.0' - }, - 'bar 3.0.0': { - 'baz': '3.0.0' - }, - 'baz 1.0.0': {} - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.0', - 'bar': '1.0.0', - 'baz': '1.0.0' - }, maxTries: 3); - - // This ensures it doesn't exhaustively search all versions of b when it's - // a-2.0.0 whose dependency on c-2.0.0-nonexistent led to the problem. We - // make sure b has more versions than a so that the solver tries a first - // since it sorts sibling dependencies by number of versions. - testResolve('backjump to nearer unsatisfied package', { - 'myapp 0.0.0': { - 'a': 'any', - 'b': 'any' - }, - 'a 1.0.0': { - 'c': '1.0.0' - }, - 'a 2.0.0': { - 'c': '2.0.0-nonexistent' - }, - 'b 1.0.0': {}, - 'b 2.0.0': {}, - 'b 3.0.0': {}, - 'c 1.0.0': {}, - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0', - 'b': '3.0.0', - 'c': '1.0.0' - }, maxTries: 2); - - // Tests that the backjumper will jump past unrelated selections when a - // source conflict occurs. This test selects, in order: - // - myapp -> a - // - myapp -> b - // - myapp -> c (1 of 5) - // - b -> a - // It selects a and b first because they have fewer versions than c. It - // traverses b's dependency on a after selecting a version of c because - // dependencies are traversed breadth-first (all of myapps's immediate deps - // before any other their deps). - // - // This means it doesn't discover the source conflict until after selecting - // c. When that happens, it should backjump past c instead of trying older - // versions of it since they aren't related to the conflict. - testResolve('backjump to conflicting source', { - 'myapp 0.0.0': { - 'a': 'any', - 'b': 'any', - 'c': 'any' - }, - 'a 1.0.0': {}, - 'a 1.0.0 from mock2': {}, - 'b 1.0.0': { - 'a': 'any' - }, - 'b 2.0.0': { - 'a from mock2': 'any' - }, - 'c 1.0.0': {}, - 'c 2.0.0': {}, - 'c 3.0.0': {}, - 'c 4.0.0': {}, - 'c 5.0.0': {}, - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0', - 'b': '1.0.0', - 'c': '5.0.0' - }, maxTries: 2); - - // Like the above test, but for a conflicting description. - testResolve('backjump to conflicting description', { - 'myapp 0.0.0': { - 'a-x': 'any', - 'b': 'any', - 'c': 'any' - }, - 'a-x 1.0.0': {}, - 'a-y 1.0.0': {}, - 'b 1.0.0': { - 'a-x': 'any' - }, - 'b 2.0.0': { - 'a-y': 'any' - }, - 'c 1.0.0': {}, - 'c 2.0.0': {}, - 'c 3.0.0': {}, - 'c 4.0.0': {}, - 'c 5.0.0': {}, - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0', - 'b': '1.0.0', - 'c': '5.0.0' - }, maxTries: 2); - - // Similar to the above two tests but where there is no solution. It should - // fail in this case with no backtracking. - testResolve('backjump to conflicting source', { - 'myapp 0.0.0': { - 'a': 'any', - 'b': 'any', - 'c': 'any' - }, - 'a 1.0.0': {}, - 'a 1.0.0 from mock2': {}, - 'b 1.0.0': { - 'a from mock2': 'any' - }, - 'c 1.0.0': {}, - 'c 2.0.0': {}, - 'c 3.0.0': {}, - 'c 4.0.0': {}, - 'c 5.0.0': {}, - }, error: sourceMismatch('a', 'myapp', 'b'), maxTries: 1); - - testResolve('backjump to conflicting description', { - 'myapp 0.0.0': { - 'a-x': 'any', - 'b': 'any', - 'c': 'any' - }, - 'a-x 1.0.0': {}, - 'a-y 1.0.0': {}, - 'b 1.0.0': { - 'a-y': 'any' - }, - 'c 1.0.0': {}, - 'c 2.0.0': {}, - 'c 3.0.0': {}, - 'c 4.0.0': {}, - 'c 5.0.0': {}, - }, error: descriptionMismatch('a', 'myapp', 'b'), maxTries: 1); - - // Dependencies are ordered so that packages with fewer versions are tried - // first. Here, there are two valid solutions (either a or b must be - // downgraded once). The chosen one depends on which dep is traversed first. - // Since b has fewer versions, it will be traversed first, which means a will - // come later. Since later selections are revised first, a gets downgraded. - testResolve('traverse into package with fewer versions first', { - 'myapp 0.0.0': { - 'a': 'any', - 'b': 'any' - }, - 'a 1.0.0': { - 'c': 'any' - }, - 'a 2.0.0': { - 'c': 'any' - }, - 'a 3.0.0': { - 'c': 'any' - }, - 'a 4.0.0': { - 'c': 'any' - }, - 'a 5.0.0': { - 'c': '1.0.0' - }, - 'b 1.0.0': { - 'c': 'any' - }, - 'b 2.0.0': { - 'c': 'any' - }, - 'b 3.0.0': { - 'c': 'any' - }, - 'b 4.0.0': { - 'c': '2.0.0' - }, - 'c 1.0.0': {}, - 'c 2.0.0': {}, - }, result: { - 'myapp from root': '0.0.0', - 'a': '4.0.0', - 'b': '4.0.0', - 'c': '2.0.0' - }, maxTries: 2); - - // This is similar to the above test. When getting the number of versions of - // a package to determine which to traverse first, versions that are - // disallowed by the root package's constraints should not be considered. - // Here, foo has more versions of bar in total (4), but fewer that meet - // myapp's constraints (only 2). There is no solution, but we will do less - // backtracking if foo is tested first. - testResolve('take root package constraints into counting versions', { - "myapp 0.0.0": { - "foo": ">2.0.0", - "bar": "any" - }, - "foo 1.0.0": { - "none": "2.0.0" - }, - "foo 2.0.0": { - "none": "2.0.0" - }, - "foo 3.0.0": { - "none": "2.0.0" - }, - "foo 4.0.0": { - "none": "2.0.0" - }, - "bar 1.0.0": {}, - "bar 2.0.0": {}, - "bar 3.0.0": {}, - "none 1.0.0": {} - }, error: noVersion(["foo", "none"]), maxTries: 2); - - // This sets up a hundred versions of foo and bar, 0.0.0 through 9.9.0. Each - // version of foo depends on a baz with the same major version. Each version - // of bar depends on a baz with the same minor version. There is only one - // version of baz, 0.0.0, so only older versions of foo and bar will - // satisfy it. - var map = { - 'myapp 0.0.0': { - 'foo': 'any', - 'bar': 'any' - }, - 'baz 0.0.0': {} - }; - - for (var i = 0; i < 10; i++) { - for (var j = 0; j < 10; j++) { - map['foo $i.$j.0'] = { - 'baz': '$i.0.0' - }; - map['bar $i.$j.0'] = { - 'baz': '0.$j.0' - }; - } - } - - testResolve('complex backtrack', map, result: { - 'myapp from root': '0.0.0', - 'foo': '0.9.0', - 'bar': '9.0.0', - 'baz': '0.0.0' - }, maxTries: 100); - - // If there's a disjoint constraint on a package, then selecting other - // versions of it is a waste of time: no possible versions can match. We need - // to jump past it to the most recent package that affected the constraint. - testResolve('backjump past failed package on disjoint constraint', { - 'myapp 0.0.0': { - 'a': 'any', - 'foo': '>2.0.0' - }, - 'a 1.0.0': { - 'foo': 'any' // ok - }, - 'a 2.0.0': { - 'foo': '<1.0.0' // disjoint with myapp's constraint on foo - }, - 'foo 2.0.0': {}, - 'foo 2.0.1': {}, - 'foo 2.0.2': {}, - 'foo 2.0.3': {}, - 'foo 2.0.4': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0', - 'foo': '2.0.4' - }, maxTries: 2); - - // This is a regression test for #18666. It was possible for the solver to - // "forget" that a package had previously led to an error. In that case, it - // would backtrack over the failed package instead of trying different - // versions of it. - testResolve("finds solution with less strict constraint", { - "myapp 1.0.0": { - "a": "any", - "c": "any", - "d": "any" - }, - "a 2.0.0": {}, - "a 1.0.0": {}, - "b 1.0.0": { - "a": "1.0.0" - }, - "c 1.0.0": { - "b": "any" - }, - "d 2.0.0": { - "myapp": "any" - }, - "d 1.0.0": { - "myapp": "<1.0.0" - } - }, result: { - 'myapp from root': '1.0.0', - 'a': '1.0.0', - 'b': '1.0.0', - 'c': '1.0.0', - 'd': '2.0.0' - }, maxTries: 3); -} - -sdkConstraint() { - var badVersion = '0.0.0-nope'; - var goodVersion = sdk.version.toString(); - - testResolve('root matches SDK', { - 'myapp 0.0.0': { - 'sdk': goodVersion - } - }, result: { - 'myapp from root': '0.0.0' - }); - - testResolve('root does not match SDK', { - 'myapp 0.0.0': { - 'sdk': badVersion - } - }, error: couldNotSolve); - - testResolve('dependency does not match SDK', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 0.0.0': { - 'sdk': badVersion - } - }, error: couldNotSolve); - - testResolve('transitive dependency does not match SDK', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 0.0.0': { - 'bar': 'any' - }, - 'bar 0.0.0': { - 'sdk': badVersion - } - }, error: couldNotSolve); - - testResolve('selects a dependency version that allows the SDK', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'sdk': goodVersion - }, - 'foo 2.0.0': { - 'sdk': goodVersion - }, - 'foo 3.0.0': { - 'sdk': badVersion - }, - 'foo 4.0.0': { - 'sdk': badVersion - } - }, result: { - 'myapp from root': '0.0.0', - 'foo': '2.0.0' - }, maxTries: 3); - - testResolve('selects a transitive dependency version that allows the SDK', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': 'any' - }, - 'bar 1.0.0': { - 'sdk': goodVersion - }, - 'bar 2.0.0': { - 'sdk': goodVersion - }, - 'bar 3.0.0': { - 'sdk': badVersion - }, - 'bar 4.0.0': { - 'sdk': badVersion - } - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.0', - 'bar': '2.0.0' - }, maxTries: 3); - - testResolve( - 'selects a dependency version that allows a transitive ' - 'dependency that allows the SDK', - { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'foo 2.0.0': { - 'bar': '2.0.0' - }, - 'foo 3.0.0': { - 'bar': '3.0.0' - }, - 'foo 4.0.0': { - 'bar': '4.0.0' - }, - 'bar 1.0.0': { - 'sdk': goodVersion - }, - 'bar 2.0.0': { - 'sdk': goodVersion - }, - 'bar 3.0.0': { - 'sdk': badVersion - }, - 'bar 4.0.0': { - 'sdk': badVersion - } - }, result: { - 'myapp from root': '0.0.0', - 'foo': '2.0.0', - 'bar': '2.0.0' - }, maxTries: 3); -} - -void prerelease() { - testResolve('prefer stable versions over unstable', { - 'myapp 0.0.0': { - 'a': 'any' - }, - 'a 1.0.0': {}, - 'a 1.1.0-dev': {}, - 'a 2.0.0-dev': {}, - 'a 3.0.0-dev': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0' - }); - - testResolve('use latest allowed prerelease if no stable versions match', { - 'myapp 0.0.0': { - 'a': '<2.0.0' - }, - 'a 1.0.0-dev': {}, - 'a 1.1.0-dev': {}, - 'a 1.9.0-dev': {}, - 'a 3.0.0': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.9.0-dev' - }); - - testResolve('use an earlier stable version on a < constraint', { - 'myapp 0.0.0': { - 'a': '<2.0.0' - }, - 'a 1.0.0': {}, - 'a 1.1.0': {}, - 'a 2.0.0-dev': {}, - 'a 2.0.0': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.1.0' - }); - - testResolve('prefer a stable version even if constraint mentions unstable', { - 'myapp 0.0.0': { - 'a': '<=2.0.0-dev' - }, - 'a 1.0.0': {}, - 'a 1.1.0': {}, - 'a 2.0.0-dev': {}, - 'a 2.0.0': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.1.0' - }); -} - -void override() { - testResolve('chooses best version matching override constraint', { - 'myapp 0.0.0': { - 'a': 'any' - }, - 'a 1.0.0': {}, - 'a 2.0.0': {}, - 'a 3.0.0': {} - }, overrides: { - 'a': '<3.0.0' - }, result: { - 'myapp from root': '0.0.0', - 'a': '2.0.0' - }); - - testResolve('uses override as dependency', { - 'myapp 0.0.0': {}, - 'a 1.0.0': {}, - 'a 2.0.0': {}, - 'a 3.0.0': {} - }, overrides: { - 'a': '<3.0.0' - }, result: { - 'myapp from root': '0.0.0', - 'a': '2.0.0' - }); - - testResolve('ignores other constraints on overridden package', { - 'myapp 0.0.0': { - 'b': 'any', - 'c': 'any' - }, - 'a 1.0.0': {}, - 'a 2.0.0': {}, - 'a 3.0.0': {}, - 'b 1.0.0': { - 'a': '1.0.0' - }, - 'c 1.0.0': { - 'a': '3.0.0' - } - }, overrides: { - 'a': '2.0.0' - }, result: { - 'myapp from root': '0.0.0', - 'a': '2.0.0', - 'b': '1.0.0', - 'c': '1.0.0' - }); - - testResolve('backtracks on overidden package for its constraints', { - 'myapp 0.0.0': { - 'shared': '2.0.0' - }, - 'a 1.0.0': { - 'shared': 'any' - }, - 'a 2.0.0': { - 'shared': '1.0.0' - }, - 'shared 1.0.0': {}, - 'shared 2.0.0': {} - }, overrides: { - 'a': '<3.0.0' - }, result: { - 'myapp from root': '0.0.0', - 'a': '1.0.0', - 'shared': '2.0.0' - }, maxTries: 2); - - testResolve('override compatible with locked dependency', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'foo 1.0.1': { - 'bar': '1.0.1' - }, - 'foo 1.0.2': { - 'bar': '1.0.2' - }, - 'bar 1.0.0': {}, - 'bar 1.0.1': {}, - 'bar 1.0.2': {} - }, lockfile: { - 'foo': '1.0.1' - }, overrides: { - 'foo': '<1.0.2' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.1', - 'bar': '1.0.1' - }); - - testResolve('override incompatible with locked dependency', { - 'myapp 0.0.0': { - 'foo': 'any' - }, - 'foo 1.0.0': { - 'bar': '1.0.0' - }, - 'foo 1.0.1': { - 'bar': '1.0.1' - }, - 'foo 1.0.2': { - 'bar': '1.0.2' - }, - 'bar 1.0.0': {}, - 'bar 1.0.1': {}, - 'bar 1.0.2': {} - }, lockfile: { - 'foo': '1.0.1' - }, overrides: { - 'foo': '>1.0.1' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '1.0.2', - 'bar': '1.0.2' - }); - - testResolve('no version that matches override', { - 'myapp 0.0.0': {}, - 'foo 2.0.0': {}, - 'foo 2.1.3': {} - }, overrides: { - 'foo': '>=1.0.0 <2.0.0' - }, error: noVersion(['myapp'])); - - testResolve('override a bad source without error', { - 'myapp 0.0.0': { - 'foo from bad': 'any' - }, - 'foo 0.0.0': {} - }, overrides: { - 'foo': 'any' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '0.0.0' - }); -} - -void downgrade() { - testResolve("downgrades a dependency to the lowest matching version", { - 'myapp 0.0.0': { - 'foo': '>=2.0.0 <3.0.0' - }, - 'foo 1.0.0': {}, - 'foo 2.0.0-dev': {}, - 'foo 2.0.0': {}, - 'foo 2.1.0': {} - }, lockfile: { - 'foo': '2.1.0' - }, result: { - 'myapp from root': '0.0.0', - 'foo': '2.0.0' - }, downgrade: true); - - testResolve( - 'use earliest allowed prerelease if no stable versions match ' - 'while downgrading', - { - 'myapp 0.0.0': { - 'a': '>=2.0.0-dev.1 <3.0.0' - }, - 'a 1.0.0': {}, - 'a 2.0.0-dev.1': {}, - 'a 2.0.0-dev.2': {}, - 'a 2.0.0-dev.3': {} - }, result: { - 'myapp from root': '0.0.0', - 'a': '2.0.0-dev.1' - }, downgrade: true); -} - -testResolve(String description, Map packages, {Map lockfile, Map overrides, - Map result, FailMatcherBuilder error, int maxTries, bool downgrade: false}) { - _testResolve( - test, - description, - packages, - lockfile: lockfile, - overrides: overrides, - result: result, - error: error, - maxTries: maxTries, - downgrade: downgrade); -} - -solo_testResolve(String description, Map packages, {Map lockfile, Map overrides, - Map result, FailMatcherBuilder error, int maxTries, bool downgrade: false}) { - log.verbosity = log.Verbosity.SOLVER; - _testResolve( - solo_test, - description, - packages, - lockfile: lockfile, - overrides: overrides, - result: result, - error: error, - maxTries: maxTries, - downgrade: downgrade); -} - -_testResolve(void testFn(String description, Function body), String description, - Map packages, {Map lockfile, Map overrides, Map result, - FailMatcherBuilder error, int maxTries, bool downgrade: false}) { - if (maxTries == null) maxTries = 1; - - testFn(description, () { - var cache = new SystemCache('.'); - source1 = new MockSource('mock1'); - source2 = new MockSource('mock2'); - cache.register(source1); - cache.register(source2); - cache.sources.setDefault(source1.name); - - // Build the test package graph. - var root; - packages.forEach((description, dependencies) { - var id = parseSpec(description); - var package = - mockPackage(id, dependencies, id.name == 'myapp' ? overrides : null); - if (id.name == 'myapp') { - // Don't add the root package to the server, so we can verify that Pub - // doesn't try to look up information about the local package on the - // remote server. - root = package; - } else { - (cache.sources[id.source] as MockSource).addPackage( - id.description, - package); - } - }); - - // Clean up the expectation. - if (result != null) { - var newResult = {}; - result.forEach((description, version) { - var id = parseSpec(description, version); - newResult[id.name] = id; - }); - result = newResult; - } - - // Parse the lockfile. - var realLockFile = new LockFile.empty(); - if (lockfile != null) { - lockfile.forEach((name, version) { - version = new Version.parse(version); - realLockFile.packages[name] = - new PackageId(name, source1.name, version, name); - }); - } - - // Resolve the versions. - var future = resolveVersions( - downgrade ? SolveType.DOWNGRADE : SolveType.GET, - cache.sources, - root, - lockFile: realLockFile); - - var matcher; - if (result != null) { - matcher = new SolveSuccessMatcher(result, maxTries); - } else if (error != null) { - matcher = error(maxTries); - } - - expect(future, completion(matcher)); - }); -} - -typedef SolveFailMatcher FailMatcherBuilder(int maxTries); - -FailMatcherBuilder noVersion(List packages) { - return (maxTries) => - new SolveFailMatcher(packages, maxTries, NoVersionException); -} - -FailMatcherBuilder disjointConstraint(List packages) { - return (maxTries) => - new SolveFailMatcher(packages, maxTries, DisjointConstraintException); -} - -FailMatcherBuilder descriptionMismatch(String package, String depender1, - String depender2) { - return (maxTries) => - new SolveFailMatcher( - [package, depender1, depender2], - maxTries, - DescriptionMismatchException); -} - -// If no solution can be found, the solver just reports the last failure that -// happened during propagation. Since we don't specify the order that solutions -// are tried, this just validates that *some* failure occurred, but not which. -SolveFailMatcher couldNotSolve(maxTries) => - new SolveFailMatcher([], maxTries, null); - -FailMatcherBuilder sourceMismatch(String package, String depender1, - String depender2) { - return (maxTries) => - new SolveFailMatcher( - [package, depender1, depender2], - maxTries, - SourceMismatchException); -} - -unknownSource(String depender, String dependency, String source) { - return (maxTries) => - new SolveFailMatcher( - [depender, dependency, source], - maxTries, - UnknownSourceException); -} - -class SolveSuccessMatcher implements Matcher { - /// The expected concrete package selections. - final Map _expected; - - /// The maximum number of attempts that should have been tried before finding - /// the solution. - final int _maxTries; - - SolveSuccessMatcher(this._expected, this._maxTries); - - Description describe(Description description) { - return description.add( - 'Solver to use at most $_maxTries attempts to find:\n' - '${_listPackages(_expected.values)}'); - } - - Description describeMismatch(SolveResult result, Description description, - Map state, bool verbose) { - if (!result.succeeded) { - description.add('Solver failed with:\n${result.error}'); - return null; - } - - description.add('Resolved:\n${_listPackages(result.packages)}\n'); - description.add(state['failures']); - return description; - } - - bool matches(SolveResult result, Map state) { - if (!result.succeeded) return false; - - var expected = new Map.from(_expected); - var failures = new StringBuffer(); - - for (var id in result.packages) { - if (!expected.containsKey(id.name)) { - failures.writeln('Should not have selected $id'); - } else { - var expectedId = expected.remove(id.name); - if (id != expectedId) { - failures.writeln('Expected $expectedId, not $id'); - } - } - } - - if (!expected.isEmpty) { - failures.writeln('Missing:\n${_listPackages(expected.values)}'); - } - - // Allow 1 here because the greedy solver will only make one attempt. - if (result.attemptedSolutions != 1 && - result.attemptedSolutions != _maxTries) { - failures.writeln('Took ${result.attemptedSolutions} attempts'); - } - - if (!failures.isEmpty) { - state['failures'] = failures.toString(); - return false; - } - - return true; - } - - String _listPackages(Iterable packages) { - return '- ${packages.join('\n- ')}'; - } -} - -class SolveFailMatcher implements Matcher { - /// The strings that should appear in the resulting error message. - // TODO(rnystrom): This seems to always be package names. Make that explicit. - final Iterable _expected; - - /// The maximum number of attempts that should be tried before failing. - final int _maxTries; - - /// The concrete error type that should be found, or `null` if any - /// [SolveFailure] is allowed. - final Type _expectedType; - - SolveFailMatcher(this._expected, this._maxTries, this._expectedType); - - Description describe(Description description) { - description.add('Solver should fail after at most $_maxTries attempts.'); - if (!_expected.isEmpty) { - var textList = _expected.map((s) => '"$s"').join(", "); - description.add(' The error should contain $textList.'); - } - return description; - } - - Description describeMismatch(SolveResult result, Description description, - Map state, bool verbose) { - description.add(state['failures']); - return description; - } - - bool matches(SolveResult result, Map state) { - var failures = new StringBuffer(); - - if (result.succeeded) { - failures.writeln('Solver succeeded'); - } else { - if (_expectedType != null && result.error.runtimeType != _expectedType) { - failures.writeln( - 'Should have error type $_expectedType, got ' '${result.error.runtimeType}'); - } - - var message = result.error.toString(); - for (var expected in _expected) { - if (!message.contains(expected)) { - failures.writeln( - 'Expected error to contain "$expected", got:\n$message'); - } - } - - // Allow 1 here because the greedy solver will only make one attempt. - if (result.attemptedSolutions != 1 && - result.attemptedSolutions != _maxTries) { - failures.writeln('Took ${result.attemptedSolutions} attempts'); - } - } - - if (!failures.isEmpty) { - state['failures'] = failures.toString(); - return false; - } - - return true; - } -} - -/// A source used for testing. This both creates mock package objects and acts -/// as a source for them. -/// -/// In order to support testing packages that have the same name but different -/// descriptions, a package's name is calculated by taking the description -/// string and stripping off any trailing hyphen followed by non-hyphen -/// characters. -class MockSource extends CachedSource { - final _packages = >{}; - - /// Keeps track of which package version lists have been requested. Ensures - /// that a source is only hit once for a given package and that pub - /// internally caches the results. - final _requestedVersions = new Set(); - - /// Keeps track of which package pubspecs have been requested. Ensures that a - /// source is only hit once for a given package and that pub internally - /// caches the results. - final _requestedPubspecs = new Map>(); - - final String name; - final hasMultipleVersions = true; - - MockSource(this.name); - - dynamic parseDescription(String containingPath, description, - {bool fromLockFile: false}) => - description; - - bool descriptionsEqual(description1, description2) => - description1 == description2; - - Future getDirectory(PackageId id) { - return new Future.value('${id.name}-${id.version}'); - } - - Future> getVersions(String name, String description) { - return new Future.sync(() { - // Make sure the solver doesn't request the same thing twice. - if (_requestedVersions.contains(description)) { - throw new Exception( - 'Version list for $description was already ' 'requested.'); - } - - _requestedVersions.add(description); - - if (!_packages.containsKey(description)) { - throw new Exception( - 'MockSource does not have a package matching ' '"$description".'); - } - - return _packages[description].keys.toList(); - }); - } - - Future describeUncached(PackageId id) { - return new Future.sync(() { - // Make sure the solver doesn't request the same thing twice. - if (_requestedPubspecs.containsKey(id.description) && - _requestedPubspecs[id.description].contains(id.version)) { - throw new Exception('Pubspec for $id was already requested.'); - } - - _requestedPubspecs.putIfAbsent(id.description, () => new Set()); - _requestedPubspecs[id.description].add(id.version); - - return _packages[id.description][id.version].pubspec; - }); - } - - Future downloadToSystemCache(PackageId id) => - throw new UnsupportedError('Cannot download mock packages'); - - List getCachedPackages() => - throw new UnsupportedError('Cannot get mock packages'); - - Future> repairCachedPackages() => - throw new UnsupportedError('Cannot repair mock packages'); - - void addPackage(String description, Package package) { - _packages.putIfAbsent(description, () => new Map()); - _packages[description][package.version] = package; - } -} - -Package mockPackage(PackageId id, Map dependencyStrings, Map overrides) { - var sdkConstraint = null; - - // Build the pubspec dependencies. - var dependencies = []; - var devDependencies = []; - - dependencyStrings.forEach((spec, constraint) { - var isDev = spec.startsWith("(dev) "); - if (isDev) { - spec = spec.substring("(dev) ".length); - } - - var dep = - parseSpec(spec).withConstraint(new VersionConstraint.parse(constraint)); - - if (dep.name == 'sdk') { - sdkConstraint = dep.constraint; - return; - } - - if (isDev) { - devDependencies.add(dep); - } else { - dependencies.add(dep); - } - }); - - var dependencyOverrides = []; - if (overrides != null) { - overrides.forEach((spec, constraint) { - dependencyOverrides.add( - parseSpec(spec).withConstraint(new VersionConstraint.parse(constraint))); - }); - } - - return new Package.inMemory( - new Pubspec( - id.name, - version: id.version, - dependencies: dependencies, - devDependencies: devDependencies, - dependencyOverrides: dependencyOverrides, - sdkConstraint: sdkConstraint)); -} - -/// Creates a new [PackageId] parsed from [text], which looks something like -/// this: -/// -/// foo-xyz 1.0.0 from mock -/// -/// The package name is "foo". A hyphenated suffix like "-xyz" here is part -/// of the package description, but not its name, so the description here is -/// "foo-xyz". -/// -/// This is followed by an optional [Version]. If [version] is provided, then -/// it is parsed to a [Version], and [text] should *not* also contain a -/// version string. -/// -/// The "from mock" optional suffix is the name of a source for the package. -/// If omitted, it defaults to "mock1". -PackageId parseSpec(String text, [String version]) { - var pattern = new RegExp(r"(([a-z_]*)(-[a-z_]+)?)( ([^ ]+))?( from (.*))?$"); - var match = pattern.firstMatch(text); - if (match == null) { - throw new FormatException("Could not parse spec '$text'."); - } - - var description = match[1]; - var name = match[2]; - - var parsedVersion; - if (version != null) { - // Spec string shouldn't also contain a version. - if (match[5] != null) { - throw new ArgumentError( - "Spec '$text' should not contain a version " - "since '$version' was passed in explicitly."); - } - parsedVersion = new Version.parse(version); - } else { - if (match[5] != null) { - parsedVersion = new Version.parse(match[5]); - } else { - parsedVersion = Version.none; - } - } - - var source = "mock1"; - if (match[7] != null) { - source = match[7]; - if (source == "root") source = null; - } - - return new PackageId(name, source, parsedVersion, description); -} diff --git a/tests/lib/analyzer/analyze_library.status b/tests/lib/analyzer/analyze_library.status index e48684e159f..5d72855b2a8 100644 --- a/tests/lib/analyzer/analyze_library.status +++ b/tests/lib/analyzer/analyze_library.status @@ -16,14 +16,6 @@ lib/web_audio/dart2js/web_audio_dart2js: CompileTimeError # Issue 16522 lib/web_gl/dart2js/web_gl_dart2js: CompileTimeError # Issue 16522 lib/web_sql/dart2js/web_sql_dart2js: CompileTimeError # Issue 16522 -# The async_await compiler isn't part of the repo so it shouldn't be tested by -# repo tests. -lib/_internal/pub_generated/bin/async_compile: Skip - -# Pub is starting to use the new async syntax, which isn't supported on the -# analyzer bots yet. -lib/_internal/pub/*: Pass, CompileTimeError - [ $compiler == dart2analyzer ] lib/web_gl/dartium/web_gl_dartium: CompileTimeError # Issue 21647 lib/web_sql/dartium/web_sql_dartium: CompileTimeError # Issue 21647 diff --git a/tools/run_pub.py b/tools/run_pub.py index e11701d0cc1..c43b0396d85 100755 --- a/tools/run_pub.py +++ b/tools/run_pub.py @@ -12,8 +12,7 @@ import sys SCRIPT_DIR = os.path.dirname(sys.argv[0]) DART_ROOT = os.path.realpath(os.path.join(SCRIPT_DIR, '..')) -PUB_PATH = os.path.join(DART_ROOT, - 'sdk/lib/_internal/pub_generated/bin/pub.dart') +PUB_PATH = os.path.join(DART_ROOT, 'sdk/lib/_internal/pub/bin/pub.dart') CANARY_PATH = os.path.join(DART_ROOT, 'tools', 'canary.dart') usage = """run_pub.py --package-root=""" @@ -102,4 +101,4 @@ def main(): if __name__ == '__main__': - sys.exit(main()); \ No newline at end of file + sys.exit(main()) diff --git a/tools/status_clean.dart b/tools/status_clean.dart index 14b0f79d932..fb975907ef7 100644 --- a/tools/status_clean.dart +++ b/tools/status_clean.dart @@ -36,8 +36,7 @@ final STATUS_TUPLES = [ "tests/compiler/dart2js_native/dart2js_native.status"], ["dart2js", "tests/compiler/dart2js", "tests/compiler/dart2js/dart2js.status"], - ["pub", "sdk/lib/_internal/pub_generated", - "sdk/lib/_internal/pub/pub.status"], + ["pub", "sdk/lib/_internal/pub", "sdk/lib/_internal/pub/pub.status"], ["benchmark_smoke", "tests/benchmark_smoke", "tests/benchmark_smoke/benchmark_smoke.status"], ["co19", "tests/co19/src", "tests/co19/co19-analyzer2.status"], diff --git a/tools/testing/dart/test_configurations.dart b/tools/testing/dart/test_configurations.dart index 6edd93c7ef1..c49bfcaf231 100644 --- a/tools/testing/dart/test_configurations.dart +++ b/tools/testing/dart/test_configurations.dart @@ -199,7 +199,7 @@ void testConfigurations(List configurations) { // TODO(rnystrom): Move pub back into TEST_SUITE_DIRECTORIES once // #104 is fixed. testSuites.add(new StandardTestSuite(conf, 'pub', - new Path('sdk/lib/_internal/pub_generated'), + new Path('sdk/lib/_internal/pub'), ['sdk/lib/_internal/pub/pub.status'], isTestFilePredicate: (file) => file.endsWith('_test.dart'), recursive: true)); diff --git a/utils/pub/pub.gyp b/utils/pub/pub.gyp index d75a3956e4a..13d0b09e315 100644 --- a/utils/pub/pub.gyp +++ b/utils/pub/pub.gyp @@ -32,7 +32,7 @@ '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)', '--package-root=<(PRODUCT_DIR)/packages/', '--snapshot=<(SHARED_INTERMEDIATE_DIR)/pub.dart.snapshot', - '../../sdk/lib/_internal/pub_generated/bin/pub.dart', + '../../sdk/lib/_internal/pub/bin/pub.dart', ] }, ], @@ -78,7 +78,7 @@ 'inputs': [ '../../tools/create_timestamp_file.py', '